Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter as DoctrineOrmAbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Elasticsearch\DataProvider\Extension\RequestBodySearchCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction\PropertySchemaRestrictionMetadataInterface;
use ApiPlatform\Core\DataPersister\DataPersisterInterface;
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
Expand Down Expand Up @@ -553,6 +554,8 @@ private function registerValidatorConfiguration(ContainerBuilder $container, arr
{
if (interface_exists(ValidatorInterface::class)) {
$loader->load('validator.xml');
$container->registerForAutoconfiguration(PropertySchemaRestrictionMetadataInterface::class)
->addTag('api_platform.metadata.property_schema_restriction');
}

if (!$config['validator']) {
Expand Down
13 changes: 13 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/validator.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@
<service id="api_platform.metadata.property.metadata_factory.validator" class="ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\ValidatorPropertyMetadataFactory" decorates="api_platform.metadata.property.metadata_factory" decoration-priority="20" public="false">
<argument type="service" id="validator" />
<argument type="service" id="api_platform.metadata.property.metadata_factory.validator.inner" />
<argument type="tagged" tag="api_platform.metadata.property_schema_restriction" />
</service>

<service id="api_platform.metadata.property_schema.length_restriction" class="ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction\PropertySchemaLengthRestriction" public="false">
<tag name="api_platform.metadata.property_schema_restriction"/>
</service>

<service id="api_platform.metadata.property_schema.regex_restriction" class="ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction\PropertySchemaRegexRestriction" public="false">
<tag name="api_platform.metadata.property_schema_restriction"/>
</service>

<service id="api_platform.metadata.property_schema.format_restriction" class="ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction\PropertySchemaFormat" public="false">
<tag name="api_platform.metadata.property_schema_restriction"/>
</service>

<service id="api_platform.listener.view.validate" class="ApiPlatform\Core\Validator\EventListener\ValidateListener">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction;

use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Ip;
use Symfony\Component\Validator\Constraints\Uuid;

/**
* Class PropertySchemaFormat.
*
* @author Andrii Penchuk penja7@gmail.com
*/
class PropertySchemaFormat implements PropertySchemaRestrictionMetadataInterface
{
/**
* {@inheritdoc}
*/
public function create(Constraint $constraint, PropertyMetadata $propertyMetadata): array
{
if ($constraint instanceof Email) {
return ['format' => 'email'];
}

if ($constraint instanceof Uuid) {
return ['format' => 'uuid'];
}

if ($constraint instanceof Ip) {
if ($constraint->version === $constraint::V4) {
return ['format' => 'ipv4'];
}

return ['format' => 'ipv6'];
}

return [];
}

/**
* {@inheritdoc}
*/
public function supports(Constraint $constraint, PropertyMetadata $propertyMetadata): bool
{
$schema = $propertyMetadata->getSchema();

return empty($schema['format']);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction;

use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Length;

/**
* Class PropertySchemaLengthRestrictions.
*
* @author Andrii Penchuk penja7@gmail.com
*/
class PropertySchemaLengthRestriction implements PropertySchemaRestrictionMetadataInterface
{
/**
* {@inheritdoc}
*/
public function create(Constraint $constraint, PropertyMetadata $propertyMetadata): array
{
$restriction = [];

switch ($propertyMetadata->getType()->getBuiltinType()) {
case Type::BUILTIN_TYPE_STRING:

if (isset($constraint->min)) {
$restriction['minLength'] = (int) $constraint->min;
}

if (isset($constraint->max)) {
$restriction['maxLength'] = (int) $constraint->max;
}

break;
case Type::BUILTIN_TYPE_INT:
case Type::BUILTIN_TYPE_FLOAT:
if (isset($constraint->min)) {
$restriction['minimum'] = (int) $constraint->min;
}

if (isset($constraint->max)) {
$restriction['maximum'] = (int) $constraint->max;
}
Comment on lines +47 to +55

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This part looks wrong. Length is a string constraint. There seems to be confusion with Range, implemented in #4158

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

That's right. Could you provide a PR to fix it?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PR: #4177

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PS: thanks @penja for implementing this feature!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@guilliamxavier thanks for fix


break;
}

return $restriction;
}

/**
* {@inheritdoc}
*/
public function supports(Constraint $constraint, PropertyMetadata $propertyMetadata): bool
{
return $constraint instanceof Length && null !== $propertyMetadata->getType();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction;

use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Regex;

/**
* Class PropertySchemaRegexRestriction.
*
* @author Andrii Penchuk penja7@gmail.com
*/
class PropertySchemaRegexRestriction implements PropertySchemaRestrictionMetadataInterface
{
/**
* {@inheritdoc}
*/
public function create(Constraint $constraint, PropertyMetadata $propertyMetadata): array
{
return isset($constraint->pattern) ? ['pattern' => $constraint->pattern] : [];
}

/**
* {@inheritdoc}
*/
public function supports(Constraint $constraint, PropertyMetadata $propertyMetadata): bool
{
return $constraint instanceof Regex && $constraint->match;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction;

use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use Symfony\Component\Validator\Constraint;

/**
* Interface PropertySchemaRestrictionsInterface.
*
* @author Andrii Penchuk penja7@gmail.com
*/
interface PropertySchemaRestrictionMetadataInterface
{
/**
* Creates json schema restrictions based on the validation constraints.
*
* @param Constraint $constraint The validation constraint
* @param PropertyMetadata $propertyMetadata The property metadata
*
* @return array The array of restrictions
*/
public function create(Constraint $constraint, PropertyMetadata $propertyMetadata): array;

/**
* Is the constraint supported by the schema restriction?
*
* @param Constraint $constraint The validation constraint
* @param PropertyMetadata $propertyMetadata The property metadata
*/
public function supports(Constraint $constraint, PropertyMetadata $propertyMetadata): bool;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property;

use ApiPlatform\Core\Bridge\Symfony\Validator\Metadata\Property\Restriction\PropertySchemaRestrictionMetadataInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use Symfony\Component\Validator\Constraint;
Expand Down Expand Up @@ -67,11 +68,19 @@ final class ValidatorPropertyMetadataFactory implements PropertyMetadataFactoryI

private $decorated;
private $validatorMetadataFactory;
/**
* @var iterable<PropertySchemaRestrictionMetadataInterface>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you move it to the constructor please?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

fixed

*/
private $restrictionsMetadata;

public function __construct(ValidatorMetadataFactoryInterface $validatorMetadataFactory, PropertyMetadataFactoryInterface $decorated)
/**
* @param PropertySchemaRestrictionMetadataInterface[] $restrictionsMetadata
*/
public function __construct(ValidatorMetadataFactoryInterface $validatorMetadataFactory, PropertyMetadataFactoryInterface $decorated, iterable $restrictionsMetadata = [])
{
$this->validatorMetadataFactory = $validatorMetadataFactory;
$this->decorated = $decorated;
$this->restrictionsMetadata = $restrictionsMetadata;
}

/**
Expand All @@ -83,26 +92,23 @@ public function create(string $resourceClass, string $name, array $options = [])

$required = $propertyMetadata->isRequired();
$iri = $propertyMetadata->getIri();
$schema = $propertyMetadata->getSchema();

if (null !== $required && null !== $iri) {
if (null !== $required && null !== $iri && null !== $schema) {
return $propertyMetadata;
}

$validatorClassMetadata = $this->validatorMetadataFactory->getMetadataFor($resourceClass);

if (!$validatorClassMetadata instanceof ValidatorClassMetadataInterface) {
throw new \UnexpectedValueException(sprintf('Validator class metadata expected to be of type "%s".', ValidatorClassMetadataInterface::class));
}

foreach ($validatorClassMetadata->getPropertyMetadata($name) as $validatorPropertyMetadata) {
if (null === $required && isset($options['validation_groups'])) {
$required = $this->isRequiredByGroups($validatorPropertyMetadata, $options);
}

if (!method_exists($validatorClassMetadata, 'getDefaultGroup')) {
throw new \UnexpectedValueException(sprintf('Validator class metadata expected to have method "%s".', 'getDefaultGroup'));
}
$validationGroups = $this->getValidationGroups($validatorClassMetadata, $options);
$restrictions = [];

foreach ($validatorPropertyMetadata->findConstraints($validatorClassMetadata->getDefaultGroup()) as $constraint) {
foreach ($validatorClassMetadata->getPropertyMetadata($name) as $validatorPropertyMetadata) {
foreach ($this->getPropertyConstraints($validatorPropertyMetadata, $validationGroups) as $constraint) {
if (null === $required && $this->isRequired($constraint)) {
$required = true;
}
Expand All @@ -111,33 +117,64 @@ public function create(string $resourceClass, string $name, array $options = [])
$iri = self::SCHEMA_MAPPED_CONSTRAINTS[\get_class($constraint)] ?? null;
}

if (null !== $required && null !== $iri) {
break 2;
foreach ($this->restrictionsMetadata as $restrictionMetadata) {
if ($restrictionMetadata->supports($constraint, $propertyMetadata)) {
$restrictions[] = $restrictionMetadata->create($constraint, $propertyMetadata);
}
}
}
}

return $propertyMetadata->withIri($iri)->withRequired($required ?? false);
$propertyMetadata = $propertyMetadata->withIri($iri)->withRequired($required ?? false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We don't break the above loop anymore, and it looks like we can have multiple constraints, hence different iris? I'm not sure that this case is handled / implemented correctly.

@penja penja Jan 8, 2020

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@soyuka Like in previous implementation we continue to set IRI and required only if it was not set before.


if (!empty($restrictions)) {
if (null === $schema) {
$schema = [];
}

$schema += array_merge(...$restrictions);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we really need this spread operator / array_merge?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes we must merge all restrictions into one schema

$propertyMetadata = $propertyMetadata->withSchema($schema);
}

return $propertyMetadata;
}

/**
* Tests if the property is required because of its validation groups.
* Returns the list of validation groups.
*/
private function isRequiredByGroups(ValidatorPropertyMetadataInterface $validatorPropertyMetadata, array $options): bool
private function getValidationGroups(ValidatorClassMetadataInterface $classMetadata, array $options): array
{
foreach ($options['validation_groups'] as $validationGroup) {
if (isset($options['validation_groups'])) {
return $options['validation_groups'];
}

if (!method_exists($classMetadata, 'getDefaultGroup')) {
throw new \UnexpectedValueException(sprintf('Validator class metadata expected to have method "%s".', 'getDefaultGroup'));
}

return [$classMetadata->getDefaultGroup()];
}

/**
* Tests if the property is required because of its validation groups.
*/
private function getPropertyConstraints(
ValidatorPropertyMetadataInterface $validatorPropertyMetadata,
array $groups
): array {
$constraints = [];

foreach ($groups as $validationGroup) {
if (!\is_string($validationGroup)) {
continue;
}

foreach ($validatorPropertyMetadata->findConstraints($validationGroup) as $constraint) {
if ($this->isRequired($constraint)) {
return true;
}
foreach ($validatorPropertyMetadata->findConstraints($validationGroup) as $propertyConstraint) {
$constraints[] = $propertyConstraint;
}
}

return false;
return $constraints;
}

/**
Expand Down
Loading