From dd1cbbbb941e62d4827ca5f5be08b60ffa391757 Mon Sep 17 00:00:00 2001 From: jewome62 Date: Tue, 5 Jun 2018 10:53:55 +0200 Subject: [PATCH 1/7] Remove unused trait into Hydra Serializer --- src/Hydra/Serializer/CollectionFiltersNormalizer.php | 2 -- src/Hydra/Serializer/PartialCollectionViewNormalizer.php | 3 --- 2 files changed, 5 deletions(-) diff --git a/src/Hydra/Serializer/CollectionFiltersNormalizer.php b/src/Hydra/Serializer/CollectionFiltersNormalizer.php index 4db84a6ce07..12d67864044 100644 --- a/src/Hydra/Serializer/CollectionFiltersNormalizer.php +++ b/src/Hydra/Serializer/CollectionFiltersNormalizer.php @@ -17,7 +17,6 @@ use ApiPlatform\Core\Api\FilterInterface; use ApiPlatform\Core\Api\FilterLocatorTrait; use ApiPlatform\Core\Api\ResourceClassResolverInterface; -use ApiPlatform\Core\JsonLd\Serializer\JsonLdContextTrait; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use Psr\Container\ContainerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; @@ -30,7 +29,6 @@ */ final class CollectionFiltersNormalizer implements NormalizerInterface, NormalizerAwareInterface { - use JsonLdContextTrait; use FilterLocatorTrait; private $collectionNormalizer; diff --git a/src/Hydra/Serializer/PartialCollectionViewNormalizer.php b/src/Hydra/Serializer/PartialCollectionViewNormalizer.php index ad4861471e2..300d06be02a 100644 --- a/src/Hydra/Serializer/PartialCollectionViewNormalizer.php +++ b/src/Hydra/Serializer/PartialCollectionViewNormalizer.php @@ -15,7 +15,6 @@ use ApiPlatform\Core\DataProvider\PaginatorInterface; use ApiPlatform\Core\DataProvider\PartialPaginatorInterface; -use ApiPlatform\Core\JsonLd\Serializer\JsonLdContextTrait; use ApiPlatform\Core\Util\IriHelper; use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; @@ -28,8 +27,6 @@ */ final class PartialCollectionViewNormalizer implements NormalizerInterface, NormalizerAwareInterface { - use JsonLdContextTrait; - private $collectionNormalizer; private $pageParameterName; private $enabledParameterName; From 000f6dfec5ec37e6b46ad6e8b7036650c70ddc09 Mon Sep 17 00:00:00 2001 From: abluchet Date: Tue, 5 Jun 2018 12:08:01 +0200 Subject: [PATCH 2/7] Disable eager loading when no groups are specified to avoid recursive joins --- features/main/circular_reference.feature | 3 +- .../Orm/Extension/EagerLoadingExtension.php | 4 + .../Extension/EagerLoadingExtensionTest.php | 106 +++++++++--------- 3 files changed, 62 insertions(+), 51 deletions(-) diff --git a/features/main/circular_reference.feature b/features/main/circular_reference.feature index ce86453f6f7..45718c6b517 100644 --- a/features/main/circular_reference.feature +++ b/features/main/circular_reference.feature @@ -61,7 +61,8 @@ Feature: Circular references handling "@type": "CircularReference", "parent": "/circular_references/1", "children": [ - "/circular_references/1" + "/circular_references/1", + "/circular_references/2" ] }, "children": [] diff --git a/src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php b/src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php index 32e763af4e4..c7a0f6c39d4 100644 --- a/src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php +++ b/src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php @@ -107,6 +107,10 @@ private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGe $context += $this->getNormalizationContext($context['resource_class'] ?? $resourceClass, $contextType, $options); } + if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) { + return; + } + $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context); } diff --git a/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php b/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php index 076f8dd11a5..0557f75c132 100644 --- a/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php +++ b/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php @@ -51,6 +51,8 @@ class EagerLoadingExtensionTest extends TestCase { public function testApplyToCollection() { + $context = ['groups' => ['foo']]; + $callContext = ['serializer_groups' => ['foo']]; $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); @@ -65,8 +67,8 @@ public function testApplyToCollection() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); $propertyNameCollectionFactoryProphecy->create(EmbeddableDummy::class)->willReturn($relatedEmbedableCollection)->shouldBeCalled(); $idPropertyMetadata = new PropertyMetadata(); @@ -80,11 +82,11 @@ public function testApplyToCollection() $notReadablePropertyMetadata = new PropertyMetadata(); $notReadablePropertyMetadata = $notReadablePropertyMetadata->withReadable(false); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'id', [])->willReturn($idPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'name', [])->willReturn($namePropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'embeddedDummy', [])->willReturn($embeddedPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notindatabase', [])->willReturn($notInDatabasePropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notreadable', [])->willReturn($notReadablePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'id', $callContext)->willReturn($idPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'name', $callContext)->willReturn($namePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'embeddedDummy', $callContext)->willReturn($embeddedPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notindatabase', $callContext)->willReturn($notInDatabasePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notreadable', $callContext)->willReturn($notReadablePropertyMetadata)->shouldBeCalled(); $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); @@ -121,11 +123,14 @@ public function testApplyToCollection() $queryBuilder = $queryBuilderProphecy->reveal(); $eagerExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, false, null, null, true); - $eagerExtensionTest->applyToCollection($queryBuilder, new QueryNameGenerator(), Dummy::class); + $eagerExtensionTest->applyToCollection($queryBuilder, new QueryNameGenerator(), Dummy::class, null, $context); } public function testApplyToItem() { + $context = ['groups' => ['foo']]; + $callContext = ['serializer_groups' => ['foo']]; + $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); @@ -142,12 +147,12 @@ public function testApplyToItem() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy3', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy4', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy5', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'singleInheritanceRelation', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy3', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy4', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy5', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'singleInheritanceRelation', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); $idPropertyMetadata = new PropertyMetadata(); $idPropertyMetadata = $idPropertyMetadata->withIdentifier(true); @@ -160,13 +165,13 @@ public function testApplyToItem() $notReadablePropertyMetadata = new PropertyMetadata(); $notReadablePropertyMetadata = $notReadablePropertyMetadata->withReadable(false); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'id', [])->willReturn($idPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'name', [])->willReturn($namePropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'embeddedDummy', [])->willReturn($embeddedDummyPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notindatabase', [])->willReturn($notInDatabasePropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notreadable', [])->willReturn($notReadablePropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'relation', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(UnknownDummy::class, 'id', [])->willReturn($idPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'id', $callContext)->willReturn($idPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'name', $callContext)->willReturn($namePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'embeddedDummy', $callContext)->willReturn($embeddedDummyPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notindatabase', $callContext)->willReturn($notInDatabasePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'notreadable', $callContext)->willReturn($notReadablePropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'relation', $callContext)->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(UnknownDummy::class, 'id', $callContext)->willReturn($idPropertyMetadata)->shouldBeCalled(); $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); @@ -225,7 +230,7 @@ public function testApplyToItem() $queryBuilder = $queryBuilderProphecy->reveal(); $orderExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, false, null, null, true); - $orderExtensionTest->applyToItem($queryBuilder, new QueryNameGenerator(), Dummy::class, []); + $orderExtensionTest->applyToItem($queryBuilder, new QueryNameGenerator(), Dummy::class, [], null, $context); } public function testCreateItemWithOperationName() @@ -236,7 +241,7 @@ public function testCreateItemWithOperationName() $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'foo', ['item_operation_name' => 'item_operation'])->shouldBeCalled()->willReturn(new PropertyMetadata()); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'foo', ['item_operation_name' => 'item_operation', 'serializer_groups' => ['foo']])->shouldBeCalled()->willReturn(new PropertyMetadata()); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -249,7 +254,7 @@ public function testCreateItemWithOperationName() $queryBuilderProphecy->getEntityManager()->willReturn($emProphecy); $orderExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, false, null, null, true); - $orderExtensionTest->applyToItem($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, [], 'item_operation'); + $orderExtensionTest->applyToItem($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, [], 'item_operation', ['groups' => ['foo']]); } public function testCreateCollectionWithOperationName() @@ -260,7 +265,7 @@ public function testCreateCollectionWithOperationName() $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'foo', ['collection_operation_name' => 'collection_operation'])->shouldBeCalled()->willReturn(new PropertyMetadata()); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'foo', ['collection_operation_name' => 'collection_operation', 'serializer_groups' => ['foo']])->shouldBeCalled()->willReturn(new PropertyMetadata()); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -273,15 +278,16 @@ public function testCreateCollectionWithOperationName() $queryBuilderProphecy->getEntityManager()->willReturn($emProphecy); $eagerExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, false, null, null, true); - $eagerExtensionTest->applyToCollection($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, 'collection_operation'); + $eagerExtensionTest->applyToCollection($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, 'collection_operation', ['groups' => ['foo']]); } public function testDenormalizeItemWithCorrectResourceClass() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); //Dummy is the correct class for the denormalization context serialization groups, and we're fetching RelatedDummy - $resourceMetadataFactoryProphecy->create(RelatedDummy::class)->willReturn(new ResourceMetadata())->shouldBeCalled(); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata())->shouldBeCalled(); + $resourceMetadata = (new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]]); + $resourceMetadataFactoryProphecy->create(RelatedDummy::class)->willReturn($resourceMetadata)->shouldBeCalled(); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn($resourceMetadata)->shouldBeCalled(); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); @@ -341,12 +347,12 @@ public function testMaxJoinsReached() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); $relatedPropertyMetadata = new PropertyMetadata(); $relatedPropertyMetadata = $relatedPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'dummy', [])->willReturn($relatedPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'dummy', ['serializer_groups' => ['foo']])->willReturn($relatedPropertyMetadata)->shouldBeCalled(); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -370,14 +376,14 @@ public function testMaxJoinsReached() $queryBuilderProphecy->addSelect(Argument::type('string'))->shouldBeCalled(); $eagerExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, false, null, null, true); - $eagerExtensionTest->applyToCollection($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class); + $eagerExtensionTest->applyToCollection($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, null, ['groups' => ['foo']]); } public function testMaxDepth() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); $resourceMetadata = new ResourceMetadata(); - $resourceMetadata = $resourceMetadata->withAttributes(['normalization_context' => ['enable_max_depth' => 'true']]); + $resourceMetadata = $resourceMetadata->withAttributes(['normalization_context' => ['enable_max_depth' => 'true', 'groups' => ['foo']]]); $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn($resourceMetadata); @@ -393,12 +399,12 @@ public function testMaxDepth() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); $relatedPropertyMetadata = new PropertyMetadata(); $relatedPropertyMetadata = $relatedPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'dummy', [])->willReturn($relatedPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(RelatedDummy::class, 'dummy', ['serializer_groups' => ['foo']])->willReturn($relatedPropertyMetadata)->shouldBeCalled(); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -524,12 +530,12 @@ public function testExtraLazy() public function testResourceClassNotFoundException() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', [])->willThrow(new ResourceClassNotFoundException()); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', ['serializer_groups' => ['foo']])->willThrow(new ResourceClassNotFoundException()); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -542,18 +548,18 @@ public function testResourceClassNotFoundException() $queryBuilderProphecy->getEntityManager()->willReturn($emProphecy); $orderExtensionTest = new EagerLoadingExtension($propertyNameCollectionFactoryProphecy->reveal(), $propertyMetadataFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), 30, true, null, null, true); - $orderExtensionTest->applyToItem($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, []); + $orderExtensionTest->applyToItem($queryBuilderProphecy->reveal(), new QueryNameGenerator(), Dummy::class, [], null); } public function testPropertyNotFoundException() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', [])->willThrow(new PropertyNotFoundException()); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', ['serializer_groups' => ['foo']])->willThrow(new PropertyNotFoundException()); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -572,7 +578,7 @@ public function testPropertyNotFoundException() public function testResourceClassNotFoundExceptionPropertyNameCollection() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(UnknownDummy::class)->willThrow(new ResourceClassNotFoundException()); @@ -580,7 +586,7 @@ public function testResourceClassNotFoundExceptionPropertyNameCollection() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', [])->willReturn($relationPropertyMetadata); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relation', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->associationMappings = [ @@ -770,7 +776,7 @@ public function testNotInAttributes() public function testApplyToCollectionNoPartial() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); @@ -778,8 +784,8 @@ public function testApplyToCollectionNoPartial() $relationPropertyMetadata = new PropertyMetadata(); $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); @@ -811,7 +817,7 @@ public function testApplyToCollectionNoPartial() public function testApplyToCollectionWithANonRedableButFetchEagerProperty() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); @@ -821,8 +827,8 @@ public function testApplyToCollectionWithANonRedableButFetchEagerProperty() $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(false); $relationPropertyMetadata = $relationPropertyMetadata->withReadable(false); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); @@ -854,7 +860,7 @@ public function testApplyToCollectionWithANonRedableButFetchEagerProperty() public function testApplyToCollectionWithARedableButNotFetchEagerProperty() { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); - $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); + $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn((new ResourceMetadata())->withAttributes(['normalization_context' => ['groups' => ['foo']]])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); @@ -864,8 +870,8 @@ public function testApplyToCollectionWithARedableButNotFetchEagerProperty() $relationPropertyMetadata = $relationPropertyMetadata->withReadableLink(true); $relationPropertyMetadata = $relationPropertyMetadata->withReadable(true); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); - $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', [])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); + $propertyMetadataFactoryProphecy->create(Dummy::class, 'relatedDummy2', ['serializer_groups' => ['foo']])->willReturn($relationPropertyMetadata)->shouldBeCalled(); $queryBuilderProphecy = $this->prophesize(QueryBuilder::class); From f7406d18bf92a6496213c29fba0e94453721a320 Mon Sep 17 00:00:00 2001 From: Ben Davies Date: Fri, 1 Jun 2018 13:14:42 +0100 Subject: [PATCH 3/7] replace exception annotations with methods --- .php_cs.dist | 21 +++---- .travis.yml | 2 +- tests/Annotation/ApiFilterTest.php | 21 +++---- tests/Api/FilterLocatorTraitTest.php | 10 +-- tests/Api/IdentifiersExtractorTest.php | 8 +-- tests/Api/ResourceClassResolverTest.php | 22 +++---- .../Orm/CollectionDataProviderTest.php | 8 +-- .../Extension/EagerLoadingExtensionTest.php | 8 +-- .../Orm/Extension/FilterExtensionTest.php | 6 +- .../Orm/Extension/PaginationExtensionTest.php | 15 +++-- .../Doctrine/Orm/ItemDataProviderTest.php | 14 ++--- tests/Bridge/Doctrine/Orm/PaginatorTest.php | 15 +++-- .../Orm/SubresourceDataProviderTest.php | 21 +++---- .../Util/IdentifierManagerTraitTest.php | 8 +-- .../ApiPlatformProviderTest.php | 6 +- .../ApiPlatformExtensionTest.php | 15 +++-- .../Compiler/AnnotationFilterPassTest.php | 8 +-- .../DependencyInjection/ConfigurationTest.php | 12 ++-- .../Bridge/Symfony/Routing/ApiLoaderTest.php | 16 +++-- .../Routing/CachedRouteNameResolverTest.php | 14 ++--- .../Symfony/Routing/IriConverterTest.php | 58 ++++++++--------- .../Routing/RouteNameGeneratorTest.php | 8 +-- .../Symfony/Routing/RouteNameResolverTest.php | 14 ++--- .../RouterOperationPathResolverTest.php | 15 +++-- .../EventListener/ValidateListenerTest.php | 6 +- .../Symfony/Validator/ValidatorTest.php | 6 +- tests/EventListener/AddFormatListenerTest.php | 30 +++++---- .../EventListener/DeserializeListenerTest.php | 15 +++-- tests/EventListener/ReadListenerTest.php | 22 +++---- .../TestBundle/Entity/CustomActionDummy.php | 2 +- .../ItemMutationResolverFactoryTest.php | 6 +- .../Type/Definition/IterableTypeTest.php | 4 +- tests/Hal/Serializer/ItemNormalizerTest.php | 6 +- .../CollectionFiltersNormalizerTest.php | 6 +- .../Serializer/CollectionNormalizerTest.php | 9 ++- .../JsonApi/Serializer/ItemNormalizerTest.php | 34 +++++----- tests/JsonLd/Action/ContextActionTest.php | 6 +- .../Metadata/Extractor/YamlExtractorTest.php | 15 +++-- .../AnnotationPropertyMetadataFactoryTest.php | 7 +-- ...ationPropertyNameCollectionFactoryTest.php | 7 +-- .../ExtractorPropertyMetadataFactoryTest.php | 63 +++++++++---------- ...actorPropertyNameCollectionFactoryTest.php | 49 +++++++-------- .../ExtractorResourceMetadataFactoryTest.php | 33 +++++----- ...actorResourceNameCollectionFactoryTest.php | 11 ++-- .../DashOperationPathResolverTest.php | 7 ++- .../UnderscoreOperationPathResolverTest.php | 7 ++- .../EventListener/DenyAccessListenerTest.php | 25 ++++---- tests/Security/ResourceAccessCheckerTest.php | 21 +++---- .../Serializer/AbstractItemNormalizerTest.php | 36 +++++------ tests/Serializer/ItemNormalizerTest.php | 8 +-- .../SerializerContextBuilderTest.php | 6 +- .../SerializerFilterContextBuilderTest.php | 8 +-- .../DocumentationNormalizerTest.php | 8 +-- tests/Util/IriHelperTest.php | 8 +-- .../EventListener/ValidateListenerTest.php | 5 +- 55 files changed, 388 insertions(+), 433 deletions(-) diff --git a/.php_cs.dist b/.php_cs.dist index 550c3f621c8..6e8308e2308 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -1,5 +1,7 @@ setRiskyAllowed(true) ->setRules([ '@DoctrineAnnotation' => true, - 'doctrine_annotation_array_assignment' => [ - 'operator' => '=', - ], - 'doctrine_annotation_spaces' => [ - 'after_array_assignments_equals' => false, - 'before_array_assignments_equals' => false, - ], + '@PHPUnit60Migration:risky' => true, '@Symfony' => true, '@Symfony:risky' => true, 'array_syntax' => [ @@ -34,12 +30,18 @@ return PhpCsFixer\Config::create() 'allow_single_line_closure' => true, ], 'declare_strict_types' => true, + 'doctrine_annotation_array_assignment' => [ + 'operator' => '=', + ], + 'doctrine_annotation_spaces' => [ + 'after_array_assignments_equals' => false, + 'before_array_assignments_equals' => false, + ], 'header_comment' => [ 'header' => $header, 'location' => 'after_open', ], 'modernize_types_casting' => true, - // 'native_function_invocation' => true, 'no_extra_consecutive_blank_lines' => [ 'break', 'continue', @@ -54,9 +56,6 @@ return PhpCsFixer\Config::create() 'no_useless_else' => true, 'no_useless_return' => true, 'ordered_imports' => true, - // 'phpdoc_add_missing_param_annotation' => [ - // 'only_untyped' => false, - // ], 'phpdoc_order' => true, 'psr4' => true, 'semicolon_after_instruction' => true, diff --git a/.travis.yml b/.travis.yml index 23871400fbb..876cf5b886f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -41,7 +41,7 @@ before_install: - phpenv config-rm xdebug.ini || echo "xdebug not available" - echo "memory_limit=-1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - if [[ $lint = 1 ]]; then - wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v2.8.4/php-cs-fixer.phar; + wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v2.12.0/php-cs-fixer.phar; fi - if [[ $lint = 1 ]]; then composer global require --dev 'phpstan/phpstan:^0.8'; diff --git a/tests/Annotation/ApiFilterTest.php b/tests/Annotation/ApiFilterTest.php index 882c841945c..270c86205a4 100644 --- a/tests/Annotation/ApiFilterTest.php +++ b/tests/Annotation/ApiFilterTest.php @@ -23,30 +23,27 @@ */ class ApiFilterTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage This annotation needs a value representing the filter class. - */ public function testInvalidConstructor() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('This annotation needs a value representing the filter class.'); + $resource = new ApiFilter(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The filter class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" does not implement "ApiPlatform\Core\Api\FilterInterface". - */ public function testInvalidFilter() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The filter class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy" does not implement "ApiPlatform\\Core\\Api\\FilterInterface".'); + $resource = new ApiFilter(['value' => Dummy::class]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Property "foo" does not exist on the ApiFilter annotation. - */ public function testInvalidProperty() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Property "foo" does not exist on the ApiFilter annotation.'); + $resource = new ApiFilter(['value' => DummyFilter::class, 'foo' => 'bar']); } diff --git a/tests/Api/FilterLocatorTraitTest.php b/tests/Api/FilterLocatorTraitTest.php index 356e37d408c..c50c3546e37 100644 --- a/tests/Api/FilterLocatorTraitTest.php +++ b/tests/Api/FilterLocatorTraitTest.php @@ -58,22 +58,24 @@ public function testSetFilterLocatorWithNullAndNullAllowed() /** * @group legacy - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface. */ public function testSetFilterLocatorWithNullAndNullNotAllowed() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface.'); + $filterLocatorTraitImpl = $this->getFilterLocatorTraitImpl(); $filterLocatorTraitImpl->setFilterLocator(null); } /** * @group legacy - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface or null. */ public function testSetFilterLocatorWithInvalidFilterLocator() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface or null.'); + $filterLocatorTraitImpl = $this->getFilterLocatorTraitImpl(); $filterLocatorTraitImpl->setFilterLocator(new \ArrayObject(), true); } diff --git a/tests/Api/IdentifiersExtractorTest.php b/tests/Api/IdentifiersExtractorTest.php index f091015752e..4a21318d80a 100644 --- a/tests/Api/IdentifiersExtractorTest.php +++ b/tests/Api/IdentifiersExtractorTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\IdentifiersExtractor; use ApiPlatform\Core\Api\ResourceClassResolverInterface; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -152,12 +153,11 @@ public function testGetRelatedIdentifiersFromItem($item, $expected) $this->assertSame($expected, $identifiersExtractor->getIdentifiersFromItem($item)); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedMessage No identifier found in "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\RelatedDummy" through relation "relatedDummy" of "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" used as identifier - */ public function testThrowNoIdentifierFromItem() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('No identifier found in "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\RelatedDummy" through relation "relatedDummy" of "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy" used as identifier'); + $prophecies = $this->getMetadataFactoryProphecies(Dummy::class, ['id', 'relatedDummy']); list($propertyNameCollectionFactoryProphecy, $propertyMetadataFactoryProphecy) = $this->getMetadataFactoryProphecies(RelatedDummy::class, [], $prophecies); diff --git a/tests/Api/ResourceClassResolverTest.php b/tests/Api/ResourceClassResolverTest.php index 85ed8383a8d..ab5e1061411 100644 --- a/tests/Api/ResourceClassResolverTest.php +++ b/tests/Api/ResourceClassResolverTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\ResourceClassResolver; use ApiPlatform\Core\DataProvider\PaginatorInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceNameCollection; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -93,12 +94,11 @@ public function testGetResourceClassWithPaginatorInterfaceAsValue() $this->assertEquals($resourceClass, Dummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No resource class found for object of type "stdClass". - */ public function testGetResourceClassWithWrongClassName() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No resource class found for object of type "stdClass".'); + $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class); $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection([Dummy::class]))->shouldBeCalled(); @@ -106,12 +106,11 @@ public function testGetResourceClassWithWrongClassName() $resourceClassResolver->getResourceClass(new \stdClass(), null); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No resource class found. - */ public function testGetResourceClassWithNoResourceClassName() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No resource class found.'); + $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class); $resourceClassResolver = new ResourceClassResolver($resourceNameCollectionFactoryProphecy->reveal()); @@ -140,12 +139,11 @@ public function testIsResourceClassWithWrongClassName() $this->assertFalse($resourceClass); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No resource class found. - */ public function testGetResourceClassWithNoResourceClassNameAndNoObject() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No resource class found.'); + $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class); $resourceClassResolver = new ResourceClassResolver($resourceNameCollectionFactoryProphecy->reveal()); diff --git a/tests/Bridge/Doctrine/Orm/CollectionDataProviderTest.php b/tests/Bridge/Doctrine/Orm/CollectionDataProviderTest.php index 352e2a89eba..31925c57775 100644 --- a/tests/Bridge/Doctrine/Orm/CollectionDataProviderTest.php +++ b/tests/Bridge/Doctrine/Orm/CollectionDataProviderTest.php @@ -17,6 +17,7 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; use Doctrine\Common\Persistence\ManagerRegistry; use Doctrine\Common\Persistence\ObjectManager; @@ -80,12 +81,11 @@ public function testQueryResultExtension() $this->assertEquals([], $dataProvider->getCollection(Dummy::class, 'foo')); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage The repository class must have a "createQueryBuilder" method. - */ public function testCannotCreateQueryBuilder() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The repository class must have a "createQueryBuilder" method.'); + $repositoryProphecy = $this->prophesize(ObjectRepository::class); $managerProphecy = $this->prophesize(ObjectManager::class); diff --git a/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php b/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php index 0557f75c132..6e086dc4aff 100644 --- a/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php +++ b/tests/Bridge/Doctrine/Orm/Extension/EagerLoadingExtensionTest.php @@ -17,6 +17,7 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator; use ApiPlatform\Core\Exception\PropertyNotFoundException; use ApiPlatform\Core\Exception\ResourceClassNotFoundException; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -326,12 +327,11 @@ public function testDenormalizeItemWithExistingGroups() $eagerExtensionTest->applyToItem($queryBuilderProphecy->reveal(), new QueryNameGenerator(), RelatedDummy::class, ['id' => 1], 'item_operation', [AbstractNormalizer::GROUPS => 'some_groups']); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary, or use the "max_depth" option of the Symfony serializer. - */ public function testMaxJoinsReached() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary, or use the "max_depth" option of the Symfony serializer.'); + $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); $resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata()); diff --git a/tests/Bridge/Doctrine/Orm/Extension/FilterExtensionTest.php b/tests/Bridge/Doctrine/Orm/Extension/FilterExtensionTest.php index de6ad7ad969..b33beb807ff 100644 --- a/tests/Bridge/Doctrine/Orm/Extension/FilterExtensionTest.php +++ b/tests/Bridge/Doctrine/Orm/Extension/FilterExtensionTest.php @@ -18,6 +18,7 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\FilterExtension; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\FilterInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -78,11 +79,12 @@ public function testApplyToCollectionWithValidFiltersAndDeprecatedFilterCollecti /** * @group legacy - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface. */ public function testConstructWithInvalidFilterLocator() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface.'); + new FilterExtension($this->prophesize(ResourceMetadataFactoryInterface::class)->reveal(), new \ArrayObject()); } diff --git a/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php b/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php index 7b1cc77e41c..846c5a6f934 100644 --- a/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php +++ b/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php @@ -17,6 +17,7 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator; use ApiPlatform\Core\DataProvider\PaginatorInterface; use ApiPlatform\Core\DataProvider\PartialPaginatorInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use Doctrine\Common\Persistence\ManagerRegistry; @@ -99,12 +100,11 @@ public function testApplyToCollectionWithItemPerPageZero() $extension->applyToCollection($queryBuilder, new QueryNameGenerator(), 'Foo', 'op'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Page should not be greater than 1 if itemsPerPage is equal to 0 - */ public function testApplyToCollectionWithItemPerPageZeroAndPage2() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Page should not be greater than 1 if itemsPerPage is equal to 0'); + $requestStack = new RequestStack(); $requestStack->push(new Request(['pagination' => true, 'itemsPerPage' => 0, '_page' => 2])); @@ -135,12 +135,11 @@ public function testApplyToCollectionWithItemPerPageZeroAndPage2() $extension->applyToCollection($queryBuilder, new QueryNameGenerator(), 'Foo', 'op'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Item per page parameter should not be less than 0 - */ public function testApplyToCollectionWithItemPerPageLessThen0() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Item per page parameter should not be less than 0'); + $requestStack = new RequestStack(); $requestStack->push(new Request(['pagination' => true, 'itemsPerPage' => -20, '_page' => 2])); diff --git a/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php b/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php index 11154633cb1..7eb53e869e4 100644 --- a/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php +++ b/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php @@ -17,6 +17,8 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\ItemDataProvider; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; +use ApiPlatform\Core\Exception\PropertyNotFoundException; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -124,11 +126,10 @@ public function testGetItemDoubleIdentifier() $this->assertEquals([], $dataProvider->getItem(Dummy::class, 'ida=1;idb=2', 'foo')); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - */ public function testGetItemWrongCompositeIdentifier() { + $this->expectException(PropertyNotFoundException::class); + list($propertyNameCollectionFactory, $propertyMetadataFactory) = $this->getMetadataFactories(Dummy::class, [ 'ida', 'idb', @@ -196,12 +197,11 @@ public function testUnsupportedClass() $this->assertFalse($dataProvider->supports(Dummy::class, 'foo')); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage The repository class must have a "createQueryBuilder" method. - */ public function testCannotCreateQueryBuilder() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The repository class must have a "createQueryBuilder" method.'); + $repositoryProphecy = $this->prophesize(ObjectRepository::class); $classMetadataProphecy = $this->prophesize(ClassMetadata::class); $classMetadataProphecy->getIdentifier()->willReturn([ diff --git a/tests/Bridge/Doctrine/Orm/PaginatorTest.php b/tests/Bridge/Doctrine/Orm/PaginatorTest.php index 4c6e1d134e0..5e67fb56d20 100644 --- a/tests/Bridge/Doctrine/Orm/PaginatorTest.php +++ b/tests/Bridge/Doctrine/Orm/PaginatorTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Bridge\Doctrine\Orm; use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Tests\Fixtures\Query; use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator; use PHPUnit\Framework\TestCase; @@ -32,21 +33,19 @@ public function testInitialize($firstResult, $maxResults, $totalItems, $currentP $this->assertEquals($maxResults, $paginator->getItemsPerPage()); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage "Doctrine\ORM\Query::setFirstResult()" or/and "Doctrine\ORM\Query::setMaxResults()" was/were not applied to the query. - */ public function testInitializeWithQueryFirstResultNotApplied() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Doctrine\\ORM\\Query::setFirstResult()" or/and "Doctrine\\ORM\\Query::setMaxResults()" was/were not applied to the query.'); + $this->getPaginatorWithMalformedQuery(false); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage "Doctrine\ORM\Query::setFirstResult()" or/and "Doctrine\ORM\Query::setMaxResults()" was/were not applied to the query. - */ public function testInitializeWithQueryMaxResultsNotApplied() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Doctrine\\ORM\\Query::setFirstResult()" or/and "Doctrine\\ORM\\Query::setMaxResults()" was/were not applied to the query.'); + $this->getPaginatorWithMalformedQuery(true); } diff --git a/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php b/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php index 161ee9422e2..1c2a4b5dc44 100644 --- a/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php +++ b/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php @@ -16,6 +16,8 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\SubresourceDataProvider; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; +use ApiPlatform\Core\Exception\ResourceClassNotSupportedException; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -100,12 +102,11 @@ private function getManagerRegistryProphecy(QueryBuilder $queryBuilder, array $i return $managerRegistryProphecy->reveal(); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotSupportedException - * @expectedExceptionMessage The given resource class is not a subresource. - */ public function testNotASubresource() { + $this->expectException(ResourceClassNotSupportedException::class); + $this->expectExceptionMessage('The given resource class is not a subresource.'); + $identifiers = ['id']; list($propertyNameCollectionFactory, $propertyMetadataFactory) = $this->getMetadataProphecies([Dummy::class => $identifiers]); $queryBuilder = $this->prophesize(QueryBuilder::class)->reveal(); @@ -332,12 +333,11 @@ public function testQueryResultExtension() $this->assertEquals([], $dataProvider->getSubresource(RelatedDummy::class, ['id' => 1], $context)); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage The repository class must have a "createQueryBuilder" method. - */ public function testCannotCreateQueryBuilder() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The repository class must have a "createQueryBuilder" method.'); + $identifiers = ['id']; $repositoryProphecy = $this->prophesize(ObjectRepository::class); @@ -353,11 +353,10 @@ public function testCannotCreateQueryBuilder() $dataProvider->getSubresource(Dummy::class, ['id' => 1], []); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotSupportedException - */ public function testThrowResourceClassNotSupportedException() { + $this->expectException(ResourceClassNotSupportedException::class); + $identifiers = ['id']; $managerRegistryProphecy = $this->prophesize(ManagerRegistry::class); $managerRegistryProphecy->getManagerForClass(Dummy::class)->willReturn(null)->shouldBeCalled(); diff --git a/tests/Bridge/Doctrine/Util/IdentifierManagerTraitTest.php b/tests/Bridge/Doctrine/Util/IdentifierManagerTraitTest.php index d7fa39276bc..47fda20d32b 100644 --- a/tests/Bridge/Doctrine/Util/IdentifierManagerTraitTest.php +++ b/tests/Bridge/Doctrine/Util/IdentifierManagerTraitTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Bridge\Doctrine\Util; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait; +use ApiPlatform\Core\Exception\PropertyNotFoundException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -80,12 +81,11 @@ public function testCompositeIdentifier() $this->assertEquals($identifierManager->normalizeIdentifiers('ida=1;idb=2', $objectManager, Dummy::class), ['ida' => 1, 'idb' => 2]); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Invalid identifier "idbad=1;idb=2", "ida" has not been found. - */ public function testInvalidIdentifier() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Invalid identifier "idbad=1;idb=2", "ida" has not been found.'); + list($propertyNameCollectionFactory, $propertyMetadataFactory) = $this->getMetadataFactories(Dummy::class, [ 'ida', 'idb', diff --git a/tests/Bridge/NelmioApiDoc/Extractor/AnnotationsProvider/ApiPlatformProviderTest.php b/tests/Bridge/NelmioApiDoc/Extractor/AnnotationsProvider/ApiPlatformProviderTest.php index 4da119dafb8..f54caf255dd 100644 --- a/tests/Bridge/NelmioApiDoc/Extractor/AnnotationsProvider/ApiPlatformProviderTest.php +++ b/tests/Bridge/NelmioApiDoc/Extractor/AnnotationsProvider/ApiPlatformProviderTest.php @@ -98,12 +98,12 @@ public function testGetAnnotationsWithDeprecatedFilterCollection() /** * @expectedDeprecation The ApiPlatform\Core\Bridge\NelmioApiDoc\Extractor\AnnotationsProvider\ApiPlatformProvider class is deprecated since version 2.2 and will be removed in 3.0. NelmioApiDocBundle 3 has native support for API Platform. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface. */ public function testConstructWithInvalidFilterLocator() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface.'); + new ApiPlatformProvider( $this->prophesize(ResourceNameCollectionFactoryInterface::class)->reveal(), $this->prophesize(NormalizerInterface::class)->reveal(), diff --git a/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php b/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php index 9181907beca..b571a61dc0f 100644 --- a/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php +++ b/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php @@ -29,6 +29,7 @@ use ApiPlatform\Core\DataProvider\ItemDataProviderInterface; use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface; use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; @@ -297,24 +298,22 @@ public function testAddResourceClassDirectories() $this->extension->load(array_merge_recursive(self::DEFAULT_CONFIG, ['api_platform' => ['resource_class_directories' => ['foobar']]]), $containerBuilder); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessageRegExp /Unsupported mapping type in ".+", supported types are XML & Yaml\./ - */ public function testResourcesToWatchWithUnsupportedMappingType() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessageRegExp('/Unsupported mapping type in ".+", supported types are XML & Yaml\\./'); + $this->extension->load( array_merge_recursive(self::DEFAULT_CONFIG, ['api_platform' => ['mapping' => ['paths' => [__FILE__]]]]), $this->getPartialContainerBuilderProphecy(false)->reveal() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage Could not open file or directory "fake_file.xml". - */ public function testResourcesToWatchWithNonExistentFile() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Could not open file or directory "fake_file.xml".'); + $this->extension->load( array_merge_recursive(self::DEFAULT_CONFIG, ['api_platform' => ['mapping' => ['paths' => ['fake_file.xml']]]]), $this->getPartialContainerBuilderProphecy()->reveal() diff --git a/tests/Bridge/Symfony/Bundle/DependencyInjection/Compiler/AnnotationFilterPassTest.php b/tests/Bridge/Symfony/Bundle/DependencyInjection/Compiler/AnnotationFilterPassTest.php index a072ac003dd..3f114b8899f 100644 --- a/tests/Bridge/Symfony/Bundle/DependencyInjection/Compiler/AnnotationFilterPassTest.php +++ b/tests/Bridge/Symfony/Bundle/DependencyInjection/Compiler/AnnotationFilterPassTest.php @@ -19,6 +19,7 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\DateFilter; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter; use ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection\Compiler\AnnotationFilterPass; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Serializer\Filter\GroupFilter; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Doctrine\Orm\Filter\AnotherDummyFilter; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -97,12 +98,11 @@ public function testProcess() $annotationFilterPass->process($containerBuilderProphecy->reveal()); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The filter class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Doctrine\Orm\Filter\AnotherDummyFilter" does not implement "ApiPlatform\Core\Api\FilterInterface". - */ public function testProcessWrongFilter() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The filter class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Doctrine\\Orm\\Filter\\AnotherDummyFilter" does not implement "ApiPlatform\\Core\\Api\\FilterInterface".'); + $annotationFilterPass = new AnnotationFilterPass(); $this->assertInstanceOf(CompilerPassInterface::class, $annotationFilterPass); diff --git a/tests/Bridge/Symfony/Bundle/DependencyInjection/ConfigurationTest.php b/tests/Bridge/Symfony/Bundle/DependencyInjection/ConfigurationTest.php index faf9a707a46..4e1e9801413 100644 --- a/tests/Bridge/Symfony/Bundle/DependencyInjection/ConfigurationTest.php +++ b/tests/Bridge/Symfony/Bundle/DependencyInjection/ConfigurationTest.php @@ -18,6 +18,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Serializer\Exception\ExceptionInterface; @@ -187,11 +189,12 @@ public function invalidHttpStatusCodeProvider() /** * @dataProvider invalidHttpStatusCodeProvider - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessageRegExp /The HTTP status code ".+" is not valid\./ */ public function testExceptionToStatusConfigWithInvalidHttpStatusCode($invalidHttpStatusCode) { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessageRegExp('/The HTTP status code ".+" is not valid\\./'); + $this->processor->processConfiguration($this->configuration, [ 'api_platform' => [ 'exception_to_status' => [ @@ -215,11 +218,12 @@ public function invalidHttpStatusCodeValueProvider() /** * @dataProvider invalidHttpStatusCodeValueProvider - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - * @expectedExceptionMessageRegExp /Invalid type for path "api_platform\.exception_to_status\.Exception". Expected int, but got .+\./ */ public function testExceptionToStatusConfigWithInvalidHttpStatusCodeValue($invalidHttpStatusCodeValue) { + $this->expectException(InvalidTypeException::class); + $this->expectExceptionMessageRegExp('/Invalid type for path "api_platform\\.exception_to_status\\.Exception". Expected int, but got .+\\./'); + $this->processor->processConfiguration($this->configuration, [ 'api_platform' => [ 'exception_to_status' => [ diff --git a/tests/Bridge/Symfony/Routing/ApiLoaderTest.php b/tests/Bridge/Symfony/Routing/ApiLoaderTest.php index a87bf17f5e8..ba23c8c49a9 100644 --- a/tests/Bridge/Symfony/Routing/ApiLoaderTest.php +++ b/tests/Bridge/Symfony/Routing/ApiLoaderTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Bridge\Symfony\Routing; use ApiPlatform\Core\Bridge\Symfony\Routing\ApiLoader; +use ApiPlatform\Core\Exception\InvalidResourceException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -97,11 +98,10 @@ public function testApiLoader() ); } - /** - * @expectedException \RuntimeException - */ public function testNoMethodApiLoader() { + $this->expectException(\RuntimeException::class); + $resourceMetadata = new ResourceMetadata(); $resourceMetadata = $resourceMetadata->withShortName('dummy'); @@ -116,11 +116,10 @@ public function testNoMethodApiLoader() $this->getApiLoaderWithResourceMetadata($resourceMetadata)->load(null); } - /** - * @expectedException \RuntimeException - */ public function testWrongMethodApiLoader() { + $this->expectException(\RuntimeException::class); + $resourceMetadata = new ResourceMetadata(); $resourceMetadata = $resourceMetadata->withShortName('dummy'); @@ -135,11 +134,10 @@ public function testWrongMethodApiLoader() $this->getApiLoaderWithResourceMetadata($resourceMetadata)->load(null); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidResourceException - */ public function testNoShortNameApiLoader() { + $this->expectException(InvalidResourceException::class); + $this->getApiLoaderWithResourceMetadata(new ResourceMetadata())->load(null); } diff --git a/tests/Bridge/Symfony/Routing/CachedRouteNameResolverTest.php b/tests/Bridge/Symfony/Routing/CachedRouteNameResolverTest.php index 573ebfd479a..1f87ca68b90 100644 --- a/tests/Bridge/Symfony/Routing/CachedRouteNameResolverTest.php +++ b/tests/Bridge/Symfony/Routing/CachedRouteNameResolverTest.php @@ -39,12 +39,11 @@ public function testConstruct() $this->assertInstanceOf(RouteNameResolverInterface::class, $cachedRouteNameResolver); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No item route associated with the type "AppBundle\Entity\User". - */ public function testGetRouteNameForItemRouteWithNoMatchingRoute() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No item route associated with the type "AppBundle\\Entity\\User".'); + $cacheItemProphecy = $this->prophesize(CacheItemInterface::class); $cacheItemProphecy->isHit()->willReturn(false)->shouldBeCalled(); @@ -99,12 +98,11 @@ public function testGetRouteNameForItemRouteOnCacheHit() $this->assertSame('some_item_route', $cachedRouteNameResolver->getRouteName('AppBundle\Entity\User', OperationType::ITEM), 'Trigger the local cache'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No collection route associated with the type "AppBundle\Entity\User". - */ public function testGetRouteNameForCollectionRouteWithNoMatchingRoute() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No collection route associated with the type "AppBundle\\Entity\\User".'); + $cacheItemProphecy = $this->prophesize(CacheItemInterface::class); $cacheItemProphecy->isHit()->willReturn(false)->shouldBeCalled(); diff --git a/tests/Bridge/Symfony/Routing/IriConverterTest.php b/tests/Bridge/Symfony/Routing/IriConverterTest.php index 510d480b3cb..3564a057e1e 100644 --- a/tests/Bridge/Symfony/Routing/IriConverterTest.php +++ b/tests/Bridge/Symfony/Routing/IriConverterTest.php @@ -21,6 +21,8 @@ use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameResolverInterface; use ApiPlatform\Core\DataProvider\ItemDataProviderInterface; use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\ItemNotFoundException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -35,24 +37,22 @@ */ class IriConverterTest extends TestCase { - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No route matches "/users/3". - */ public function testGetItemFromIriNoRouteException() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No route matches "/users/3".'); + $routerProphecy = $this->prophesize(RouterInterface::class); $routerProphecy->match('/users/3')->willThrow(new RouteNotFoundException())->shouldBeCalledTimes(1); $converter = $this->getIriConverter($routerProphecy); $converter->getItemFromIri('/users/3'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage No resource associated to "/users/3". - */ public function testGetItemFromIriNoResourceException() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No resource associated to "/users/3".'); + $routerProphecy = $this->prophesize(RouterInterface::class); $routerProphecy->match('/users/3')->willReturn([])->shouldBeCalledTimes(1); @@ -60,12 +60,11 @@ public function testGetItemFromIriNoResourceException() $converter->getItemFromIri('/users/3'); } - /** - * @expectedException \ApiPlatform\Core\Exception\ItemNotFoundException - * @expectedExceptionMessage Item not found for "/users/3". - */ public function testGetItemFromIriItemNotFoundException() { + $this->expectException(ItemNotFoundException::class); + $this->expectExceptionMessage('Item not found for "/users/3".'); + $itemDataProviderProphecy = $this->prophesize(ItemDataProviderInterface::class); $itemDataProviderProphecy ->getItem(Dummy::class, 3, 'get', []) @@ -146,12 +145,11 @@ public function testGetIriFromResourceClass() $this->assertEquals($converter->getIriFromResourceClass(Dummy::class), '/dummies'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Unable to generate an IRI for "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" - */ public function testNotAbleToGenerateGetIriFromResourceClass() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to generate an IRI for "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy"'); + $routeNameResolverProphecy = $this->prophesize(RouteNameResolverInterface::class); $routeNameResolverProphecy->getRouteName(Dummy::class, OperationType::COLLECTION)->willReturn('dummies'); @@ -174,12 +172,11 @@ public function testGetSubresourceIriFromResourceClass() $this->assertEquals($converter->getSubresourceIriFromResourceClass(Dummy::class, ['subresource_identifiers' => ['id' => 1], 'subresource_resources' => [RelatedDummy::class => 1]]), '/dummies/1/related_dummies'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Unable to generate an IRI for "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" - */ public function testNotAbleToGenerateGetSubresourceIriFromResourceClass() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to generate an IRI for "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy"'); + $routeNameResolverProphecy = $this->prophesize(RouteNameResolverInterface::class); $routeNameResolverProphecy->getRouteName(Dummy::class, OperationType::SUBRESOURCE, Argument::type('array'))->willReturn('dummies'); @@ -202,12 +199,11 @@ public function testGetItemIriFromResourceClass() $this->assertEquals($converter->getItemIriFromResourceClass(Dummy::class, ['id' => 1]), '/dummies/1'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Unable to generate an IRI for "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy" - */ public function testNotAbleToGenerateGetItemIriFromResourceClass() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to generate an IRI for "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy"'); + $routeNameResolverProphecy = $this->prophesize(RouteNameResolverInterface::class); $routeNameResolverProphecy->getRouteName(Dummy::class, OperationType::ITEM)->willReturn('dummies'); @@ -237,12 +233,11 @@ public function testGetItemFromIriWithSubresourceDataProvider() $this->assertEquals($converter->getItemFromIri('/users/3/adresses', ['fetch_data' => true]), $item); } - /** - * @expectedException \ApiPlatform\Core\Exception\ItemNotFoundException - * @expectedExceptionMessage Item not found for "/users/3/adresses". - */ public function testGetItemFromIriWithSubresourceDataProviderNotFound() { + $this->expectException(ItemNotFoundException::class); + $this->expectExceptionMessage('Item not found for "/users/3/adresses".'); + $subresourceContext = ['identifiers' => [['id', Dummy::class, true]]]; $itemDataProviderProphecy = $this->prophesize(ItemDataProviderInterface::class); $routeNameResolverProphecy = $this->prophesize(RouteNameResolverInterface::class); @@ -259,12 +254,11 @@ public function testGetItemFromIriWithSubresourceDataProviderNotFound() $converter->getItemFromIri('/users/3/adresses', ['fetch_data' => true]); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Item not found for "/users/3". - */ public function testGetItemFromIriBadIdentifierException() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Item not found for "/users/3".'); + $item = new \StdClass(); $itemDataProviderProphecy = $this->prophesize(ItemDataProviderInterface::class); $routeNameResolverProphecy = $this->prophesize(RouteNameResolverInterface::class); diff --git a/tests/Bridge/Symfony/Routing/RouteNameGeneratorTest.php b/tests/Bridge/Symfony/Routing/RouteNameGeneratorTest.php index f8160ed0ebb..e789dd6144d 100644 --- a/tests/Bridge/Symfony/Routing/RouteNameGeneratorTest.php +++ b/tests/Bridge/Symfony/Routing/RouteNameGeneratorTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\OperationType; use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameGenerator; +use ApiPlatform\Core\Exception\InvalidArgumentException; use PHPUnit\Framework\TestCase; /** @@ -37,12 +38,11 @@ public function testLegacyGenerate() $this->assertEquals('api_foos_get_collection', RouteNameGenerator::generate('get', 'Foo', true)); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedMessage Subresource operations are not supported by the RouteNameGenerator. - */ public function testGenerateWithSubresource() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Subresource operations are not supported by the RouteNameGenerator.'); + $this->assertEquals('api_foos_bar_get_subresource', RouteNameGenerator::generate('get', 'Foo', OperationType::SUBRESOURCE)); } } diff --git a/tests/Bridge/Symfony/Routing/RouteNameResolverTest.php b/tests/Bridge/Symfony/Routing/RouteNameResolverTest.php index c50ed462cd4..df0cf445964 100644 --- a/tests/Bridge/Symfony/Routing/RouteNameResolverTest.php +++ b/tests/Bridge/Symfony/Routing/RouteNameResolverTest.php @@ -35,12 +35,11 @@ public function testConstruct() $this->assertInstanceOf(RouteNameResolverInterface::class, $routeNameResolver); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage No item route associated with the type "AppBundle\Entity\User". - */ public function testGetRouteNameForItemRouteWithNoMatchingRoute() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('No item route associated with the type "AppBundle\\Entity\\User".'); + $routeCollection = new RouteCollection(); $routeCollection->add('some_collection_route', new Route('/some/collection/path', [ '_api_resource_class' => 'AppBundle\Entity\User', @@ -100,12 +99,11 @@ public function testGetRouteNameForItemRoute() $this->assertSame('some_item_route', $actual); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage No collection route associated with the type "AppBundle\Entity\User". - */ public function testGetRouteNameForCollectionRouteWithNoMatchingRoute() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('No collection route associated with the type "AppBundle\\Entity\\User".'); + $routeCollection = new RouteCollection(); $routeCollection->add('some_item_route', new Route('/some/item/path/{id}', [ '_api_resource_class' => 'AppBundle\Entity\User', diff --git a/tests/Bridge/Symfony/Routing/RouterOperationPathResolverTest.php b/tests/Bridge/Symfony/Routing/RouterOperationPathResolverTest.php index 330f9daf0d4..912847bd255 100644 --- a/tests/Bridge/Symfony/Routing/RouterOperationPathResolverTest.php +++ b/tests/Bridge/Symfony/Routing/RouterOperationPathResolverTest.php @@ -16,6 +16,7 @@ use ApiPlatform\Core\Api\OperationType; use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameGenerator; use ApiPlatform\Core\Bridge\Symfony\Routing\RouterOperationPathResolver; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\PathResolver\OperationPathResolverInterface; use PHPUnit\Framework\TestCase; use Prophecy\Argument; @@ -41,12 +42,11 @@ public function testResolveOperationPath() $this->assertEquals('/foos', $operationPathResolver->resolveOperationPath('Foo', ['route_name' => 'foos'], OperationType::COLLECTION, 'get')); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedMessage Subresource operations are not supported by the RouterOperationPathResolver. - */ public function testResolveOperationPathWithSubresource() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Subresource operations are not supported by the RouterOperationPathResolver without a route name.'); + $routerProphecy = $this->prophesize(RouterInterface::class); $operationPathResolver = new RouterOperationPathResolver($routerProphecy->reveal(), $this->prophesize(OperationPathResolverInterface::class)->reveal()); @@ -67,12 +67,11 @@ public function testResolveOperationPathWithRouteNameGeneration() $this->assertEquals('/foos', $operationPathResolver->resolveOperationPath('Foo', [], OperationType::COLLECTION, 'get')); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The route "api_foos_get_collection" of the resource "Foo" was not found. - */ public function testResolveOperationPathWithRouteNotFound() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The route "api_foos_get_collection" of the resource "Foo" was not found.'); + $routerProphecy = $this->prophesize(RouterInterface::class); $routerProphecy->getRouteCollection()->willReturn(new RouteCollection())->shouldBeCalled(); diff --git a/tests/Bridge/Symfony/Validator/EventListener/ValidateListenerTest.php b/tests/Bridge/Symfony/Validator/EventListener/ValidateListenerTest.php index 68089083bac..165293e60b4 100644 --- a/tests/Bridge/Symfony/Validator/EventListener/ValidateListenerTest.php +++ b/tests/Bridge/Symfony/Validator/EventListener/ValidateListenerTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Bridge\Symfony\Validator\EventListener; use ApiPlatform\Core\Bridge\Symfony\Validator\EventListener\ValidateListener; +use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Tests\Fixtures\DummyEntity; @@ -150,11 +151,10 @@ public function testDoNotCallWhenReceiveFlagIsFalse() $validationViewListener->onKernelView($event); } - /** - * @expectedException \ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException - */ public function testThrowsValidationExceptionWithViolationsFound() { + $this->expectException(ValidationException::class); + $data = new DummyEntity(); $expectedValidationGroups = ['a', 'b', 'c']; diff --git a/tests/Bridge/Symfony/Validator/ValidatorTest.php b/tests/Bridge/Symfony/Validator/ValidatorTest.php index 6c034a4a33c..bee2588fcde 100644 --- a/tests/Bridge/Symfony/Validator/ValidatorTest.php +++ b/tests/Bridge/Symfony/Validator/ValidatorTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Core\Tests\Bridge\Symfony\Validator; +use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException; use ApiPlatform\Core\Bridge\Symfony\Validator\Validator; use ApiPlatform\Core\Tests\Fixtures\DummyEntity; use PHPUnit\Framework\TestCase; @@ -38,11 +39,10 @@ public function testValid() $validator->validate(new DummyEntity()); } - /** - * @expectedException \ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException - */ public function testInvalid() { + $this->expectException(ValidationException::class); + $data = new DummyEntity(); $constraintViolationListProphecy = $this->prophesize(ConstraintViolationListInterface::class); diff --git a/tests/EventListener/AddFormatListenerTest.php b/tests/EventListener/AddFormatListenerTest.php index 5574c529948..f60904e1179 100644 --- a/tests/EventListener/AddFormatListenerTest.php +++ b/tests/EventListener/AddFormatListenerTest.php @@ -18,6 +18,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * @author Kévin Dunglas @@ -70,12 +72,11 @@ public function testRespondFlag() $this->assertSame('text/xml', $request->getMimeType($request->getRequestFormat())); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException - * @expectedExceptionMessage Requested format "text/xml" is not supported. Supported MIME types are "application/json". - */ public function testUnsupportedRequestFormat() { + $this->expectException(NotAcceptableHttpException::class); + $this->expectExceptionMessage('Requested format "text/xml" is not supported. Supported MIME types are "application/json".'); + $request = new Request([], [], ['_api_resource_class' => 'Foo']); $request->setRequestFormat('xml'); @@ -120,12 +121,11 @@ public function testAcceptAllHeader() $this->assertSame('application/octet-stream', $request->getMimeType($request->getRequestFormat())); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException - * @expectedExceptionMessage Requested format "text/html, application/xhtml+xml, application/xml;q=0.9" is not supported. Supported MIME types are "application/octet-stream", "application/json". - */ public function testUnsupportedAcceptHeader() { + $this->expectException(NotAcceptableHttpException::class); + $this->expectExceptionMessage('Requested format "text/html, application/xhtml+xml, application/xml;q=0.9" is not supported. Supported MIME types are "application/octet-stream", "application/json".'); + $request = new Request([], [], ['_api_resource_class' => 'Foo']); $request->headers->set('Accept', 'text/html, application/xhtml+xml, application/xml;q=0.9'); @@ -137,12 +137,11 @@ public function testUnsupportedAcceptHeader() $listener->onKernelRequest($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException - * @expectedExceptionMessage Requested format "invalid" is not supported. Supported MIME types are "application/json". - */ public function testInvalidAcceptHeader() { + $this->expectException(NotAcceptableHttpException::class); + $this->expectExceptionMessage('Requested format "invalid" is not supported. Supported MIME types are "application/json".'); + $request = new Request([], [], ['_api_resource_class' => 'Foo']); $request->headers->set('Accept', 'invalid'); @@ -170,12 +169,11 @@ public function testAcceptHeaderTakePrecedenceOverRequestFormat() $this->assertSame('json', $request->getRequestFormat()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - * @expectedExceptionMessage Format "invalid" is not supported - */ public function testInvalidRouteFormat() { + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('Format "invalid" is not supported'); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_format' => 'invalid']); $eventProphecy = $this->prophesize(GetResponseEvent::class); diff --git a/tests/EventListener/DeserializeListenerTest.php b/tests/EventListener/DeserializeListenerTest.php index ef8bb57dfa4..527ee9a661b 100644 --- a/tests/EventListener/DeserializeListenerTest.php +++ b/tests/EventListener/DeserializeListenerTest.php @@ -19,6 +19,7 @@ use Prophecy\Argument; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\SerializerInterface; @@ -155,12 +156,11 @@ public function testContentNegotiation() $listener->onKernelRequest($eventProphecy->reveal()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException - * @expectedExceptionMessage The content-type "application/rdf+xml" is not supported. Supported MIME types are "application/ld+json", "text/xml". - */ public function testNotSupportedContentType() { + $this->expectException(NotAcceptableHttpException::class); + $this->expectExceptionMessage('The content-type "application/rdf+xml" is not supported. Supported MIME types are "application/ld+json", "text/xml".'); + $eventProphecy = $this->prophesize(GetResponseEvent::class); $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'post'], [], [], [], '{}'); @@ -183,12 +183,11 @@ public function testNotSupportedContentType() $listener->onKernelRequest($eventProphecy->reveal()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException - * @expectedExceptionMessage The "Content-Type" header must exist. - */ public function testNoContentType() { + $this->expectException(NotAcceptableHttpException::class); + $this->expectExceptionMessage('The "Content-Type" header must exist.'); + $eventProphecy = $this->prophesize(GetResponseEvent::class); $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'post'], [], [], [], '{}'); diff --git a/tests/EventListener/ReadListenerTest.php b/tests/EventListener/ReadListenerTest.php index 65b44631291..e5cb08204cc 100644 --- a/tests/EventListener/ReadListenerTest.php +++ b/tests/EventListener/ReadListenerTest.php @@ -17,9 +17,11 @@ use ApiPlatform\Core\DataProvider\ItemDataProviderInterface; use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface; use ApiPlatform\Core\EventListener\ReadListener; +use ApiPlatform\Core\Exception\RuntimeException; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * @author Kévin Dunglas @@ -136,11 +138,10 @@ public function testRetrieveItem() $this->assertSame($data, $request->attributes->get('data')); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testRetrieveItemNoIdentifier() { + $this->expectException(NotFoundHttpException::class); + $collectionDataProvider = $this->prophesize(CollectionDataProviderInterface::class); $collectionDataProvider->getCollection()->shouldNotBeCalled(); @@ -186,11 +187,10 @@ public function testRetrieveSubresource() $this->assertSame($data, $request->attributes->get('data')); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - */ public function testRetrieveSubresourceNoDataProvider() { + $this->expectException(RuntimeException::class); + $collectionDataProvider = $this->prophesize(CollectionDataProviderInterface::class); $collectionDataProvider->getCollection()->shouldNotBeCalled(); @@ -209,11 +209,10 @@ public function testRetrieveSubresourceNoDataProvider() $request->attributes->get('data'); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testRetrieveSubresourceNotFound() { + $this->expectException(NotFoundHttpException::class); + $collectionDataProvider = $this->prophesize(CollectionDataProviderInterface::class); $collectionDataProvider->getCollection()->shouldNotBeCalled(); @@ -233,11 +232,10 @@ public function testRetrieveSubresourceNotFound() $listener->onKernelRequest($event->reveal()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testRetrieveItemNotFound() { + $this->expectException(NotFoundHttpException::class); + $collectionDataProvider = $this->prophesize(CollectionDataProviderInterface::class); $itemDataProvider = $this->prophesize(ItemDataProviderInterface::class); diff --git a/tests/Fixtures/TestBundle/Entity/CustomActionDummy.php b/tests/Fixtures/TestBundle/Entity/CustomActionDummy.php index 237deb312e2..088db841c9f 100644 --- a/tests/Fixtures/TestBundle/Entity/CustomActionDummy.php +++ b/tests/Fixtures/TestBundle/Entity/CustomActionDummy.php @@ -21,7 +21,7 @@ * @ApiResource(itemOperations={ * "get", * "custom_normalization"={"route_name"="custom_normalization"} - * }, collectionOperations={ + * }, collectionOperations={ * "get", * "custom_denormalization"={"route_name"="custom_denormalization"} * }) diff --git a/tests/GraphQl/Resolver/Factory/ItemMutationResolverFactoryTest.php b/tests/GraphQl/Resolver/Factory/ItemMutationResolverFactoryTest.php index 1d09b316d5c..17d18651e73 100644 --- a/tests/GraphQl/Resolver/Factory/ItemMutationResolverFactoryTest.php +++ b/tests/GraphQl/Resolver/Factory/ItemMutationResolverFactoryTest.php @@ -21,6 +21,7 @@ use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; +use GraphQL\Error\Error; use GraphQL\Type\Definition\ResolveInfo; use PHPUnit\Framework\TestCase; use Prophecy\Argument; @@ -33,11 +34,10 @@ */ class ItemMutationResolverFactoryTest extends TestCase { - /** - * @expectedException \GraphQL\Error\Error - */ public function testCreateItemMutationResolverNoItem() { + $this->expectException(Error::class); + $dataPersisterProphecy = $this->prophesize(DataPersisterInterface::class); $dataPersisterProphecy->remove(Argument::any())->shouldNotBeCalled(); diff --git a/tests/GraphQl/Type/Definition/IterableTypeTest.php b/tests/GraphQl/Type/Definition/IterableTypeTest.php index 2a6bf4b3310..a847c818800 100644 --- a/tests/GraphQl/Type/Definition/IterableTypeTest.php +++ b/tests/GraphQl/Type/Definition/IterableTypeTest.php @@ -36,7 +36,7 @@ public function testSerialize() $iterableType = new IterableType(); $this->expectException(Error::class); - $this->expectExceptionMessage('Iterable cannot represent non iterable value: foo'); + $this->expectExceptionMessageRegExp('/Iterable cannot represent non iterable value: .+/'); $iterableType->serialize('foo'); @@ -48,7 +48,7 @@ public function testParseValue() $iterableType = new IterableType(); $this->expectException(Error::class); - $this->expectExceptionMessage('Iterable cannot represent non iterable value: "foo"'); + $this->expectExceptionMessageRegExp('/Iterable cannot represent non iterable value: .+/'); $iterableType->parseValue('foo'); diff --git a/tests/Hal/Serializer/ItemNormalizerTest.php b/tests/Hal/Serializer/ItemNormalizerTest.php index 39a6d8e607c..572f349c2ba 100644 --- a/tests/Hal/Serializer/ItemNormalizerTest.php +++ b/tests/Hal/Serializer/ItemNormalizerTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\IriConverterInterface; use ApiPlatform\Core\Api\ResourceClassResolverInterface; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Hal\Serializer\ItemNormalizer; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; @@ -40,11 +41,10 @@ */ class ItemNormalizerTest extends TestCase { - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - */ public function testDoesNotSupportDenormalization() { + $this->expectException(RuntimeException::class); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); $iriConverterProphecy = $this->prophesize(IriConverterInterface::class); diff --git a/tests/Hydra/Serializer/CollectionFiltersNormalizerTest.php b/tests/Hydra/Serializer/CollectionFiltersNormalizerTest.php index e15da141e4a..fad1a46fbba 100644 --- a/tests/Hydra/Serializer/CollectionFiltersNormalizerTest.php +++ b/tests/Hydra/Serializer/CollectionFiltersNormalizerTest.php @@ -16,6 +16,7 @@ use ApiPlatform\Core\Api\FilterCollection; use ApiPlatform\Core\Api\ResourceClassResolverInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\FilterInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Hydra\Serializer\CollectionFiltersNormalizer; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; @@ -136,11 +137,12 @@ public function testNormalizeWithDeprecatedFilterCollection() /** * @group legacy - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface. */ public function testConstructWithInvalidFilterLocator() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface.'); + new CollectionFiltersNormalizer( $this->prophesize(NormalizerInterface::class)->reveal(), $this->prophesize(ResourceMetadataFactoryInterface::class)->reveal(), diff --git a/tests/JsonApi/Serializer/CollectionNormalizerTest.php b/tests/JsonApi/Serializer/CollectionNormalizerTest.php index eefe7363de1..febbf3611b4 100644 --- a/tests/JsonApi/Serializer/CollectionNormalizerTest.php +++ b/tests/JsonApi/Serializer/CollectionNormalizerTest.php @@ -16,9 +16,9 @@ use ApiPlatform\Core\Api\ResourceClassResolverInterface; use ApiPlatform\Core\DataProvider\PaginatorInterface; use ApiPlatform\Core\DataProvider\PartialPaginatorInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\JsonApi\Serializer\CollectionNormalizer; use PHPUnit\Framework\TestCase; -use Symfony\Component\PropertyInfo\Type; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; /** @@ -224,12 +224,11 @@ public function testNormalizeArray() $this->assertEquals($expected, $normalizer->normalize($data, CollectionNormalizer::FORMAT, ['request_uri' => '/foos'])); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The JSON API document must contain a "data" key. - */ public function testNormalizeWithoutDataKey() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The JSON API document must contain a "data" key.'); + $data = ['foo']; $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); diff --git a/tests/JsonApi/Serializer/ItemNormalizerTest.php b/tests/JsonApi/Serializer/ItemNormalizerTest.php index 945e2fa312d..21d8b0858f3 100644 --- a/tests/JsonApi/Serializer/ItemNormalizerTest.php +++ b/tests/JsonApi/Serializer/ItemNormalizerTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\IriConverterInterface; use ApiPlatform\Core\Api\ResourceClassResolverInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\JsonApi\Serializer\ItemNormalizer; use ApiPlatform\Core\JsonApi\Serializer\ReservedAttributeNameConverter; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; @@ -181,11 +182,10 @@ public function testNormalizeIsNotAnArray() )); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - */ public function testNormalizeThrowsNoSuchPropertyException() { + $this->expectException(NoSuchPropertyException::class); + $foo = new \stdClass(); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); @@ -324,12 +324,11 @@ public function testDenormalize() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Update is not allowed for this operation. - */ public function testDenormalizeUpdateOperationNotAllowed() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Update is not allowed for this operation.'); + $normalizer = new ItemNormalizer( $this->prophesize(PropertyNameCollectionFactoryInterface::class)->reveal(), $this->prophesize(PropertyMetadataFactoryInterface::class)->reveal(), @@ -355,12 +354,11 @@ public function testDenormalizeUpdateOperationNotAllowed() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The type of the "relatedDummies" attribute must be "array", "string" given. - */ public function testDenormalizeCollectionIsNotArray() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The type of the "relatedDummies" attribute must be "array", "string" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn(new PropertyNameCollection(['relatedDummies']))->shouldBeCalled(); @@ -408,12 +406,11 @@ public function testDenormalizeCollectionIsNotArray() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The type of the key "0" must be "string", "integer" given. - */ public function testDenormalizeCollectionWithInvalidKey() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The type of the key "0" must be "string", "integer" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn(new PropertyNameCollection(['relatedDummies']))->shouldBeCalled(); @@ -466,12 +463,11 @@ public function testDenormalizeCollectionWithInvalidKey() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage. - */ public function testDenormalizeRelationIsNotResourceLinkage() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn(new PropertyNameCollection(['relatedDummy']))->shouldBeCalled(); diff --git a/tests/JsonLd/Action/ContextActionTest.php b/tests/JsonLd/Action/ContextActionTest.php index fdb0d327740..20c9395649d 100644 --- a/tests/JsonLd/Action/ContextActionTest.php +++ b/tests/JsonLd/Action/ContextActionTest.php @@ -20,6 +20,7 @@ use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Metadata\Resource\ResourceNameCollection; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * @author Amrouche Hamza @@ -63,11 +64,10 @@ public function testContextActionWithResourceClass() $this->assertEquals(['@context' => ['/dummies']], $contextAction('dummy')); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testContextActionWithThrown() { + $this->expectException(NotFoundHttpException::class); + $contextBuilderProphecy = $this->prophesize(ContextBuilderInterface::class); $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class); $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); diff --git a/tests/Metadata/Extractor/YamlExtractorTest.php b/tests/Metadata/Extractor/YamlExtractorTest.php index 8197b3acc2c..4f0885f13e2 100644 --- a/tests/Metadata/Extractor/YamlExtractorTest.php +++ b/tests/Metadata/Extractor/YamlExtractorTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Core\Tests\Metadata\Extractor; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Extractor\YamlExtractor; use PHPUnit\Framework\TestCase; @@ -21,21 +22,19 @@ */ class YamlExtractorTest extends TestCase { - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The property "shortName" must be a "string", "integer" given. - */ public function testInvalidProperty() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The property "shortName" must be a "string", "integer" given.'); + (new YamlExtractor([__DIR__.'/../../Fixtures/FileConfigurations/badpropertytype.yml']))->getResources(); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Unable to parse in ".+\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/parse_exception.yml"/ - */ public function testParseException() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/Unable to parse in ".+\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/parse_exception.yml"/'); + (new YamlExtractor([__DIR__.'/../../Fixtures/FileConfigurations/parse_exception.yml']))->getResources(); } diff --git a/tests/Metadata/Property/Factory/AnnotationPropertyMetadataFactoryTest.php b/tests/Metadata/Property/Factory/AnnotationPropertyMetadataFactoryTest.php index 0ed0a441d6a..326518adcd3 100644 --- a/tests/Metadata/Property/Factory/AnnotationPropertyMetadataFactoryTest.php +++ b/tests/Metadata/Property/Factory/AnnotationPropertyMetadataFactoryTest.php @@ -87,12 +87,11 @@ public function getDependencies() ]; } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Property "foo" of class "\DoNotExist" not found. - */ public function testClassNotFound() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Property "foo" of class "\\DoNotExist" not found.'); + $factory = new AnnotationPropertyMetadataFactory($this->prophesize(Reader::class)->reveal()); $factory->create('\DoNotExist', 'foo'); } diff --git a/tests/Metadata/Property/Factory/AnnotationPropertyNameCollectionFactoryTest.php b/tests/Metadata/Property/Factory/AnnotationPropertyNameCollectionFactoryTest.php index e6cf670c789..c3ca0113b3b 100644 --- a/tests/Metadata/Property/Factory/AnnotationPropertyNameCollectionFactoryTest.php +++ b/tests/Metadata/Property/Factory/AnnotationPropertyNameCollectionFactoryTest.php @@ -94,12 +94,11 @@ public function getUpperCaseDependencies() ]; } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotFoundException - * @expectedExceptionMessage The resource class "\DoNotExist" does not exist. - */ public function testClassDoesNotExist() { + $this->expectException(ResourceClassNotFoundException::class); + $this->expectExceptionMessage('The resource class "\\DoNotExist" does not exist.'); + $reader = $this->prophesize(Reader::class); $factory = new AnnotationPropertyNameCollectionFactory($reader->reveal()); diff --git a/tests/Metadata/Property/Factory/ExtractorPropertyMetadataFactoryTest.php b/tests/Metadata/Property/Factory/ExtractorPropertyMetadataFactoryTest.php index 932e17ab675..68da3efa204 100644 --- a/tests/Metadata/Property/Factory/ExtractorPropertyMetadataFactoryTest.php +++ b/tests/Metadata/Property/Factory/ExtractorPropertyMetadataFactoryTest.php @@ -13,6 +13,8 @@ namespace ApiPlatform\Core\Tests\Metadata\Property\Factory; +use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\PropertyNotFoundException; use ApiPlatform\Core\Metadata\Extractor\XmlExtractor; use ApiPlatform\Core\Metadata\Extractor\YamlExtractor; use ApiPlatform\Core\Metadata\Property\Factory\ExtractorPropertyMetadataFactory; @@ -63,34 +65,31 @@ public function testCreateWithParentPropertyMetadataFactoryXml(PropertyMetadata $this->assertEquals($expectedPropertyMetadata, $propertyMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Property "foo" of the resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" not found. - */ public function testCreateWithNonexistentResourceXml() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Property "foo" of the resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.xml'; (new ExtractorPropertyMetadataFactory(new XmlExtractor([$configPath])))->create('ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist', 'foo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Property "bar" of the resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\FileConfigDummy" not found. - */ public function testCreateWithNonexistentPropertyXml() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Property "bar" of the resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\FileConfigDummy" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resources.xml'; (new ExtractorPropertyMetadataFactory(new XmlExtractor([$configPath])))->create(FileConfigDummy::class, 'bar'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp #.+Element '\{https://api-platform.com/schema/metadata\}foo': This element is not expected\..+# - */ public function testCreateWithInvalidXml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('#.+Element \'\\{https://api-platform.com/schema/metadata\\}foo\': This element is not expected\\..+#'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertyinvalid.xml'; (new ExtractorPropertyMetadataFactory(new XmlExtractor([$configPath])))->create(FileConfigDummy::class, 'foo'); @@ -186,66 +185,60 @@ public function testCreateWithTypedParentPropertyMetadataFactoryYaml(PropertyMet $this->assertEquals($expectedPropertyMetadata, $propertyMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Property "foo" of the resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" not found. - */ public function testCreateWithNonexistentResourceYaml() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Property "foo" of the resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create('ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist', 'foo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\PropertyNotFoundException - * @expectedExceptionMessage Property "bar" of the resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\FileConfigDummy" not found. - */ public function testCreateWithNonexistentPropertyYaml() { + $this->expectException(PropertyNotFoundException::class); + $this->expectExceptionMessage('Property "bar" of the resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\FileConfigDummy" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resources.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class, 'bar'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"resources" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/resourcesinvalid\.yml"\./ - */ public function testCreateWithMalformedResourcesSettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"resources" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/resourcesinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcesinvalid.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class, 'foo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"properties" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/propertiesinvalid\.yml"\./ - */ public function testCreateWithMalformedPropertiesSettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"properties" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/propertiesinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertiesinvalid.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class, 'foo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"foo" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/propertyinvalid\.yml"\./ - */ public function testCreateWithMalformedPropertySettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"foo" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/propertyinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertyinvalid.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class, 'foo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testCreateWithMalformedYaml() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/parse_exception.yml'; (new ExtractorPropertyMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class, 'foo'); diff --git a/tests/Metadata/Property/Factory/ExtractorPropertyNameCollectionFactoryTest.php b/tests/Metadata/Property/Factory/ExtractorPropertyNameCollectionFactoryTest.php index e59203066a4..95e142dea96 100644 --- a/tests/Metadata/Property/Factory/ExtractorPropertyNameCollectionFactoryTest.php +++ b/tests/Metadata/Property/Factory/ExtractorPropertyNameCollectionFactoryTest.php @@ -13,6 +13,8 @@ namespace ApiPlatform\Core\Tests\Metadata\Property\Factory; +use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\ResourceClassNotFoundException; use ApiPlatform\Core\Metadata\Extractor\XmlExtractor; use ApiPlatform\Core\Metadata\Extractor\YamlExtractor; use ApiPlatform\Core\Metadata\Property\Factory\ExtractorPropertyNameCollectionFactory; @@ -52,23 +54,21 @@ public function testCreateWithParentPropertyNameCollectionFactoryXml() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotFoundException - * @expectedExceptionMessage The resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" does not exist. - */ public function testCreateWithNonexistentResourceXml() { + $this->expectException(ResourceClassNotFoundException::class); + $this->expectExceptionMessage('The resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" does not exist.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.xml'; (new ExtractorPropertyNameCollectionFactory(new XmlExtractor([$configPath])))->create('ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp #.+Element '\{https://api-platform.com/schema/metadata\}foo': This element is not expected\..+# - */ public function testCreateWithInvalidXml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('#.+Element \'\\{https://api-platform.com/schema/metadata\\}foo\': This element is not expected\\..+#'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertyinvalid.xml'; (new ExtractorPropertyNameCollectionFactory(new XmlExtractor([$configPath])))->create(FileConfigDummy::class); @@ -100,55 +100,50 @@ public function testCreateWithParentPropertyMetadataFactoryYaml() ); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotFoundException - * @expectedExceptionMessage The resource class "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" does not exist. - */ public function testCreateWithNonexistentResourceYaml() { + $this->expectException(ResourceClassNotFoundException::class); + $this->expectExceptionMessage('The resource class "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" does not exist.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.yml'; (new ExtractorPropertyNameCollectionFactory(new YamlExtractor([$configPath])))->create('ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"resources" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/resourcesinvalid\.yml"\./ - */ public function testCreateWithMalformedResourcesSettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"resources" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/resourcesinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcesinvalid.yml'; (new ExtractorPropertyNameCollectionFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"properties" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/propertiesinvalid\.yml"\./ - */ public function testCreateWithMalformedPropertiesSettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"properties" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/propertiesinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertiesinvalid.yml'; (new ExtractorPropertyNameCollectionFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"foo" setting is expected to be null or an array, string given in ".+\/\.\.\/\.\.\/\.\.\/Fixtures\/FileConfigurations\/propertyinvalid\.yml"\./ - */ public function testCreateWithMalformedPropertySettingYaml() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"foo" setting is expected to be null or an array, string given in ".+\\/\\.\\.\\/\\.\\.\\/\\.\\.\\/Fixtures\\/FileConfigurations\\/propertyinvalid\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/propertyinvalid.yml'; (new ExtractorPropertyNameCollectionFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testCreateWithMalformedYaml() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/parse_exception.yml'; (new ExtractorPropertyNameCollectionFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); diff --git a/tests/Metadata/Resource/Factory/ExtractorResourceMetadataFactoryTest.php b/tests/Metadata/Resource/Factory/ExtractorResourceMetadataFactoryTest.php index 7a908342564..19b0a9fafb2 100644 --- a/tests/Metadata/Resource/Factory/ExtractorResourceMetadataFactoryTest.php +++ b/tests/Metadata/Resource/Factory/ExtractorResourceMetadataFactoryTest.php @@ -13,6 +13,8 @@ namespace ApiPlatform\Core\Tests\Metadata\Resource\Factory; +use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\ResourceClassNotFoundException; use ApiPlatform\Core\Metadata\Extractor\XmlExtractor; use ApiPlatform\Core\Metadata\Extractor\YamlExtractor; use ApiPlatform\Core\Metadata\Resource\Factory\ExtractorResourceMetadataFactory; @@ -43,12 +45,11 @@ public function testXmlCreateResourceMetadata($expectedResourceMetadata) $this->assertEquals($expectedResourceMetadata, $resourceMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotFoundException - * @expectedExceptionMessage Resource "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" not found. - */ public function testXmlDoesNotExistMetadataFactory() { + $this->expectException(ResourceClassNotFoundException::class); + $this->expectExceptionMessage('Resource "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.xml'; $factory = new ExtractorResourceNameCollectionFactory(new XmlExtractor([$configPath])); $resourceMetadataFactory = new ExtractorResourceMetadataFactory(new XmlExtractor([$configPath])); @@ -120,11 +121,10 @@ public function testXmlNoItemOperationsResourceMetadata($expectedResourceMetadat $this->assertEquals($expectedResourceMetadata, $resourceMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testInvalidXmlResourceMetadataFactory() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcesinvalid.xml'; $resourceMetadataFactory = new ExtractorResourceMetadataFactory(new XmlExtractor([$configPath])); @@ -180,12 +180,11 @@ public function testYamlCreateResourceMetadata(ResourceMetadata $expectedResourc $this->assertEquals($expectedResourceMetadata, $resourceMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\ResourceClassNotFoundException - * @expectedExceptionMessage Resource "ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\ThisDoesNotExist" not found. - */ public function testYamlDoesNotExistMetadataFactory() { + $this->expectException(ResourceClassNotFoundException::class); + $this->expectExceptionMessage('Resource "ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\ThisDoesNotExist" not found.'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcenotfound.yml'; $factory = new ExtractorResourceNameCollectionFactory(new YamlExtractor([$configPath])); $resourceMetadataFactory = new ExtractorResourceMetadataFactory(new YamlExtractor([$configPath])); @@ -258,22 +257,20 @@ public function testYamlExistingParentResourceMetadataFactory(ResourceMetadata $ $this->assertEquals($expectedResourceMetadata, $resourceMetadata); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testCreateWithMalformedYaml() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/parse_exception.yml'; (new ExtractorResourceMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /"ApiPlatform\\Core\\Tests\\Fixtures\\TestBundle\\Entity\\Dummy" setting is expected to be null or an array, string given in ".+\/Fixtures\/FileConfigurations\/bad_declaration\.yml"\./ - */ public function testCreateWithBadDeclaration() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageRegExp('/"ApiPlatform\\\\Core\\\\Tests\\\\Fixtures\\\\TestBundle\\\\Entity\\\\Dummy" setting is expected to be null or an array, string given in ".+\\/Fixtures\\/FileConfigurations\\/bad_declaration\\.yml"\\./'); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/bad_declaration.yml'; (new ExtractorResourceMetadataFactory(new YamlExtractor([$configPath])))->create(FileConfigDummy::class); diff --git a/tests/Metadata/Resource/Factory/ExtractorResourceNameCollectionFactoryTest.php b/tests/Metadata/Resource/Factory/ExtractorResourceNameCollectionFactoryTest.php index 9537210c4a3..69606bd7679 100644 --- a/tests/Metadata/Resource/Factory/ExtractorResourceNameCollectionFactoryTest.php +++ b/tests/Metadata/Resource/Factory/ExtractorResourceNameCollectionFactoryTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Core\Tests\Metadata\Resource\Factory; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Extractor\XmlExtractor; use ApiPlatform\Core\Metadata\Extractor\YamlExtractor; use ApiPlatform\Core\Metadata\Resource\Factory\ExtractorResourceNameCollectionFactory; @@ -39,11 +40,10 @@ public function testXmlResourceName() ])); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testInvalidExtractorResourceNameCollectionFactory() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/resourcesinvalid.xml'; $factory = new ExtractorResourceNameCollectionFactory(new XmlExtractor([$configPath])); $factory->create(); @@ -68,11 +68,10 @@ public function testYamlSingleResourceName() $this->assertEquals($factory->create(), new ResourceNameCollection([FileConfigDummy::class])); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - */ public function testCreateWithMalformedYaml() { + $this->expectException(InvalidArgumentException::class); + $configPath = __DIR__.'/../../../Fixtures/FileConfigurations/parse_exception.yml'; (new ExtractorResourceNameCollectionFactory(new YamlExtractor([$configPath])))->create(); diff --git a/tests/PathResolver/DashOperationPathResolverTest.php b/tests/PathResolver/DashOperationPathResolverTest.php index 36e93196966..6957c536d92 100644 --- a/tests/PathResolver/DashOperationPathResolverTest.php +++ b/tests/PathResolver/DashOperationPathResolverTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\PathResolver; use ApiPlatform\Core\Api\OperationType; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\PathResolver\DashOperationPathResolver; use PHPUnit\Framework\TestCase; @@ -46,12 +47,12 @@ public function testResolveItemOperationPath() /** * @expectedDeprecation The use of ApiPlatform\Core\PathResolver\DashOperationPathResolver is deprecated since 2.1. Please use ApiPlatform\Core\Operation\DashPathSegmentNameGenerator instead. - * - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedMessage Subresource operations are not supported by the OperationPathResolver. */ public function testResolveSubresourceOperationPath() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Subresource operations are not supported by the OperationPathResolver.'); + $dashOperationPathResolver = new DashOperationPathResolver(); $dashOperationPathResolver->resolveOperationPath('ShortName', ['property' => 'bar', 'identifiers' => [['id', 'class'], ['relatedId', 'class']], 'collection' => false], OperationType::SUBRESOURCE, 'get'); diff --git a/tests/PathResolver/UnderscoreOperationPathResolverTest.php b/tests/PathResolver/UnderscoreOperationPathResolverTest.php index 82a7916a785..21a24e3bc6b 100644 --- a/tests/PathResolver/UnderscoreOperationPathResolverTest.php +++ b/tests/PathResolver/UnderscoreOperationPathResolverTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\PathResolver; use ApiPlatform\Core\Api\OperationType; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\PathResolver\UnderscoreOperationPathResolver; use PHPUnit\Framework\TestCase; @@ -46,12 +47,12 @@ public function testResolveItemOperationPath() /** * @expectedDeprecation The use of ApiPlatform\Core\PathResolver\UnderscoreOperationPathResolver is deprecated since 2.1. Please use ApiPlatform\Core\Operation\UnderscorePathSegmentNameGenerator instead. - * - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedMessage Subresource operations are not supported by the OperationPathResolver. */ public function testResolveSubresourceOperationPath() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Subresource operations are not supported by the OperationPathResolver.'); + $dashOperationPathResolver = new UnderscoreOperationPathResolver(); $dashOperationPathResolver->resolveOperationPath('ShortName', ['property' => 'relatedFoo', 'identifiers' => [['id', 'class']], 'collection' => true], OperationType::SUBRESOURCE, 'get'); diff --git a/tests/Security/EventListener/DenyAccessListenerTest.php b/tests/Security/EventListener/DenyAccessListenerTest.php index d51ecc26837..63de9ddb29d 100644 --- a/tests/Security/EventListener/DenyAccessListenerTest.php +++ b/tests/Security/EventListener/DenyAccessListenerTest.php @@ -26,6 +26,7 @@ use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Role\RoleHierarchyInterface; /** @@ -87,11 +88,10 @@ public function testIsGranted() $listener->onKernelRequest($event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - */ public function testIsNotGranted() { + $this->expectException(AccessDeniedException::class); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); @@ -110,12 +110,11 @@ public function testIsNotGranted() $listener->onKernelRequest($event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - * @expectedExceptionMessage You are not admin. - */ public function testAccessControlMessage() { + $this->expectException(AccessDeniedException::class); + $this->expectExceptionMessage('You are not admin.'); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); @@ -160,10 +159,11 @@ public function testIsGrantedLegacy() /** * @group legacy - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException */ public function testIsNotGrantedLegacy() { + $this->expectException(AccessDeniedException::class); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); @@ -183,11 +183,12 @@ public function testIsNotGrantedLegacy() } /** - * @expectedException \LogicException * @group legacy */ public function testSecurityComponentNotAvailable() { + $this->expectException(\LogicException::class); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); @@ -204,11 +205,12 @@ public function testSecurityComponentNotAvailable() } /** - * @expectedException \LogicException * @group legacy */ public function testExpressionLanguageNotInstalled() { + $this->expectException(\LogicException::class); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); @@ -229,11 +231,12 @@ public function testExpressionLanguageNotInstalled() } /** - * @expectedException \LogicException * @group legacy */ public function testNotBehindAFirewall() { + $this->expectException(\LogicException::class); + $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'get']); $eventProphecy = $this->prophesize(GetResponseEvent::class); diff --git a/tests/Security/ResourceAccessCheckerTest.php b/tests/Security/ResourceAccessCheckerTest.php index a7b664a7815..8dd581b9b13 100644 --- a/tests/Security/ResourceAccessCheckerTest.php +++ b/tests/Security/ResourceAccessCheckerTest.php @@ -54,22 +54,20 @@ public function getGranted(): array return [[true], [false]]; } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The "symfony/security" library must be installed to use the "access_control" attribute. - */ public function testSecurityComponentNotAvailable() { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The "symfony/security" library must be installed to use the "access_control" attribute.'); + $checker = new ResourceAccessChecker($this->prophesize(ExpressionLanguage::class)->reveal()); $checker->isGranted(Dummy::class, 'has_role("ROLE_ADMIN")'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The "symfony/expression-language" library must be installed to use the "access_control". - */ public function testExpressionLanguageNotInstalled() { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The "symfony/expression-language" library must be installed to use the "access_control".'); + $authenticationTrustResolverProphecy = $this->prophesize(AuthenticationTrustResolverInterface::class); $tokenStorageProphecy = $this->prophesize(TokenStorageInterface::class); $tokenStorageProphecy->getToken()->willReturn($this->prophesize(TokenInterface::class)->reveal()); @@ -78,12 +76,11 @@ public function testExpressionLanguageNotInstalled() $checker->isGranted(Dummy::class, 'has_role("ROLE_ADMIN")'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The current token must be set to use the "access_control" attribute (is the URL behind a firewall?). - */ public function testNotBehindAFirewall() { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The current token must be set to use the "access_control" attribute (is the URL behind a firewall?).'); + $authenticationTrustResolverProphecy = $this->prophesize(AuthenticationTrustResolverInterface::class); $tokenStorageProphecy = $this->prophesize(TokenStorageInterface::class); diff --git a/tests/Serializer/AbstractItemNormalizerTest.php b/tests/Serializer/AbstractItemNormalizerTest.php index 9f764c55e39..420c6e5c898 100644 --- a/tests/Serializer/AbstractItemNormalizerTest.php +++ b/tests/Serializer/AbstractItemNormalizerTest.php @@ -16,6 +16,7 @@ use ApiPlatform\Core\Api\IriConverterInterface; use ApiPlatform\Core\Api\ResourceClassResolverInterface; use ApiPlatform\Core\DataProvider\ItemDataProviderInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -356,12 +357,11 @@ public function testDenormalizeWritableLinks() ], Dummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Expected IRI or nested document for attribute "relatedDummy", "integer" given. - */ public function testBadRelationType() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Expected IRI or nested document for attribute "relatedDummy", "integer" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn( new PropertyNameCollection(['relatedDummy']) @@ -400,12 +400,11 @@ public function testBadRelationType() $normalizer->denormalize(['relatedDummy' => 22], Dummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Nested documents for attribute "relatedDummy" are not allowed. Use IRIs instead. - */ public function testInnerDocumentNotAllowed() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Nested documents for attribute "relatedDummy" are not allowed. Use IRIs instead.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn( new PropertyNameCollection(['relatedDummy']) @@ -444,12 +443,11 @@ public function testInnerDocumentNotAllowed() $normalizer->denormalize(['relatedDummy' => ['foo' => 'bar']], Dummy::class); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The type of the "foo" attribute must be "float", "integer" given. - */ public function testBadType() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The type of the "foo" attribute must be "float", "integer" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn( new PropertyNameCollection(['foo']) @@ -511,12 +509,11 @@ public function testJsonAllowIntAsFloat() $normalizer->denormalize(['foo' => 42], Dummy::class, 'jsonfoo'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The type of the key "a" must be "int", "string" given. - */ public function testDenormalizeBadKeyType() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The type of the key "a" must be "int", "string" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn( new PropertyNameCollection(['relatedDummies']) @@ -691,12 +688,11 @@ public function testDenormalizeRelationWithPlainId() $normalizer->denormalize(['relatedDummy' => 1], Dummy::class, 'jsonld'); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Expected IRI or nested document for attribute "relatedDummy", "integer" given. - */ public function testDoNotDenormalizeRelationWithPlainIdWhenPlainIdentifiersAreNotAllowed() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Expected IRI or nested document for attribute "relatedDummy", "integer" given.'); + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->willReturn( new PropertyNameCollection(['relatedDummy']) diff --git a/tests/Serializer/ItemNormalizerTest.php b/tests/Serializer/ItemNormalizerTest.php index 99fd1292661..93b4ab4faef 100644 --- a/tests/Serializer/ItemNormalizerTest.php +++ b/tests/Serializer/ItemNormalizerTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Core\Api\IriConverterInterface; use ApiPlatform\Core\Api\ResourceClassResolverInterface; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -157,12 +158,11 @@ public function testDenormalizeWithIri() $this->assertInstanceOf(Dummy::class, $normalizer->denormalize(['id' => '/dummies/12', 'name' => 'hello'], Dummy::class, null, $context)); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Update is not allowed for this operation. - */ public function testDenormalizeWithIdAndUpdateNotAllowed() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Update is not allowed for this operation.'); + $context = ['resource_class' => Dummy::class, 'api_allow_update' => false]; $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); diff --git a/tests/Serializer/SerializerContextBuilderTest.php b/tests/Serializer/SerializerContextBuilderTest.php index 4445c45c58d..4cbb79a1d01 100644 --- a/tests/Serializer/SerializerContextBuilderTest.php +++ b/tests/Serializer/SerializerContextBuilderTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Core\Tests\Serializer; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Serializer\SerializerContextBuilder; @@ -83,11 +84,10 @@ public function testCreateFromRequest() $this->assertEquals($expected, $this->builder->createFromRequest($request, false)); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - */ public function testThrowExceptionOnInvalidRequest() { + $this->expectException(RuntimeException::class); + $this->builder->createFromRequest(new Request(), false); } diff --git a/tests/Serializer/SerializerFilterContextBuilderTest.php b/tests/Serializer/SerializerFilterContextBuilderTest.php index b8e83a2d807..d90723cb0a1 100644 --- a/tests/Serializer/SerializerFilterContextBuilderTest.php +++ b/tests/Serializer/SerializerFilterContextBuilderTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Serializer; use ApiPlatform\Core\Api\FilterInterface; +use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; use ApiPlatform\Core\Serializer\Filter\FilterInterface as SerializerFilterInterface; @@ -187,12 +188,11 @@ public function testCreateFromRequestWithoutAttributes() $this->assertInternalType('array', $context); } - /** - * @expectedException \ApiPlatform\Core\Exception\RuntimeException - * @expectedExceptionMessage Request attributes are not valid. - */ public function testCreateFromRequestThrowsExceptionWithoutAttributesAndRequestAttributes() { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Request attributes are not valid.'); + $request = new Request(); $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); diff --git a/tests/Swagger/Serializer/DocumentationNormalizerTest.php b/tests/Swagger/Serializer/DocumentationNormalizerTest.php index 824e9a433e7..1726b281887 100644 --- a/tests/Swagger/Serializer/DocumentationNormalizerTest.php +++ b/tests/Swagger/Serializer/DocumentationNormalizerTest.php @@ -19,6 +19,7 @@ use ApiPlatform\Core\Api\UrlGeneratorInterface; use ApiPlatform\Core\Bridge\Symfony\Routing\RouterOperationPathResolver; use ApiPlatform\Core\Documentation\Documentation; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; @@ -1263,12 +1264,11 @@ public function testFiltersWithDeprecatedFilterCollection() ])); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The "$filterLocator" argument is expected to be an implementation of the "Psr\Container\ContainerInterface" interface or null. - */ public function testConstructWithInvalidFilterLocator() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "$filterLocator" argument is expected to be an implementation of the "Psr\\Container\\ContainerInterface" interface or null.'); + new DocumentationNormalizer( $this->prophesize(ResourceMetadataFactoryInterface::class)->reveal(), $this->prophesize(PropertyNameCollectionFactoryInterface::class)->reveal(), diff --git a/tests/Util/IriHelperTest.php b/tests/Util/IriHelperTest.php index f9f797481ce..689a7a13cf4 100644 --- a/tests/Util/IriHelperTest.php +++ b/tests/Util/IriHelperTest.php @@ -13,6 +13,7 @@ namespace ApiPlatform\Core\Tests\Util; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Util\IriHelper; use PHPUnit\Framework\TestCase; @@ -69,12 +70,11 @@ public function testHelpersWithAbsoluteUrl() $this->assertEquals('https://foo:bar@localhost:443/hello.json?foo=bar&bar=3&page=2#foo', IriHelper::createIri($parsed['parts'], $parsed['parameters'], 'page', 2., true)); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage The request URI "http:///" is malformed. - */ public function testParseIriWithInvalidUrl() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The request URI "http:///" is malformed.'); + IriHelper::parseIri('http:///', 'page'); } } diff --git a/tests/Validator/EventListener/ValidateListenerTest.php b/tests/Validator/EventListener/ValidateListenerTest.php index 600efe0b8f5..6ed24118185 100644 --- a/tests/Validator/EventListener/ValidateListenerTest.php +++ b/tests/Validator/EventListener/ValidateListenerTest.php @@ -82,11 +82,10 @@ public function testDoNotCallWhenReceiveFlagIsFalse() $validationViewListener->onKernelView($event); } - /** - * @expectedException \ApiPlatform\Core\Validator\Exception\ValidationException - */ public function testThrowsValidationExceptionWithViolationsFound() { + $this->expectException(ValidationException::class); + $data = new DummyEntity(); $expectedValidationGroups = ['a', 'b', 'c']; From 3e5d6295f2c86a45e008b47b586d8961e2b80b42 Mon Sep 17 00:00:00 2001 From: abluchet Date: Tue, 5 Jun 2018 15:44:21 +0200 Subject: [PATCH 4/7] Style fixes --- tests/Annotation/ApiResourceTest.php | 8 ++++---- tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php | 2 +- .../Doctrine/Orm/SubresourceDataProviderTest.php | 2 +- .../Doctrine/Orm/Util/IdentifierManagerTraitTest.php | 2 +- .../RamseyUuid/Normalizer/UuidNormalizerTest.php | 5 ++--- tests/Bridge/Symfony/Routing/IriConverterTest.php | 6 +++--- tests/EventListener/ReadListenerTest.php | 12 +++++------- .../Normalizer/DateTimeIdentifierNormalizerTest.php | 5 ++--- 8 files changed, 19 insertions(+), 23 deletions(-) diff --git a/tests/Annotation/ApiResourceTest.php b/tests/Annotation/ApiResourceTest.php index 7c8b1b33ea0..81cf09f6cfb 100644 --- a/tests/Annotation/ApiResourceTest.php +++ b/tests/Annotation/ApiResourceTest.php @@ -14,6 +14,7 @@ namespace ApiPlatform\Core\Tests\Annotation; use ApiPlatform\Core\Annotation\ApiResource; +use ApiPlatform\Core\Exception\InvalidArgumentException; use ApiPlatform\Core\Tests\Fixtures\AnnotatedClass; use Doctrine\Common\Annotations\AnnotationReader; use PHPUnit\Framework\TestCase; @@ -102,12 +103,11 @@ public function testApiResourceAnnotation() ], $resource->attributes); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException - * @expectedExceptionMessage Unknown property "invalidAttribute" on annotation "ApiPlatform\Core\Annotation\ApiResource". - */ public function testConstructWithInvalidAttribute() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unknown property "invalidAttribute" on annotation "ApiPlatform\\Core\\Annotation\\ApiResource".'); + new ApiResource([ 'shortName' => 'shortName', 'routePrefix' => '/foo', diff --git a/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php b/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php index f1ba80154c0..5e41f173b1d 100644 --- a/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php +++ b/tests/Bridge/Doctrine/Orm/ItemDataProviderTest.php @@ -17,9 +17,9 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\ItemDataProvider; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; -use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Exception\PropertyNotFoundException; use ApiPlatform\Core\Exception\RuntimeException; +use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; diff --git a/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php b/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php index e3ec6a7abcb..b6137655153 100644 --- a/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php +++ b/tests/Bridge/Doctrine/Orm/SubresourceDataProviderTest.php @@ -16,9 +16,9 @@ use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface; use ApiPlatform\Core\Bridge\Doctrine\Orm\SubresourceDataProvider; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; -use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Exception\ResourceClassNotSupportedException; use ApiPlatform\Core\Exception\RuntimeException; +use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyMetadata; diff --git a/tests/Bridge/Doctrine/Orm/Util/IdentifierManagerTraitTest.php b/tests/Bridge/Doctrine/Orm/Util/IdentifierManagerTraitTest.php index f019c5bb4a3..cd0fe670f86 100644 --- a/tests/Bridge/Doctrine/Orm/Util/IdentifierManagerTraitTest.php +++ b/tests/Bridge/Doctrine/Orm/Util/IdentifierManagerTraitTest.php @@ -93,7 +93,7 @@ public function testCompositeIdentifier() public function testInvalidIdentifier() { $this->expectException(PropertyNotFoundException::class); - $this->expectExceptionMessage('Invalid identifier "idbad=1;idb=2", "ida" has not been found.'); + $this->expectExceptionMessage('Invalid identifier "idbad=1;idb=2", "ida" was not found.'); list($propertyNameCollectionFactory, $propertyMetadataFactory) = $this->getMetadataFactories(Dummy::class, [ 'ida', diff --git a/tests/Bridge/RamseyUuid/Normalizer/UuidNormalizerTest.php b/tests/Bridge/RamseyUuid/Normalizer/UuidNormalizerTest.php index def11451314..eaf83bbf406 100644 --- a/tests/Bridge/RamseyUuid/Normalizer/UuidNormalizerTest.php +++ b/tests/Bridge/RamseyUuid/Normalizer/UuidNormalizerTest.php @@ -34,11 +34,10 @@ public function testNoSupportDenormalizeUuid() $this->assertFalse($normalizer->supportsDenormalization($uuid, '')); } - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidIdentifierException - */ public function testFailDenormalizeUuid() { + $this->expectException(\ApiPlatform\Core\Exception\InvalidIdentifierException::class); + $uuid = 'notanuuid'; $normalizer = new UuidNormalizer(); $this->assertTrue($normalizer->supportsDenormalization($uuid, Uuid::class)); diff --git a/tests/Bridge/Symfony/Routing/IriConverterTest.php b/tests/Bridge/Symfony/Routing/IriConverterTest.php index fc4dd9e6b0a..a55eac1c18f 100644 --- a/tests/Bridge/Symfony/Routing/IriConverterTest.php +++ b/tests/Bridge/Symfony/Routing/IriConverterTest.php @@ -21,10 +21,10 @@ use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameResolverInterface; use ApiPlatform\Core\DataProvider\ItemDataProviderInterface; use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface; -use ApiPlatform\Core\Exception\InvalidIdentifierException; -use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Exception\InvalidArgumentException; +use ApiPlatform\Core\Exception\InvalidIdentifierException; use ApiPlatform\Core\Exception\ItemNotFoundException; +use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -280,7 +280,7 @@ public function testGetItemFromIriBadIdentifierException() 'id' => 3, ])->shouldBeCalledTimes(1); $identifierDenormalizerProphecy = $this->prophesize(ChainIdentifierDenormalizer::class); - $identifierDenormalizerProphecy->denormalize('3', Dummy::class)->shouldBeCalled()->willThrow(new InvalidIdentifierException('fail')); + $identifierDenormalizerProphecy->denormalize('3', Dummy::class)->shouldBeCalled()->willThrow(new InvalidIdentifierException('Item not found for "/users/3".')); $converter = $this->getIriConverter($routerProphecy, $routeNameResolverProphecy, null, null, $identifierDenormalizerProphecy); $this->assertEquals($converter->getItemFromIri('/users/3', ['fetch_data' => true]), $item); } diff --git a/tests/EventListener/ReadListenerTest.php b/tests/EventListener/ReadListenerTest.php index 77f9c27fa1c..46b6f584da6 100644 --- a/tests/EventListener/ReadListenerTest.php +++ b/tests/EventListener/ReadListenerTest.php @@ -18,8 +18,8 @@ use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface; use ApiPlatform\Core\EventListener\ReadListener; use ApiPlatform\Core\Exception\InvalidIdentifierException; -use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use ApiPlatform\Core\Exception\RuntimeException; +use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Symfony\Component\HttpFoundation\Request; @@ -292,11 +292,10 @@ public function testRetrieveItemNotFound() $listener->onKernelRequest($event->reveal()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testRetrieveBadItemNormalizedIdentifiers() { + $this->expectException(NotFoundHttpException::class); + $identifierDenormalizer = $this->prophesize(ChainIdentifierDenormalizer::class); $identifierDenormalizer->denormalize('1', 'Foo')->shouldBeCalled()->willThrow(new InvalidIdentifierException()); @@ -314,11 +313,10 @@ public function testRetrieveBadItemNormalizedIdentifiers() $listener->onKernelRequest($event->reveal()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testRetrieveBadSubresourceNormalizedIdentifiers() { + $this->expectException(NotFoundHttpException::class); + $identifierDenormalizer = $this->prophesize(ChainIdentifierDenormalizer::class); $identifierDenormalizer->denormalize(Argument::type('string'), Argument::type('string'))->shouldBeCalled()->willThrow(new InvalidIdentifierException()); diff --git a/tests/Identifier/Normalizer/DateTimeIdentifierNormalizerTest.php b/tests/Identifier/Normalizer/DateTimeIdentifierNormalizerTest.php index c21e31ac1a0..c1963fe5c9f 100644 --- a/tests/Identifier/Normalizer/DateTimeIdentifierNormalizerTest.php +++ b/tests/Identifier/Normalizer/DateTimeIdentifierNormalizerTest.php @@ -21,11 +21,10 @@ */ class DateTimeIdentifierNormalizerTest extends TestCase { - /** - * @expectedException \ApiPlatform\Core\Exception\InvalidIdentifierException - */ public function testDenormalize() { + $this->expectException(\ApiPlatform\Core\Exception\InvalidIdentifierException::class); + $normalizer = new DateTimeIdentifierDenormalizer(); $normalizer->denormalize('not valid', \DateTimeImmutable::class); } From de389fff7b77c8d256253823b6e2875180039e6f Mon Sep 17 00:00:00 2001 From: Teoh Han Hui Date: Tue, 5 Jun 2018 17:00:06 +0200 Subject: [PATCH 5/7] Move lint jobs to CircleCI --- .circleci/config.yml | 80 ++++++++++++++++++++++++++++++++++++++++---- .php_cs.dist | 27 +++++++++------ .travis.yml | 32 +++--------------- 3 files changed, 96 insertions(+), 43 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 513d7342876..8a6e170d8ae 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,6 +25,12 @@ reusable-steps: - npm-cache-{{ .Revision }} - npm-cache-{{ .Branch }} - npm-cache + - &restore-php-cs-fixer-cache + restore_cache: + keys: + - php-cs-fixer-cache-{{ .Revision }} + - php-cs-fixer-cache-{{ .Branch }} + - php-cs-fixer-cache - &save-composer-cache-by-branch save_cache: paths: @@ -45,6 +51,16 @@ reusable-steps: paths: - ~/.npm key: npm-cache-{{ .Revision }}-{{ .BuildNum }} + - &save-php-cs-fixer-cache-by-branch + save_cache: + paths: + - .php_cs.cache + key: php-cs-fixer-cache-{{ .Branch }}-{{ .BuildNum }} + - &save-php-cs-fixer-cache-by-revision + save_cache: + paths: + - .php_cs.cache + key: php-cs-fixer-cache-{{ .Revision }}-{{ .BuildNum }} - &update-composer run: name: Update Composer @@ -55,7 +71,55 @@ reusable-steps: command: composer update --prefer-dist --no-progress --no-suggest --ansi jobs: - phpunit-php-7.2-coverage: + php-cs-fixer: + docker: + - image: circleci/php:7.2-node-browsers + environment: + PHP_CS_FIXER_FUTURE_MODE: 1 + working_directory: ~/api-platform/core + steps: + - checkout + - *restore-composer-cache + - *restore-php-cs-fixer-cache + - *disable-xdebug-php-extension + - *disable-php-memory-limit + - *update-composer + - run: + name: Install PHP-CS-Fixer + command: composer global require friendsofphp/php-cs-fixer:^2.12 + - *save-composer-cache-by-revision + - *save-composer-cache-by-branch + - run: + name: Run PHP-CS-Fixer + command: |- + export PATH="$PATH:$HOME/.composer/vendor/bin" + php-cs-fixer fix --dry-run --diff --ansi + - *save-php-cs-fixer-cache-by-revision + - *save-php-cs-fixer-cache-by-branch + + phpstan: + docker: + - image: circleci/php:7.2-node-browsers + working_directory: ~/api-platform/core + steps: + - checkout + - *restore-composer-cache + - *disable-xdebug-php-extension + - *disable-php-memory-limit + - *update-composer + - *update-project-dependencies + - run: + name: Install PHPStan + command: composer global require phpstan/phpstan:^0.8 + - *save-composer-cache-by-revision + - *save-composer-cache-by-branch + - run: + name: Run PHPStan + command: |- + export PATH="$PATH:$HOME/.composer/vendor/bin" + phpstan analyse -c phpstan.neon -l5 --ansi src tests + + phpunit-coverage: docker: - image: circleci/php:7.2-node-browsers environment: @@ -98,7 +162,7 @@ jobs: - *save-npm-cache-by-revision - *save-npm-cache-by-branch - behat-php-7.2-coverage: + behat-coverage: docker: - image: circleci/php:7.2-node-browsers environment: @@ -181,11 +245,15 @@ jobs: workflows: version: 2 + lint: + jobs: + - php-cs-fixer + - phpstan test-with-coverage: jobs: - - phpunit-php-7.2-coverage - - behat-php-7.2-coverage + - phpunit-coverage + - behat-coverage - merge-and-upload-coverage: requires: - - phpunit-php-7.2-coverage - - behat-php-7.2-coverage + - phpunit-coverage + - behat-coverage diff --git a/.php_cs.dist b/.php_cs.dist index 6e8308e2308..bb45efae9ac 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -42,16 +42,23 @@ return PhpCsFixer\Config::create() 'location' => 'after_open', ], 'modernize_types_casting' => true, - 'no_extra_consecutive_blank_lines' => [ - 'break', - 'continue', - 'curly_brace_block', - 'extra', - 'parenthesis_brace_block', - 'return', - 'square_brace_block', - 'throw', - 'use', + 'native_function_invocation' => [ + 'include' => [ + '@compiler_optimized', + ], + ], + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'break', + 'continue', + 'curly_brace_block', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'throw', + 'use', + ], ], 'no_useless_else' => true, 'no_useless_return' => true, diff --git a/.travis.yml b/.travis.yml index 876cf5b886f..568cb139241 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,8 +16,6 @@ matrix: - php: '7.0' - php: '7.1' - php: '7.2' - - php: '7.2' - env: lint=1 - php: '7.2' env: deps=low - php: '7.2' @@ -40,12 +38,6 @@ matrix: before_install: - phpenv config-rm xdebug.ini || echo "xdebug not available" - echo "memory_limit=-1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - - if [[ $lint = 1 ]]; then - wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v2.12.0/php-cs-fixer.phar; - fi - - if [[ $lint = 1 ]]; then - composer global require --dev 'phpstan/phpstan:^0.8'; - fi - export PATH="$PATH:$HOME/.composer/vendor/bin" install: @@ -56,26 +48,12 @@ install: fi script: - - if [[ $lint != 1 ]]; then - tests/Fixtures/app/console cache:clear; - fi - - if [[ $lint != 1 ]]; then - vendor/bin/phpunit; - fi - - if [[ $lint != 1 ]]; then - tests/Fixtures/app/console cache:clear; - fi + - tests/Fixtures/app/console cache:clear + - vendor/bin/phpunit + - tests/Fixtures/app/console cache:clear - if [[ $APP_ENV = 'postgres' ]]; then vendor/bin/behat --suite=postgres --format=progress; - elif [[ $lint != 1 ]]; then + else vendor/bin/behat --suite=default --format=progress; fi - - if [[ $lint != 1 ]]; then - tests/Fixtures/app/console api:swagger:export > swagger.json && npx swagger-cli validate swagger.json && rm swagger.json; - fi - - if [[ $lint = 1 ]]; then - php php-cs-fixer.phar fix --dry-run --diff --no-ansi; - fi - - if [[ $lint = 1 ]]; then - phpstan analyse -c phpstan.neon -l5 --ansi src tests; - fi + - tests/Fixtures/app/console api:swagger:export > swagger.json && npx swagger-cli validate swagger.json && rm swagger.json From 3ea975594050f49181ce3b9da931409ba8577b40 Mon Sep 17 00:00:00 2001 From: Teoh Han Hui Date: Tue, 5 Jun 2018 18:56:06 +0200 Subject: [PATCH 6/7] Fix files with PHP-CS-Fixer (native_function_invocation) --- features/bootstrap/FeatureContext.php | 16 ++++++++-------- features/bootstrap/HydraContext.php | 4 ++-- features/bootstrap/JsonContext.php | 4 ++-- features/bootstrap/SwaggerContext.php | 2 +- src/Bridge/Doctrine/Common/DataPersister.php | 2 +- src/DataProvider/ChainItemDataProvider.php | 2 +- .../ConstraintViolationListNormalizer.php | 2 +- src/JsonApi/Serializer/ItemNormalizer.php | 6 +++--- .../ReservedAttributeNameConverter.php | 2 +- .../Factory/OperationResourceMetadataFactory.php | 4 ++-- src/Serializer/AbstractCollectionNormalizer.php | 8 ++++---- src/Serializer/SerializerContextBuilder.php | 2 +- src/Util/AnnotationFilterExtractorTrait.php | 4 ++-- .../Orm/Extension/PaginationExtensionTest.php | 2 +- .../ApiPlatformExtensionTest.php | 2 +- .../ChainCollectionDataProviderTest.php | 2 +- .../SerializableResourceDenormalizer.php | 2 +- tests/JsonApi/Serializer/ItemNormalizerTest.php | 2 +- tests/Metadata/Resource/ResourceMetadataTest.php | 4 ++-- 19 files changed, 36 insertions(+), 36 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 67d14788597..2375594a07d 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -386,9 +386,9 @@ public function thereAreDummyObjectsWithDummyDateAndDummyBoolean(int $nb, string { $descriptions = ['Smart dummy.', 'Not so smart dummy.']; - if (in_array($bool, ['true', '1', 1], true)) { + if (\in_array($bool, ['true', '1', 1], true)) { $bool = true; - } elseif (in_array($bool, ['false', '0', 0], true)) { + } elseif (\in_array($bool, ['false', '0', 0], true)) { $bool = false; } else { $expected = ['true', 'false', '1', '0']; @@ -496,9 +496,9 @@ public function thereAreDummyObjectsWithDummyPrice(int $nb) */ public function thereAreDummyObjectsWithDummyBoolean(int $nb, string $bool) { - if (in_array($bool, ['true', '1', 1], true)) { + if (\in_array($bool, ['true', '1', 1], true)) { $bool = true; - } elseif (in_array($bool, ['false', '0', 0], true)) { + } elseif (\in_array($bool, ['false', '0', 0], true)) { $bool = false; } else { $expected = ['true', 'false', '1', '0']; @@ -524,9 +524,9 @@ public function thereAreDummyObjectsWithDummyBoolean(int $nb, string $bool) */ public function thereAreDummyObjectsWithEmbeddedDummyBoolean(int $nb, string $bool) { - if (in_array($bool, ['true', '1', 1], true)) { + if (\in_array($bool, ['true', '1', 1], true)) { $bool = true; - } elseif (in_array($bool, ['false', '0', 0], true)) { + } elseif (\in_array($bool, ['false', '0', 0], true)) { $bool = false; } else { $expected = ['true', 'false', '1', '0']; @@ -551,9 +551,9 @@ public function thereAreDummyObjectsWithEmbeddedDummyBoolean(int $nb, string $bo */ public function thereAreDummyObjectsWithRelationEmbeddedDummyBoolean(int $nb, string $bool) { - if (in_array($bool, ['true', '1', 1], true)) { + if (\in_array($bool, ['true', '1', 1], true)) { $bool = true; - } elseif (in_array($bool, ['false', '0', 0], true)) { + } elseif (\in_array($bool, ['false', '0', 0], true)) { $bool = false; } else { $expected = ['true', 'false', '1', '0']; diff --git a/features/bootstrap/HydraContext.php b/features/bootstrap/HydraContext.php index f0f9b765cb5..4bb02f43d75 100644 --- a/features/bootstrap/HydraContext.php +++ b/features/bootstrap/HydraContext.php @@ -118,7 +118,7 @@ public function assertOperationNodeValueContains(string $nodeName, string $opera */ public function assertNbOperationsExist(int $nb, string $className) { - Assert::assertEquals($nb, count($this->getOperations($className))); + Assert::assertEquals($nb, \count($this->getOperations($className))); } /** @@ -126,7 +126,7 @@ public function assertNbOperationsExist(int $nb, string $className) */ public function assertNbPropertiesExist(int $nb, string $className) { - Assert::assertEquals($nb, count($this->getProperties($className))); + Assert::assertEquals($nb, \count($this->getProperties($className))); } /** diff --git a/features/bootstrap/JsonContext.php b/features/bootstrap/JsonContext.php index b56a60523b1..c432860437f 100644 --- a/features/bootstrap/JsonContext.php +++ b/features/bootstrap/JsonContext.php @@ -26,14 +26,14 @@ public function __construct(HttpCallResultPool $httpCallResultPool) private function sortArrays($obj) { - $isObject = is_object($obj); + $isObject = \is_object($obj); foreach ($obj as $key => $value) { if (null === $value || is_scalar($value)) { continue; } - if (is_array($value)) { + if (\is_array($value)) { sort($value); } diff --git a/features/bootstrap/SwaggerContext.php b/features/bootstrap/SwaggerContext.php index 75da107e6dd..643026de458 100644 --- a/features/bootstrap/SwaggerContext.php +++ b/features/bootstrap/SwaggerContext.php @@ -90,7 +90,7 @@ public function assertPropertyExist(string $propertyName, string $className) */ public function assertPropertyIsRequired(string $propertyName, string $className) { - if (!in_array($propertyName, $this->getClassInfo($className)->required, true)) { + if (!\in_array($propertyName, $this->getClassInfo($className)->required, true)) { throw new ExpectationFailedException(sprintf('Property "%s" of class "%s" should be required', $propertyName, $className)); } } diff --git a/src/Bridge/Doctrine/Common/DataPersister.php b/src/Bridge/Doctrine/Common/DataPersister.php index d66a20ec0f1..52ddf7096fe 100644 --- a/src/Bridge/Doctrine/Common/DataPersister.php +++ b/src/Bridge/Doctrine/Common/DataPersister.php @@ -81,6 +81,6 @@ public function remove($data) */ private function getManager($data) { - return is_object($data) ? $this->managerRegistry->getManagerForClass($this->getObjectClass($data)) : null; + return \is_object($data) ? $this->managerRegistry->getManagerForClass($this->getObjectClass($data)) : null; } } diff --git a/src/DataProvider/ChainItemDataProvider.php b/src/DataProvider/ChainItemDataProvider.php index 76180f57b86..4158d6b4339 100644 --- a/src/DataProvider/ChainItemDataProvider.php +++ b/src/DataProvider/ChainItemDataProvider.php @@ -46,7 +46,7 @@ public function getItem(string $resourceClass, $id, string $operationName = null return $dataProvider->getItem($resourceClass, $id, $operationName, $context); } catch (ResourceClassNotSupportedException $e) { - @trigger_error(sprintf('Throwing a "%s" is deprecated in favor of implementing "%s"', get_class($e), RestrictedDataProviderInterface::class), E_USER_DEPRECATED); + @trigger_error(sprintf('Throwing a "%s" is deprecated in favor of implementing "%s"', \get_class($e), RestrictedDataProviderInterface::class), E_USER_DEPRECATED); continue; } } diff --git a/src/JsonApi/Serializer/ConstraintViolationListNormalizer.php b/src/JsonApi/Serializer/ConstraintViolationListNormalizer.php index 96ac9c92d13..95848ef0b7f 100644 --- a/src/JsonApi/Serializer/ConstraintViolationListNormalizer.php +++ b/src/JsonApi/Serializer/ConstraintViolationListNormalizer.php @@ -71,7 +71,7 @@ private function getSourcePointerFromViolation(ConstraintViolationInterface $vio $propertyMetadata = $this->propertyMetadataFactory ->create( // Im quite sure this requires some thought in case of validations over relationships - get_class($violation->getRoot()), + \get_class($violation->getRoot()), $fieldName ); diff --git a/src/JsonApi/Serializer/ItemNormalizer.php b/src/JsonApi/Serializer/ItemNormalizer.php index 3f39e432f8e..0d0f754f0dd 100644 --- a/src/JsonApi/Serializer/ItemNormalizer.php +++ b/src/JsonApi/Serializer/ItemNormalizer.php @@ -67,7 +67,7 @@ public function normalize($object, $format = null, array $context = []) // Get and populate attributes data $objectAttributesData = parent::normalize($object, $format, $context); - if (!is_array($objectAttributesData)) { + if (!\is_array($objectAttributesData)) { return $objectAttributesData; } @@ -147,7 +147,7 @@ protected function getAttributes($object, $format = null, array $context) */ protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = []) { - parent::setAttributeValue($object, $attribute, is_array($value) && array_key_exists('data', $value) ? $value['data'] : $value, $format, $context); + parent::setAttributeValue($object, $attribute, \is_array($value) && array_key_exists('data', $value) ? $value['data'] : $value, $format, $context); } /** @@ -164,7 +164,7 @@ protected function denormalizeRelation(string $attributeName, PropertyMetadata $ return $this->serializer->denormalize($value, $className, $format, $context); } - if (!is_array($value) || !isset($value['id'], $value['type'])) { + if (!\is_array($value) || !isset($value['id'], $value['type'])) { throw new InvalidArgumentException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.'); } diff --git a/src/JsonApi/Serializer/ReservedAttributeNameConverter.php b/src/JsonApi/Serializer/ReservedAttributeNameConverter.php index a6b6649bd47..add93d79bf9 100644 --- a/src/JsonApi/Serializer/ReservedAttributeNameConverter.php +++ b/src/JsonApi/Serializer/ReservedAttributeNameConverter.php @@ -57,7 +57,7 @@ public function normalize($propertyName) */ public function denormalize($propertyName) { - if (in_array($propertyName, self::JSON_API_RESERVED_ATTRIBUTES, true)) { + if (\in_array($propertyName, self::JSON_API_RESERVED_ATTRIBUTES, true)) { $propertyName = substr($propertyName, 1); } diff --git a/src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php b/src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php index 4813f52c61c..ec29d11859c 100644 --- a/src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php +++ b/src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php @@ -107,7 +107,7 @@ private function normalize(bool $collection, ResourceMetadata $resourceMetadata, $newOperations = []; foreach ($operations as $operationName => $operation) { // e.g.: @ApiResource(itemOperations={"get"}) - if (is_int($operationName) && is_string($operation)) { + if (\is_int($operationName) && \is_string($operation)) { $operationName = $operation; $operation = []; } @@ -132,7 +132,7 @@ private function normalize(bool $collection, ResourceMetadata $resourceMetadata, private function normalizeGraphQl(ResourceMetadata $resourceMetadata, array $operations) { foreach ($operations as $operationName => $operation) { - if (is_int($operationName) && is_string($operation)) { + if (\is_int($operationName) && \is_string($operation)) { unset($operations[$operationName]); $operations[$operation] = []; } diff --git a/src/Serializer/AbstractCollectionNormalizer.php b/src/Serializer/AbstractCollectionNormalizer.php index 870e593eef9..8f5cd27e64d 100644 --- a/src/Serializer/AbstractCollectionNormalizer.php +++ b/src/Serializer/AbstractCollectionNormalizer.php @@ -49,7 +49,7 @@ public function __construct(ResourceClassResolverInterface $resourceClassResolve */ public function supportsNormalization($data, $format = null) { - return static::FORMAT === $format && (is_array($data) || $data instanceof \Traversable); + return static::FORMAT === $format && (\is_array($data) || $data instanceof \Traversable); } /** @@ -97,13 +97,13 @@ protected function getPaginationConfig($object, array $context = []): array $paginated = 1. !== $lastPage = $object->getLastPage(); $totalItems = $object->getTotalItems(); } else { - $pageTotalItems = (float) count($object); + $pageTotalItems = (float) \count($object); } $currentPage = $object->getCurrentPage(); $itemsPerPage = $object->getItemsPerPage(); - } elseif (is_array($object) || $object instanceof \Countable) { - $totalItems = count($object); + } elseif (\is_array($object) || $object instanceof \Countable) { + $totalItems = \count($object); } return [$paginator, $paginated, $currentPage, $itemsPerPage, $lastPage, $pageTotalItems, $totalItems]; diff --git a/src/Serializer/SerializerContextBuilder.php b/src/Serializer/SerializerContextBuilder.php index 74962da44ca..f760f08635b 100644 --- a/src/Serializer/SerializerContextBuilder.php +++ b/src/Serializer/SerializerContextBuilder.php @@ -69,7 +69,7 @@ public function createFromRequest(Request $request, bool $normalization, array $ $context['operation_type'] = $operationType ?: OperationType::ITEM; if (!$normalization && !isset($context['api_allow_update'])) { - $context['api_allow_update'] = in_array($request->getMethod(), ['PUT', 'PATCH'], true); + $context['api_allow_update'] = \in_array($request->getMethod(), ['PUT', 'PATCH'], true); } $context['resource_class'] = $attributes['resource_class']; diff --git a/src/Util/AnnotationFilterExtractorTrait.php b/src/Util/AnnotationFilterExtractorTrait.php index 2c0c4e60aa4..5109a109112 100644 --- a/src/Util/AnnotationFilterExtractorTrait.php +++ b/src/Util/AnnotationFilterExtractorTrait.php @@ -36,7 +36,7 @@ trait AnnotationFilterExtractorTrait private function getFilterAnnotations(array $miscAnnotations): \Iterator { foreach ($miscAnnotations as $miscAnnotation) { - if (ApiFilter::class === get_class($miscAnnotation)) { + if (ApiFilter::class === \get_class($miscAnnotation)) { yield $miscAnnotation; } } @@ -51,7 +51,7 @@ private function getFilterProperties(ApiFilter $filterAnnotation, \ReflectionCla if ($filterAnnotation->properties) { foreach ($filterAnnotation->properties as $property => $strategy) { - if (is_int($property)) { + if (\is_int($property)) { $properties[$strategy] = null; } else { $properties[$property] = $strategy; diff --git a/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php b/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php index 846c5a6f934..93831b122f6 100644 --- a/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php +++ b/tests/Bridge/Doctrine/Orm/Extension/PaginationExtensionTest.php @@ -463,7 +463,7 @@ private function getPaginationExtensionResult(bool $partial = false, bool $legac $queryBuilderProphecy->getRootEntities()->willReturn([])->shouldBeCalled(); $queryBuilderProphecy->getQuery()->willReturn($query)->shouldBeCalled(); $queryBuilderProphecy->getDQLPart(Argument::that(function ($arg) { - return in_array($arg, ['having', 'orderBy', 'join'], true); + return \in_array($arg, ['having', 'orderBy', 'join'], true); }))->willReturn('')->shouldBeCalled(); $queryBuilderProphecy->getMaxResults()->willReturn(42)->shouldBeCalled(); diff --git a/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php b/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php index b571a61dc0f..eabda5f6dbe 100644 --- a/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php +++ b/tests/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtensionTest.php @@ -287,7 +287,7 @@ public function testAddResourceClassDirectories() return $arg; } - if (!in_array('foobar', $arg, true)) { + if (!\in_array('foobar', $arg, true)) { throw new \Exception('"foobar" should be in "resource_class_directories"'); } diff --git a/tests/DataProvider/ChainCollectionDataProviderTest.php b/tests/DataProvider/ChainCollectionDataProviderTest.php index 80409906a8f..73ad9354624 100644 --- a/tests/DataProvider/ChainCollectionDataProviderTest.php +++ b/tests/DataProvider/ChainCollectionDataProviderTest.php @@ -69,7 +69,7 @@ public function testGetCollectionNotSupported() $collection = (new ChainCollectionDataProvider([$firstDataProvider->reveal()]))->getCollection('notfound', 'op'); - $this->assertTrue(is_array($collection) || $collection instanceof \Traversable); + $this->assertTrue(\is_array($collection) || $collection instanceof \Traversable); $this->assertEmpty($collection); } diff --git a/tests/Fixtures/TestBundle/Serializer/Denormalizer/SerializableResourceDenormalizer.php b/tests/Fixtures/TestBundle/Serializer/Denormalizer/SerializableResourceDenormalizer.php index d5da541faf0..812bc27ce5f 100644 --- a/tests/Fixtures/TestBundle/Serializer/Denormalizer/SerializableResourceDenormalizer.php +++ b/tests/Fixtures/TestBundle/Serializer/Denormalizer/SerializableResourceDenormalizer.php @@ -39,6 +39,6 @@ public function denormalize($data, $class, $format = null, array $context = []) */ public function supportsDenormalization($data, $type, $format = null) { - return 'json' === $format && SerializableResource::class === $type && is_array($data); + return 'json' === $format && SerializableResource::class === $type && \is_array($data); } } diff --git a/tests/JsonApi/Serializer/ItemNormalizerTest.php b/tests/JsonApi/Serializer/ItemNormalizerTest.php index 21d8b0858f3..38a2b7cab48 100644 --- a/tests/JsonApi/Serializer/ItemNormalizerTest.php +++ b/tests/JsonApi/Serializer/ItemNormalizerTest.php @@ -260,7 +260,7 @@ public function testDenormalize() )->shouldBeCalled(); $getItemFromIriSecondArgCallback = function ($arg) { - return is_array($arg) && isset($arg['fetch_data']) && true === $arg['fetch_data']; + return \is_array($arg) && isset($arg['fetch_data']) && true === $arg['fetch_data']; }; $iriConverterProphecy = $this->prophesize(IriConverterInterface::class); diff --git a/tests/Metadata/Resource/ResourceMetadataTest.php b/tests/Metadata/Resource/ResourceMetadataTest.php index 63ea67fd051..d699bc1f35d 100644 --- a/tests/Metadata/Resource/ResourceMetadataTest.php +++ b/tests/Metadata/Resource/ResourceMetadataTest.php @@ -73,9 +73,9 @@ public function testValueObject() public function testWithMethods(string $name, $value) { $metadata = new ResourceMetadata(); - $newMetadata = call_user_func([$metadata, "with$name"], $value); + $newMetadata = \call_user_func([$metadata, "with$name"], $value); $this->assertNotSame($metadata, $newMetadata); - $this->assertSame($value, call_user_func([$newMetadata, "get$name"])); + $this->assertSame($value, \call_user_func([$newMetadata, "get$name"])); } public function testGetOperationAttributeFallback() From 5cb8cb3cedde4a89addf83adb62f245c5503ea2b Mon Sep 17 00:00:00 2001 From: abluchet Date: Wed, 6 Jun 2018 11:46:35 +0200 Subject: [PATCH 7/7] Fix lint for \get_class in RequestDataCollection --- .../Symfony/Bundle/DataCollector/RequestDataCollector.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bridge/Symfony/Bundle/DataCollector/RequestDataCollector.php b/src/Bridge/Symfony/Bundle/DataCollector/RequestDataCollector.php index 0cc0f012566..05826b7f17e 100644 --- a/src/Bridge/Symfony/Bundle/DataCollector/RequestDataCollector.php +++ b/src/Bridge/Symfony/Bundle/DataCollector/RequestDataCollector.php @@ -46,7 +46,7 @@ public function collect(Request $request, Response $response, \Exception $except $filters = []; foreach ($resourceMetadata ? $resourceMetadata->getAttribute('filters', []) : [] as $id) { if ($this->filterLocator->has($id)) { - $filters[$id] = get_class($this->filterLocator->get($id)); + $filters[$id] = \get_class($this->filterLocator->get($id)); continue; }