Thanks to visit codestin.com
Credit goes to github.com

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
12 changes: 8 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ on:
push:
pull_request:

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
COMPOSER_TOKEN: ${{ secrets.GITHUB_TOKEN }}
COVERAGE: '0'
Expand Down Expand Up @@ -373,7 +377,7 @@ jobs:
run: tests/Fixtures/app/console cache:clear --ansi
- name: Run Behat tests
run: |
vendor/bin/behat --out=std --format=progress --profile=postgres --no-interaction -vv --tags='~php8'
vendor/bin/behat --out=std --format=progress --profile=postgres --no-interaction -vv

mysql:
name: Behat (PHP ${{ matrix.php }}) (MySQL)
Expand Down Expand Up @@ -422,7 +426,7 @@ jobs:
- name: Clear test app cache
run: tests/Fixtures/app/console cache:clear --ansi
- name: Run Behat tests
run: vendor/bin/behat --out=std --format=progress --profile=default --no-interaction --tags '~@!mysql&&~@php8'
run: vendor/bin/behat --out=std --format=progress --profile=default --no-interaction --tags '~@!mysql'

mongodb:
name: PHPUnit + Behat (PHP ${{ matrix.php }}) (MongoDB)
Expand Down Expand Up @@ -481,9 +485,9 @@ jobs:
run: |
mkdir -p build/logs/behat
if [ "$COVERAGE" = '1' ]; then
vendor/bin/behat --out=std --format=progress --format=junit --out=build/logs/behat/junit --profile=mongodb-coverage --no-interaction --tags='~@php8'
vendor/bin/behat --out=std --format=progress --format=junit --out=build/logs/behat/junit --profile=mongodb-coverage --no-interaction
else
vendor/bin/behat --out=std --format=progress --format=junit --out=build/logs/behat/junit --profile=mongodb --no-interaction --tags='~@php8'
vendor/bin/behat --out=std --format=progress --format=junit --out=build/logs/behat/junit --profile=mongodb --no-interaction
fi
- name: Merge code coverage reports
run: |
Expand Down
2 changes: 1 addition & 1 deletion features/hydra/item_uri_template.feature
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@php8
@!mongodb
@v3
Feature: Exposing a collection of objects should use the specified operation to generate the IRI

Expand Down
11 changes: 10 additions & 1 deletion features/main/attribute_resource.feature
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,17 @@ Feature: Resource attributes

Scenario: Uri variables with Post operation
When I add "Content-Type" header equal to "application/ld+json"
And I send a "POST" request to "/post_with_uri_variables/{id}" with body:
And I send a "POST" request to "/post_with_uri_variables_and_no_provider/{id}" with body:
"""
{}
"""
Then the response status code should be 201

Scenario: Throw validation exception in a provider
When I add "Content-Type" header equal to "application/ld+json"
And I send a "POST" request to "/post_with_uri_variables/{id}" with body:
"""
{}
"""
Then the response status code should be 422

5 changes: 5 additions & 0 deletions features/main/composite.feature
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,8 @@ Feature: Retrieve data with Composite identifiers
Then the response status code should be 200
And the response should be in JSON
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"

Scenario: Get identifiers with different types
Given there are Composite identifier objects
When I send a "GET" request to "/composite_key_with_different_types/id=82133;verificationKey=7d75af772e637e45c36d041696e1128d"
Then the response status code should be 200
15 changes: 13 additions & 2 deletions src/Api/UriVariablesConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public function __construct(private readonly PropertyMetadataFactoryInterface $p

/**
* {@inheritdoc}
*
* To handle the composite identifiers type correctly, use an `uri_variables_map` that maps uriVariables to their uriVariablesDefinition.
* Indeed, a composite identifier will already be parsed, and their corresponding properties will be the parameterName and not the defined
* identifiers.
*/
public function convert(array $uriVariables, string $class, array $context = []): array
{
Expand All @@ -43,8 +47,15 @@ public function convert(array $uriVariables, string $class, array $context = [])
$uriVariablesDefinitions = $operation->getUriVariables() ?? [];

foreach ($uriVariables as $parameterName => $value) {
$uriVariableDefinition = $uriVariablesDefinitions[$parameterName] ?? $uriVariablesDefinitions['id'] ?? new Link();
if ([] === $types = $this->getIdentifierTypes($uriVariableDefinition->getFromClass() ?? $class, $uriVariableDefinition->getIdentifiers() ?? [$parameterName])) {
$uriVariableDefinition = $context['uri_variables_map'][$parameterName] ?? $uriVariablesDefinitions[$parameterName] ?? $uriVariablesDefinitions['id'] ?? new Link();

// When a composite identifier is used, we assume that the parameterName is the property to find our type
$properties = $uriVariableDefinition->getIdentifiers() ?? [$parameterName];
if ($uriVariableDefinition->getCompositeIdentifier()) {
$properties = [$parameterName];
}

if (!$types = $this->getIdentifierTypes($uriVariableDefinition->getFromClass() ?? $class, $properties)) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Doctrine/Orm/Extension/EagerLoadingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ private function addSelect(QueryBuilder $queryBuilder, string $entity, string $a
}

// It's an embedded property, select relevant subfields
foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) { // @phpstan-ignore-line
foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
$isFetchable = $propertyMetadata->isFetchable();
$propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
$propertyName = "$property.$embeddedProperty";
Expand Down
2 changes: 1 addition & 1 deletion src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ private function createAndValidateAttributeValue(string $attribute, mixed $value
return $value;
}

if (null === $value && $type->isNullable()) {
if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
return $value;
}

Expand Down
6 changes: 3 additions & 3 deletions src/State/CallableProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

namespace ApiPlatform\State;

use ApiPlatform\Exception\RuntimeException;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Exception\ProviderNotFoundException;
use Psr\Container\ContainerInterface;

final class CallableProvider implements ProviderInterface
Expand All @@ -34,7 +34,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c

if (\is_string($provider)) {
if (!$this->locator->has($provider)) {
throw new RuntimeException(sprintf('Provider "%s" not found on operation "%s"', $provider, $operation->getName()));
throw new ProviderNotFoundException(sprintf('Provider "%s" not found on operation "%s"', $provider, $operation->getName()));
}

/** @var ProviderInterface $providerInstance */
Expand All @@ -43,6 +43,6 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
return $providerInstance->provide($operation, $uriVariables, $context);
}

throw new RuntimeException(sprintf('Provider not found on operation "%s"', $operation->getName()));
throw new ProviderNotFoundException(sprintf('Provider not found on operation "%s"', $operation->getName()));
}
}
20 changes: 20 additions & 0 deletions src/State/Exception/ProviderNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\State\Exception;

use ApiPlatform\Metadata\Exception\RuntimeException;

final class ProviderNotFoundException extends RuntimeException
{
}
5 changes: 4 additions & 1 deletion src/State/UriVariablesResolverTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ private function getOperationUriVariables(HttpOperation $operation = null, array
return $identifiers;
}

$uriVariablesMap = [];
foreach ($operation->getUriVariables() ?? [] as $parameterName => $uriVariableDefinition) {
if (!isset($parameters[$parameterName])) {
if (!isset($parameters['id'])) {
Expand All @@ -51,16 +52,18 @@ private function getOperationUriVariables(HttpOperation $operation = null, array

foreach ($currentIdentifiers as $key => $value) {
$identifiers[$key] = $value;
$uriVariableMap[$key] = $uriVariableDefinition;
}

continue;
}

$identifiers[$parameterName] = $parameters[$parameterName];
$uriVariableMap[$parameterName] = $uriVariableDefinition;
}

if ($this->uriVariablesConverter) {
$context = ['operation' => $operation];
$context = ['operation' => $operation, 'uri_variables_map' => $uriVariablesMap];
$identifiers = $this->uriVariablesConverter->convert($identifiers, $operation->getClass() ?? $resourceClass, $context);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/EventListener/ReadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
use ApiPlatform\Api\UriVariablesConverterInterface;
use ApiPlatform\Exception\InvalidIdentifierException;
use ApiPlatform\Exception\InvalidUriVariableException;
use ApiPlatform\Exception\RuntimeException;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\State\Exception\ProviderNotFoundException;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\UriVariablesResolverTrait;
use ApiPlatform\Util\CloneTrait;
Expand Down Expand Up @@ -92,7 +92,7 @@ public function onKernelRequest(RequestEvent $event): void
$data = $this->provider->provide($operation, $uriVariables, $context);
} catch (InvalidIdentifierException|InvalidUriVariableException $e) {
throw new NotFoundHttpException('Invalid identifier value or configuration.', $e);
} catch (RuntimeException $e) {
} catch (ProviderNotFoundException $e) {
$data = null;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Tests\Fixtures\TestBundle\ApiResource\Issue5396;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Operation;

#[ApiResource(provider: [CompositeKeyWithDifferentType::class, 'provide'])]
class CompositeKeyWithDifferentType
{
#[ApiProperty(identifier: true)]
public ?int $id;

#[ApiProperty(identifier: true)]
public ?string $verificationKey;

public static function provide(Operation $operation, array $uriVariables = [], array $context = []): array
{
if (!\is_string($uriVariables['verificationKey'])) {
throw new \RuntimeException('verificationKey should be a string.');
}

return $context;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Tests\Fixtures\TestBundle\ApiResource\Issue5584;

use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;

#[ApiResource(denormalizationContext: [AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true])]
final class DtoWithNullValue
{
public \stdClass $dummy;
}
10 changes: 9 additions & 1 deletion tests/Fixtures/TestBundle/ApiResource/PostWithUriVariables.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
use ApiPlatform\Metadata\NotExposed;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Symfony\Validator\Exception\ValidationException as ExceptionValidationException;
use Symfony\Component\Validator\ConstraintViolationList;

#[NotExposed(uriTemplate: '/post_with_uri_variables/{id}')]
#[Post(uriTemplate: '/post_with_uri_variables/{id}', uriVariables: ['id'], processor: [PostWithUriVariables::class, 'process'])]
#[Post(uriTemplate: '/post_with_uri_variables_and_no_provider/{id}', uriVariables: ['id'], processor: [PostWithUriVariables::class, 'process'])]
#[Post(uriTemplate: '/post_with_uri_variables/{id}', uriVariables: ['id'], provider: [PostWithUriVariables::class, 'provide'])]
final class PostWithUriVariables
{
public function __construct(public readonly ?int $id = null)
Expand All @@ -29,4 +32,9 @@ public static function process(mixed $data, Operation $operation, array $uriVari
{
return new self(id: 1);
}

public static function provide(Operation $operation, array $uriVariables = [], array $context = []): void
{
throw new ExceptionValidationException(new ConstraintViolationList());
}
}
43 changes: 43 additions & 0 deletions tests/Serializer/AbstractItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use ApiPlatform\Metadata\Property\PropertyNameCollection;
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue5584\DtoWithNullValue;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DummyTableInheritance;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DummyTableInheritanceChild;
Expand Down Expand Up @@ -1347,6 +1348,48 @@ public function testDenormalizePopulatingNonCloneableObject(): void
$this->assertSame($dummy, $actual);
$propertyAccessorProphecy->setValue($actual, 'name', 'bar')->shouldHaveBeenCalled();
}

public function testDenormalizeObjectWithNullDisabledTypeEnforcement(): void
{
$data = [
'dummy' => null,
];

$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactoryProphecy->create(DtoWithNullValue::class, [])->willReturn(new PropertyNameCollection(['dummy']));

$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
$propertyMetadataFactoryProphecy->create(DtoWithNullValue::class, 'dummy', [])->willReturn((new ApiProperty())->withBuiltinTypes([new Type(Type::BUILTIN_TYPE_OBJECT, nullable: true)])->withDescription('')->withReadable(true)->withWritable(true));

$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);
$propertyAccessorProphecy = $this->prophesize(PropertyAccessorInterface::class);
$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$resourceClassResolverProphecy->getResourceClass(null, DtoWithNullValue::class)->willReturn(DtoWithNullValue::class);
$resourceClassResolverProphecy->isResourceClass(DtoWithNullValue::class)->willReturn(true);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);

$normalizer = $this->getMockForAbstractClass(AbstractItemNormalizer::class, [
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$iriConverterProphecy->reveal(),
$resourceClassResolverProphecy->reveal(),
$propertyAccessorProphecy->reveal(),
null,
null,
[],
null,
null,
]);
$normalizer->setSerializer($serializerProphecy->reveal());

$context = [AbstractItemNormalizer::DISABLE_TYPE_ENFORCEMENT => true];
$actual = $normalizer->denormalize($data, DtoWithNullValue::class, null, $context);

$this->assertInstanceOf(DtoWithNullValue::class, $actual);
$this->assertEquals(new DtoWithNullValue(), $actual);
}
}

class ObjectWithBasicProperties
Expand Down