Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support minProperties and maxProperties on objects #53

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ SHELL := /bin/bash

.PHONY: test autoload composer

HHVM_VERSION=4.80.5
HHVM_NEXT_VERSION=4.80.5
HHVM_VERSION=4.102.2
HHVM_NEXT_VERSION=4.102.2
Comment on lines +5 to +6
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i noticed @sarahhenkens also updated HHVM_VERSION in her PR #52, should we also update HHVM_NEXT_VERSION? i wasn't 100% sure if they should always match

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm I think we should probably update this to 4.121?


DOCKER_RUN=docker run -v $(shell pwd):/data --workdir /data --rm hhvm/hhvm:$(HHVM_VERSION)
CONTAINER_NAME=hack-json-schema-hhvm
Expand Down
53 changes: 53 additions & 0 deletions src/Codegen/Constraints/ObjectBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
?'additionalProperties' => mixed,
?'patternProperties' => dict<string, TSchema>,
?'coerce' => bool,
?'minProperties' => int,
?'maxProperties' => int,
...
);

Expand Down Expand Up @@ -74,6 +76,34 @@ public function build(): this {
->setValue($hb->getCode(), HackBuilderValues::literal());
}

$max_properties = $this->typed_schema['maxProperties'] ?? null;
if ($max_properties is nonnull) {
if ($max_properties < 0) {
throw new \Exception('maxProperties must be a non-negative integer');
}

$class_properties[] = $this->codegenProperty('maxProperties')
->setType('int')
->setValue($max_properties, HackBuilderValues::export());
}

$min_properties = $this->typed_schema['minProperties'] ?? null;
if ($min_properties is nonnull) {
if ($min_properties < 0) {
throw new \Exception('minProperties must be a non-negative integer');
}

$class_properties[] = $this->codegenProperty('minProperties')
->setType('int')
->setValue($min_properties, HackBuilderValues::export());
}

if ($min_properties is nonnull && $max_properties is nonnull) {
if ($min_properties > $max_properties) {
throw new \Exception('maxProperties must be greater than minProperties');
}
}

$class->addProperties($class_properties);
$this->addBuilderClass($class);

Expand Down Expand Up @@ -132,6 +162,29 @@ protected function getCheckMethodCode(
$include_error_handling = true;
}

$max_properties = $this->typed_schema['maxProperties'] ?? null;
$min_properties = $this->typed_schema['minProperties'] ?? null;
Comment on lines +165 to +166
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

someone asked about whether we should validate if these integers are non-negative. i noticed we don't validate that for StringMinLengthConstraint or ArrayMinItemsConstraint - is there a reason/context for that?

if we were to add that check for objects, i'm trying to figure out where the best place for it would be so that it'd error out for the developer trying to generate a schema with negative min/max numbers. doesn't seem like the getCheckMethod is the right place.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wasn't intentional that we left those off, just didn't get around to it. I'd add it anywhere in this codegen path, maybe above where you set the class properties?

Copy link
Contributor Author

@betsyalegria betsyalegria Oct 12, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay, sounds good - i added checks for those above in the build method & tested that it throws an error when trying to generate a file that has invalid min/max values.


if ($max_properties is nonnull || $min_properties is nonnull) {
$hb->addAssignment('$length', '\HH\Lib\C\count($typed)', HackBuilderValues::literal())->ensureEmptyLine();
}

if ($max_properties is nonnull) {
$hb->addMultilineCall(
'Constraints\ObjectMaxPropertiesConstraint::check',
vec['$length', 'self::$maxProperties', '$pointer'],
)
->ensureEmptyLine();
}

if ($min_properties is nonnull) {
$hb->addMultilineCall(
'Constraints\ObjectMinPropertiesConstraint::check',
vec['$length', 'self::$minProperties', '$pointer'],
)
->ensureEmptyLine();
}

$defaults = $this->getDefaults();
if (!C\is_empty($defaults)) {
$hb->ensureEmptyLine();
Expand Down
22 changes: 22 additions & 0 deletions src/Constraints/ObjectMaxPropertiesConstraint.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?hh // strict

namespace Slack\Hack\JsonSchema\Constraints;

use namespace Slack\Hack\JsonSchema;

class ObjectMaxPropertiesConstraint {
public static function check(int $num_properties, int $max_properties, string $pointer): void {
if ($num_properties > $max_properties) {
$error = shape(
'code' => JsonSchema\FieldErrorCode::FAILED_CONSTRAINT,
'constraint' => shape(
'type' => JsonSchema\FieldErrorConstraint::MAX_PROPERTIES,
'expected' => $max_properties,
'got' => $num_properties,
),
'message' => "no more than {$max_properties} properties allowed",
);
throw new JsonSchema\InvalidFieldException($pointer, vec[$error]);
}
}
}
22 changes: 22 additions & 0 deletions src/Constraints/ObjectMinPropertiesConstraint.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?hh // strict

namespace Slack\Hack\JsonSchema\Constraints;

use namespace Slack\Hack\JsonSchema;

class ObjectMinPropertiesConstraint {
public static function check(int $num_properties, int $min_properties, string $pointer): void {
if ($num_properties < $min_properties) {
$error = shape(
'code' => JsonSchema\FieldErrorCode::FAILED_CONSTRAINT,
'constraint' => shape(
'type' => JsonSchema\FieldErrorConstraint::MIN_PROPERTIES,
'expected' => $min_properties,
'got' => $num_properties,
),
'message' => "must have minimum {$min_properties} properties",
);
throw new JsonSchema\InvalidFieldException($pointer, vec[$error]);
}
}
}
2 changes: 2 additions & 0 deletions src/Exceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ enum FieldErrorConstraint: string {
MAX_ITEMS = 'max_items';
MAX_LENGTH = 'max_length';
MIN_LENGTH = 'min_length';
MAX_PROPERTIES = 'max_properties';
MIN_PROPERTIES = 'min_properties';
MAXIMUM = 'maximum';
MINIMUM = 'minimum';
MULTIPLE_OF = 'multiple_of';
Expand Down
162 changes: 162 additions & 0 deletions tests/ObjectSchemaValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use namespace Facebook\TypeAssert;
use function Facebook\FBExpect\expect;

use type Slack\Hack\JsonSchema\{FieldErrorCode, FieldErrorConstraint};
use type Slack\Hack\JsonSchema\Tests\Generated\ObjectSchemaValidator;

final class ObjectSchemaValidatorTest extends BaseCodegenTestCase {
Expand Down Expand Up @@ -530,4 +531,165 @@ public function testAdditionalProperitesRef(): void {
expect($validator->isValid())->toBeFalse();
}

public function testMinPropertiesWithValidLength(): void {
$validator = new ObjectSchemaValidator(dict[
'only_min_properties' => dict[
'a' => 0,
],
]);

$validator->validate();
expect($validator->isValid())->toBeTrue();
}

public function testMinPropertiesWithInvalidLength(): void {
$validator = new ObjectSchemaValidator(dict[
'only_min_properties' => dict[],
]);

$validator->validate();
expect($validator->isValid())->toBeFalse();

$errors = $validator->getErrors();
expect(C\count($errors))->toEqual(1);

$error = C\firstx($errors);
expect($error['code'])->toEqual(FieldErrorCode::FAILED_CONSTRAINT);
expect($error['message'])->toEqual('must have minimum 1 properties');

$constraint = Shapes::at($error, 'constraint');
expect($constraint['type'])->toEqual(FieldErrorConstraint::MIN_PROPERTIES);
expect($constraint['got'] ?? null)->toEqual(0);
}

public function testMaxPropertiesWithValidLength(): void {
// maxProperties is set to 1, so having 1 value should be fine
$validator = new ObjectSchemaValidator(dict[
'only_max_properties' => dict[
'a' => 0,
],
]);

$validator->validate();
expect($validator->isValid())->toBeTrue();

// maxProperties is set to 1, so having no values should also be fine
$validator = new ObjectSchemaValidator(dict[
'only_max_properties' => dict[],
]);

$validator->validate();
expect($validator->isValid())->toBeTrue();
}

public function testMaxPropertiesWithInvalidLength(): void {
$validator = new ObjectSchemaValidator(dict[
'only_max_properties' => dict[
'a' => 0,
'b' => 1,
],
]);

$validator->validate();
expect($validator->isValid())->toBeFalse();

$errors = $validator->getErrors();
expect(C\count($errors))->toEqual(1);

$error = C\firstx($errors);
expect($error['code'])->toEqual(FieldErrorCode::FAILED_CONSTRAINT);
expect($error['message'])->toEqual('no more than 1 properties allowed');

$constraint = Shapes::at($error, 'constraint');
expect($constraint['type'])->toEqual(FieldErrorConstraint::MAX_PROPERTIES);
expect($constraint['got'] ?? null)->toEqual(2);
}

public function testMinAndMaxPropertiesWithValidLength(): void {
$validator = new ObjectSchemaValidator(dict[
'min_and_max_properties' => dict[
'a' => 0,
],
]);

$validator->validate();
expect($validator->isValid())->toBeTrue();

$validator = new ObjectSchemaValidator(dict[
'min_and_max_properties' => dict[
'a' => 0,
'b' => 1,
],
]);

$validator->validate();
expect($validator->isValid())->toBeTrue();
}

public function testMinAndMaxPropertiesWithInvalidLength(): void {
// minProperties is set to 1, violate it
$validator = new ObjectSchemaValidator(dict[
'min_and_max_properties' => dict[],
]);

$validator->validate();
expect($validator->isValid())->toBeFalse();

$errors = $validator->getErrors();
expect(C\count($errors))->toEqual(1);

$error = C\firstx($errors);
expect($error['code'])->toEqual(FieldErrorCode::FAILED_CONSTRAINT);
expect($error['message'])->toEqual('must have minimum 1 properties');

$constraint = Shapes::at($error, 'constraint');
expect($constraint['type'])->toEqual(FieldErrorConstraint::MIN_PROPERTIES);
expect($constraint['got'] ?? null)->toEqual(0);

// maxProperties is set to 2, violate it
$validator = new ObjectSchemaValidator(dict[
'min_and_max_properties' => dict[
'a' => 0,
'b' => 1,
'c' => 2,
],
]);

$validator->validate();
expect($validator->isValid())->toBeFalse();

$errors = $validator->getErrors();
expect(C\count($errors))->toEqual(1);

$error = C\firstx($errors);
expect($error['code'])->toEqual(FieldErrorCode::FAILED_CONSTRAINT);
expect($error['message'])->toEqual('no more than 2 properties allowed');

$constraint = Shapes::at($error, 'constraint');
expect($constraint['type'])->toEqual(FieldErrorConstraint::MAX_PROPERTIES);
expect($constraint['got'] ?? null)->toEqual(3);
}

public function testInvalidMinPropertiesWithNoAdditionalProperties(): void {
$validator = new ObjectSchemaValidator(dict[
'invalid_min_properties_with_no_additional_properties' => dict[
'a' => 0,
],
]);

$validator->validate();
expect($validator->isValid())->toBeFalse();

$errors = $validator->getErrors();
expect(C\count($errors))->toEqual(1);

$error = C\firstx($errors);
expect($error['code'])->toEqual(FieldErrorCode::FAILED_CONSTRAINT);
expect($error['message'])->toEqual('invalid additional property: a');

$constraint = Shapes::at($error, 'constraint');
expect($constraint['type'])->toEqual(FieldErrorConstraint::ADDITIONAL_PROPERTIES);
expect($constraint['got'] ?? null)->toEqual('a');
}

}
Loading