From cc2b1a14157f3903335035eb1b8dc5e1a5182325 Mon Sep 17 00:00:00 2001 From: Joel Wurtz Date: Tue, 28 Apr 2026 10:15:07 +0200 Subject: [PATCH] chore(lint): update to phpstan 2 / update some types --- castor.php | 22 +++--- phpstan.neon | 55 +++++++++++--- src/Attribute/MapFrom.php | 24 +++---- .../ReflectionReference.php | 3 + src/AutoMapper.php | 8 +-- src/EventListener/MapListener.php | 2 +- src/EventListener/MapperListener.php | 2 +- src/Extractor/AddRemoveWriteMutator.php | 2 +- src/Extractor/ArrayReadAccessor.php | 2 +- src/Extractor/FromSourceMappingExtractor.php | 2 +- src/Extractor/FromTargetMappingExtractor.php | 2 +- src/Extractor/MappingExtractor.php | 2 +- src/Extractor/MethodReadAccessor.php | 2 +- src/Extractor/PropertyReadAccessor.php | 2 +- src/GeneratedMapper.php | 8 +-- .../CreateTargetStatementsGenerator.php | 10 +-- src/Generator/IdentifierHashGenerator.php | 2 +- .../InjectMapperMethodStatementsGenerator.php | 2 +- .../MapMethodStatementsGenerator.php | 14 ++-- src/Generator/MapperConstructorGenerator.php | 2 +- src/Generator/MapperGenerator.php | 6 +- src/Generator/PropertyConditionsGenerator.php | 2 +- src/Generator/PropertyStatementsGenerator.php | 4 +- .../Shared/ClassDiscriminatorResolver.php | 2 +- .../DiscriminatorStatementsGenerator.php | 4 +- src/Lazy/LazyMap.php | 5 +- src/Loader/FileLoader.php | 8 +-- src/MapperContext.php | 3 +- src/Normalizer/AutoMapperNormalizer.php | 12 ++-- src/ObjectMapper/ObjectMapper.php | 7 +- src/Provider/ApiPlatform/IriProvider.php | 2 +- src/Provider/Doctrine/DoctrineProvider.php | 2 +- .../Bundle/Command/DebugMapperCommand.php | 10 +-- .../DataCollector/MetadataCollector.php | 6 +- .../AutoMapperExtension.php | 43 ++++++++--- .../DependencyInjection/Configuration.php | 8 +-- .../ReflectionClassRecursiveIterator.php | 2 + src/Symfony/ExpressionLanguageProvider.php | 2 +- src/Transformer/AbstractArrayTransformer.php | 2 +- .../ApiPlatform/JsonLdContextTransformer.php | 1 + .../JsonLdObjectToIdTransformer.php | 2 +- .../ArrayToDoctrineCollectionTransformer.php | 2 +- src/Transformer/ArrayTransformer.php | 2 +- src/Transformer/BuiltinTransformer.php | 51 +++++++------ src/Transformer/ChainTransformerFactory.php | 8 +-- .../DateTimeToStringTransformer.php | 2 +- .../DateTimeTransformerFactory.php | 6 +- src/Transformer/DictionaryTransformer.php | 2 +- .../DoctrineCollectionTransformerFactory.php | 2 +- src/Transformer/MultipleTransformer.php | 2 +- .../PropertyTransformerFactory.php | 8 +-- .../SymfonyUidTransformerFactory.php | 4 +- tests/AutoMapperMapToTest.php | 16 ++--- tests/AutoMapperTest.php | 6 +- tests/AutoMapperTest/ArrayAccess/map.php | 2 +- tests/AutoMapperTest/ArrayConsistency/map.php | 2 +- .../ArrayDefaultWithKey/map.php | 2 +- tests/AutoMapperTest/ArrayNested/map.php | 2 +- tests/AutoMapperTest/ArrayNotNested/map.php | 4 +- .../ArraySourceCastAlreadyCorrect/map.php | 2 +- .../ArraySourceCastDateTime/map.php | 2 +- .../ArraySourceCastDictionary/map.php | 2 +- .../ArraySourceCastInnerValues/map.php | 2 +- .../ArraySourceCastNested/map.php | 2 +- .../ArraySourceCastNullable/map.php | 2 +- .../ArraySourceCastObjects/map.php | 2 +- .../ArraySourceCastShape/map.php | 2 +- .../ArraySourceCastShapeComplex/map.php | 2 +- .../ArraySourceCastShapeNested/map.php | 2 +- .../ArraySourceCastShapeOptional/map.php | 2 +- .../ArraySourceCastShapeTypedSource/map.php | 2 +- .../ArraySourcePropertyType/map.php | 2 +- .../ConstructorWithRelation/map.php | 2 +- .../ConstructorWithSerializedName/map.php | 2 +- .../DeepPopulateMergeExisting/map.php | 2 +- .../DeepPopulateWithArrayCollection/map.php | 2 +- .../DiscriminatorAttributeArray/map.php | 2 +- .../DiscriminatorFromAndTo/map.php | 2 +- .../DiscriminatorMapAndInterface/map.php | 2 +- .../DoctrineCollections/map.php | 2 +- tests/AutoMapperTest/Ignore/map.php | 2 +- tests/AutoMapperTest/Nested/map.php | 2 +- .../ObjectWithPropertyAsUnknownArray/map.php | 2 +- tests/AutoMapperTest/Paramters/map.php | 2 +- .../PrivatePropertyInConstructors/map.php | 2 +- tests/AutoMapperTest/Provider/map.php | 2 +- .../StringUnionProperty/map.php | 2 +- tests/AutoMapperTest/SymfonyUId/map.php | 2 +- tests/AutoMapperTest/UnionProperty/map.php | 2 +- tests/Bundle/Resources/App/AppKernel.php | 4 ++ tests/Bundle/Resources/App/Entity/Pet.php | 6 +- tests/Bundle/Resources/App/Entity/UserDTO.php | 2 +- tests/Bundle/Resources/bin/console | 0 tests/Bundle/ServiceInstantiationTest.php | 2 +- tests/Doctrine/DoctrineTest.php | 2 +- tests/Fixtures/MapTo/Bar.php | 2 +- .../DeepObjectPopulateChildDummy.php | 4 +- .../DeepObjectPopulateParentDummy.php | 2 +- tests/Fixtures/Normalizer/GroupDummy.php | 8 +-- .../Fixtures/Normalizer/GroupDummyParent.php | 4 +- .../Normalizer/ToBeProxyfiedDummy.php | 2 +- .../ReflectionExtractorTestFixture.php | 6 +- .../FromSourceCustomModelTransformer.php | 2 +- .../FromTargetCustomModelTransformer.php | 2 +- .../SourceTargetCustomModelTransformer.php | 4 +- tests/Fixtures/UserDTO.php | 2 +- tests/MapperContextTest.php | 12 ++-- .../Features/AttributesTestTrait.php | 6 +- tests/Normalizer/Features/CallbacksObject.php | 4 +- .../Features/CallbacksTestTrait.php | 20 +++--- .../Features/CircularReferenceTestTrait.php | 4 +- .../ConstructorArgumentsTestTrait.php | 10 +-- .../Features/ContextMetadataTestTrait.php | 6 +- tests/Normalizer/Features/GroupsTestTrait.php | 6 +- .../Features/IgnoredAttributesTestTrait.php | 6 +- .../Normalizer/Features/MaxDepthTestTrait.php | 4 +- tests/Normalizer/Features/ObjectDummy.php | 12 ++-- tests/Normalizer/Features/ObjectOuter.php | 6 +- .../Features/ObjectToPopulateTestTrait.php | 8 +-- .../Features/SkipNullValuesTestTrait.php | 2 +- .../SkipUninitializedValuesTestTrait.php | 4 +- .../Features/TypeEnforcementNumberObject.php | 2 +- .../Features/TypeEnforcementTestTrait.php | 4 +- .../Fixtures/InitializedConstructor/B.php | 4 +- tests/ObjectMapper/ObjectMapperTest.php | 72 +++++++++---------- tests/Transformer/BuiltinTransformerTest.php | 4 +- 126 files changed, 404 insertions(+), 330 deletions(-) mode change 100644 => 100755 tests/Bundle/Resources/bin/console diff --git a/castor.php b/castor.php index c1a7e05c..57fbe14c 100644 --- a/castor.php +++ b/castor.php @@ -11,35 +11,37 @@ use function Castor\PHPQa\phpstan; use function Castor\run; +const PHP_CS_FIXER_VERSION = '3.95.1'; + #[AsTask('cs:check', namespace: 'qa', description: 'Check for coding standards without fixing them')] -function qa_cs_check() +function qa_cs_check(): void { - php_cs_fixer(['fix', '--config', __DIR__ . '/.php-cs-fixer.php', '--dry-run', '--diff'], '3.92.3', [ + php_cs_fixer(['fix', '--config', __DIR__ . '/.php-cs-fixer.php', '--dry-run', '--diff'], PHP_CS_FIXER_VERSION, [ 'kubawerlos/php-cs-fixer-custom-fixers' => '^3.21', ]); } #[AsTask('cs:fix', namespace: 'qa', description: 'Fix all coding standards', aliases: ['cs'])] -function qa_cs_fix() +function qa_cs_fix(): void { - php_cs_fixer(['fix', '--config', __DIR__ . '/.php-cs-fixer.php', '-v'], '3.92.3', [ + php_cs_fixer(['fix', '--config', __DIR__ . '/.php-cs-fixer.php', '-v'], PHP_CS_FIXER_VERSION, [ 'kubawerlos/php-cs-fixer-custom-fixers' => '^3.21', ]); } #[AsTask('phpstan', namespace: 'qa', description: 'Run PHPStan for static analysis', aliases: ['phpstan'])] -function qa_phpstan(bool $generateBaseline = false) +function qa_phpstan(bool $generateBaseline = false): void { $params = ['analyse', '--configuration', __DIR__ . '/phpstan.neon', '--memory-limit=-1', '-v']; if ($generateBaseline) { $params[] = '--generate-baseline'; } - phpstan($params, '1.12.23'); + phpstan($params, '2.1.51'); } #[AsTask('mapper', namespace: 'debug', description: 'Debug a mapper', aliases: ['debug'])] -function debug_mapper(string $source, string $target, string $load = '') +function debug_mapper(string $source, string $target, string $load = ''): void { require_once __DIR__ . '/vendor/autoload.php'; @@ -79,13 +81,13 @@ function debug_mapper(string $source, string $target, string $load = '') } #[AsTask('install', namespace: 'doc', description: 'Install tool for documentation (need poetry)')] -function doc_install() +function doc_install(): void { run('poetry install'); } #[AsTask('server', namespace: 'doc', description: 'Serve documentation')] -function doc_serve() +function doc_serve(): void { run('poetry run mkdocs serve -a localhost:8000'); } @@ -113,7 +115,7 @@ function build_assets(): void } #[AsTask('build-github-pages', namespace: 'doc', description: 'Serve documentation')] -function doc_build_github_pages() +function doc_build_github_pages(): void { // clean .build directory run('rm -rf ./.build', context: context()->withAllowFailure()); diff --git a/phpstan.neon b/phpstan.neon index 4c4a5cbd..1b7f6dde 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,12 +1,49 @@ parameters: - level: max - paths: - - src/ + level: max + paths: + - src/ - tmpDir: cache + tmpDir: cache + treatPhpDocTypesAsCertain: false - ignoreErrors: - - - message: "#^Method AutoMapper\\\\ObjectMapper\\\\ObjectMapper\\:\\:map\\(\\) should return T of object but returns object\\|null\\.$#" - count: 1 - path: src/ObjectMapper/ObjectMapper.php + ignoreErrors: + - + message: "#^Method AutoMapper\\\\ObjectMapper\\\\ObjectMapper\\:\\:map\\(\\) should return T of object but returns object\\|null\\.$#" + count: 1 + path: src/ObjectMapper/ObjectMapper.php + + - + message: '#^Parameter \#2 \$array of function implode expects array\, array given\.$#' + identifier: argument.type + count: 1 + path: src/EventListener/MapListener.php + + - + message: '#^Binary operation "\." between mixed and string results in an error\.$#' + identifier: binaryOp.invalid + count: 1 + path: src/EventListener/MapToContextListener.php + + - + message: '#^Parameter \$mapping of class AutoMapper\\Metadata\\Discriminator constructor expects array\, array given\.$#' + identifier: argument.type + count: 2 + path: src/EventListener/Symfony/ClassDiscriminatorListener.php + + - + message: '#^Call to function function_exists\(\) with callable\-string will always evaluate to true\.$#' + identifier: function.alreadyNarrowedType + count: 1 + path: src/Generator/PropertyConditionsGenerator.php + + - + message: '#^Method AutoMapper\\Loader\\FileLoader\:\:getRegistry\(\) should return array\ but returns array\.$#' + identifier: return.type + count: 1 + path: src/Loader/FileLoader.php + + - + message: '#^Property AutoMapper\\Loader\\FileLoader\:\:\$registry \(array\\) does not accept mixed\.$#' + identifier: assign.propertyType + count: 1 + path: src/Loader/FileLoader.php diff --git a/src/Attribute/MapFrom.php b/src/Attribute/MapFrom.php index 3e6205c0..a46fa1f3 100644 --- a/src/Attribute/MapFrom.php +++ b/src/Attribute/MapFrom.php @@ -13,18 +13,18 @@ final readonly class MapFrom { /** - * @param class-string|'array'|array|'array'>|null $source The specific source class name or array. If null this attribute will be used for all source classes. - * @param string|null $property The source property name. If null, the target property name will be used. - * @param int|null $maxDepth The maximum depth of the mapping. If null, the default max depth will be used. - * @param string|callable(mixed $value, object|array $source, array $context): mixed $transformer A transformer id or a callable that transform the value during mapping - * @param bool|null $ignore If true, the property will be ignored during mapping - * @param string|null $if The condition to map the property, using the expression language - * @param string[]|null $groups The groups to map the property - * @param string|null $dateTimeFormat The date-time format to use when transforming this property - * @param bool|null $extractTypesFromGetter If true, the types will be extracted from the getter method - * @param bool|null $identifier If true, the property will be used as an identifier - * @param Type|string|null $sourcePropertyType Override the source property type, where this property is mapped from - * @param Type|string|null $targetPropertyType Override the target property type, which in this case is the property type where the attribute is defined + * @param class-string|'array'|array|'array'>|null $source The specific source class name or array. If null this attribute will be used for all source classes. + * @param string|null $property The source property name. If null, the target property name will be used. + * @param int|null $maxDepth The maximum depth of the mapping. If null, the default max depth will be used. + * @param string|callable(mixed $value, object|array $source, array $context): mixed|null $transformer A transformer id or a callable that transform the value during mapping + * @param bool|null $ignore If true, the property will be ignored during mapping + * @param string|null $if The condition to map the property, using the expression language + * @param string[]|null $groups The groups to map the property + * @param string|null $dateTimeFormat The date-time format to use when transforming this property + * @param bool|null $extractTypesFromGetter If true, the types will be extracted from the getter method + * @param bool|null $identifier If true, the property will be used as an identifier + * @param Type|string|null $sourcePropertyType Override the source property type, where this property is mapped from + * @param Type|string|null $targetPropertyType Override the target property type, which in this case is the property type where the attribute is defined */ public function __construct( public string|array|null $source = null, diff --git a/src/AttributeReference/ReflectionReference.php b/src/AttributeReference/ReflectionReference.php index 4973d42e..6e29923c 100644 --- a/src/AttributeReference/ReflectionReference.php +++ b/src/AttributeReference/ReflectionReference.php @@ -46,6 +46,9 @@ public static function fromMethod(string $className, string $methodName): self return self::$method[$key]; } + /** + * @param class-string $className + */ public static function fromProperty(string $className, string $propertyName): self { $key = $className . '::$' . $propertyName; diff --git a/src/AutoMapper.php b/src/AutoMapper.php index fc5de16e..ade877b7 100644 --- a/src/AutoMapper.php +++ b/src/AutoMapper.php @@ -85,12 +85,9 @@ public function getMapper(string $source, string $target): MapperInterface public function map(array|object $source, string|array|object $target, array $context = []): array|object|null { - $sourceType = $targetType = null; - if (\is_object($source)) { - /** @var class-string $sourceType */ $sourceType = $source::class; - } elseif (\is_array($source)) { + } else { $sourceType = 'array'; } @@ -102,7 +99,7 @@ public function map(array|object $source, string|array|object $target, array $co $targetType = 'array'; $context[MapperContext::TARGET_TO_POPULATE] = $target; $context[MapperContext::DEEP_TARGET_TO_POPULATE] ??= true; - } elseif (\is_string($target)) { + } else { $targetType = $target; } @@ -116,6 +113,7 @@ public function map(array|object $source, string|array|object $target, array $co public function mapCollection(iterable $collection, string $target, array $context = []): array { $output = []; + /** @var string|int $k */ foreach ($collection as $k => $item) { if (\is_array($item) && 'array' === $target) { throw new InvalidMappingException('Cannot map this value, both source and target are array.'); diff --git a/src/EventListener/MapListener.php b/src/EventListener/MapListener.php index f115a776..2ba2e1a8 100644 --- a/src/EventListener/MapListener.php +++ b/src/EventListener/MapListener.php @@ -49,7 +49,7 @@ protected function getTransformerFromMapAttribute(string $class, MapTo|MapFrom $ $transformer = new PropertyTransformer($transformerCallable); } elseif (!\is_object($transformerCallable) && \is_callable($transformerCallable, false, $callableName)) { $transformer = new CallableTransformer($callableName); - } elseif (\is_object($transformerCallable) && \is_callable($transformerCallable)) { + } elseif (\is_callable($transformerCallable)) { $transformer = new ReferenceTransformer($reference); } elseif (\is_string($transformerCallable) && method_exists($class, $transformerCallable)) { $reflMethod = new \ReflectionMethod($class, $transformerCallable); diff --git a/src/EventListener/MapperListener.php b/src/EventListener/MapperListener.php index d21893ef..bcd6081f 100644 --- a/src/EventListener/MapperListener.php +++ b/src/EventListener/MapperListener.php @@ -105,7 +105,7 @@ private function getMapperAttribute(GenerateMapperEvent $event, bool $allowParen } // sort by priority - usort($mappers, fn (array $a, array $b) => $a[0]->priority <=> $b[0]->priority); + usort($mappers, static fn (array $a, array $b) => $a[0]->priority <=> $b[0]->priority); return $mappers[0]; } diff --git a/src/Extractor/AddRemoveWriteMutator.php b/src/Extractor/AddRemoveWriteMutator.php index 25b9f20e..c30c281c 100644 --- a/src/Extractor/AddRemoveWriteMutator.php +++ b/src/Extractor/AddRemoveWriteMutator.php @@ -22,7 +22,7 @@ public function getExpression(Expr $output, Expr $value, bool $byRef = false): E ]); } - public function getRemoveExpression(Expr $object, Expr $value): ?Expr + public function getRemoveExpression(Expr $object, Expr $value): Expr { return new Expr\MethodCall($object, $this->removeMethodName, [ new Arg($value), diff --git a/src/Extractor/ArrayReadAccessor.php b/src/Extractor/ArrayReadAccessor.php index ed699737..49d9b50c 100644 --- a/src/Extractor/ArrayReadAccessor.php +++ b/src/Extractor/ArrayReadAccessor.php @@ -22,7 +22,7 @@ public function getExpression(Expr $input, bool $target = false): Expr return new Expr\ArrayDimFetch($input, new Scalar\String_($this->property)); } - public function getIsDefinedExpression(Expr\Variable $input, bool $nullable = false, bool $target = false): ?Expr + public function getIsDefinedExpression(Expr\Variable $input, bool $nullable = false, bool $target = false): Expr { if ($this->isArrayAccess) { return new Expr\MethodCall($input, 'offsetExists', [new Arg(new Scalar\String_($this->property))]); diff --git a/src/Extractor/FromSourceMappingExtractor.php b/src/Extractor/FromSourceMappingExtractor.php index 1839ccef..9f35efea 100644 --- a/src/Extractor/FromSourceMappingExtractor.php +++ b/src/Extractor/FromSourceMappingExtractor.php @@ -104,7 +104,7 @@ private function transformSourceType(string $target, ?Type $type = null): ?Type } // Transform datetime to string - if ($type instanceof Type\ObjectType && $type->getClassName() !== null && (\DateTimeInterface::class === $type->getClassName() || is_subclass_of($type->getClassName(), \DateTimeInterface::class))) { + if ($type instanceof Type\ObjectType && (\DateTimeInterface::class === $type->getClassName() || is_subclass_of($type->getClassName(), \DateTimeInterface::class))) { return Type::string(); } diff --git a/src/Extractor/FromTargetMappingExtractor.php b/src/Extractor/FromTargetMappingExtractor.php index 8682dd4c..91682647 100644 --- a/src/Extractor/FromTargetMappingExtractor.php +++ b/src/Extractor/FromTargetMappingExtractor.php @@ -117,7 +117,7 @@ private function transformTargetType(string $source, ?Type $type = null): ?Type } // Transform datetime to string - if ($type instanceof Type\ObjectType && $type->getClassName() !== null && (\DateTimeInterface::class === $type->getClassName() || is_subclass_of($type->getClassName(), \DateTimeInterface::class))) { + if ($type instanceof Type\ObjectType && (\DateTimeInterface::class === $type->getClassName() || is_subclass_of($type->getClassName(), \DateTimeInterface::class))) { return Type::string(); } diff --git a/src/Extractor/MappingExtractor.php b/src/Extractor/MappingExtractor.php index b8e20c76..4eea5248 100644 --- a/src/Extractor/MappingExtractor.php +++ b/src/Extractor/MappingExtractor.php @@ -34,7 +34,7 @@ public function __construct( } /** - * @return list + * @return array */ public function getProperties(string $class, bool $withConstructorParameters = false): iterable { diff --git a/src/Extractor/MethodReadAccessor.php b/src/Extractor/MethodReadAccessor.php index 277a7d31..e97b4ffc 100644 --- a/src/Extractor/MethodReadAccessor.php +++ b/src/Extractor/MethodReadAccessor.php @@ -22,7 +22,7 @@ * @param array $context */ public function __construct( - public string $property, + public ?string $property, public string $method, public string $sourceClass, public bool $private = false, diff --git a/src/Extractor/PropertyReadAccessor.php b/src/Extractor/PropertyReadAccessor.php index e739dc01..4da3b094 100644 --- a/src/Extractor/PropertyReadAccessor.php +++ b/src/Extractor/PropertyReadAccessor.php @@ -53,7 +53,7 @@ public function getExpression(Expr $input, bool $target = false): Expr return new Expr\PropertyFetch($input, $this->property); } - public function getIsDefinedExpression(Expr\Variable $input, bool $nullable = false, bool $target = false): ?Expr + public function getIsDefinedExpression(Expr\Variable $input, bool $nullable = false, bool $target = false): Expr { if ($this->private) { /* diff --git a/src/GeneratedMapper.php b/src/GeneratedMapper.php index 1ed29c62..8d61188c 100644 --- a/src/GeneratedMapper.php +++ b/src/GeneratedMapper.php @@ -58,19 +58,19 @@ public function getTargetHash(mixed $value): string /** @var array */ protected array $extractCallbacks = []; - /** @var array) */ + /** @var array */ protected array $extractIsNullCallbacks = []; - /** @var array) */ + /** @var array */ protected array $extractIsUndefinedCallbacks = []; /** @var array */ protected array $extractTargetCallbacks = []; - /** @var array) */ + /** @var array */ protected array $extractTargetIsNullCallbacks = []; - /** @var array) */ + /** @var array */ protected array $extractTargetIsUndefinedCallbacks = []; /** @var Target|\ReflectionClass */ diff --git a/src/Generator/CreateTargetStatementsGenerator.php b/src/Generator/CreateTargetStatementsGenerator.php index 309f30cc..d34a44d7 100644 --- a/src/Generator/CreateTargetStatementsGenerator.php +++ b/src/Generator/CreateTargetStatementsGenerator.php @@ -45,7 +45,7 @@ public function __construct( * } * ``` * - * @return list + * @return Stmt[] */ public function generate(GeneratorMetadata $metadata, VariableRegistry $variableRegistry, bool $callDoConstruct): array { @@ -218,7 +218,7 @@ private function targetAsStdClass(GeneratorMetadata $metadata): ?Stmt } /** - * @return list + * @return Stmt[] */ public function getConstructStatements(GeneratorMetadata $metadata): array { @@ -290,7 +290,7 @@ public function getConstructStatements(GeneratorMetadata $metadata): array * } * ``` * - * @return list|null + * @return Stmt[]|null */ private function constructorArgument(Expr\ArrayDimFetch $assignVar, GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata, \ReflectionParameter $parameter): ?array { @@ -299,7 +299,7 @@ private function constructorArgument(Expr\ArrayDimFetch $assignVar, GeneratorMet $conditionDefined = $propertyMetadata->source->accessor?->getIsDefinedExpression($variableRegistry->getSourceInput(), $parameter->allowsNull()); if (null === $fieldValueExpr) { - if (!($propertyMetadata->transformer instanceof AllowNullValueTransformerInterface)) { + if (!$propertyMetadata->transformer instanceof AllowNullValueTransformerInterface) { return null; } @@ -393,7 +393,7 @@ private function constructorArgument(Expr\ArrayDimFetch $assignVar, GeneratorMet * } * ``` * - * @return list + * @return Stmt[] */ private function constructorArgumentWithoutSource(Expr\ArrayDimFetch $assignVar, GeneratorMetadata $metadata, \ReflectionParameter $constructorParameter): array { diff --git a/src/Generator/IdentifierHashGenerator.php b/src/Generator/IdentifierHashGenerator.php index 8c1dc003..72492956 100644 --- a/src/Generator/IdentifierHashGenerator.php +++ b/src/Generator/IdentifierHashGenerator.php @@ -18,7 +18,7 @@ final readonly class IdentifierHashGenerator { /** - * @return list + * @return Stmt[] */ private function getStatements(GeneratorMetadata $metadata, bool $fromSource): array { diff --git a/src/Generator/InjectMapperMethodStatementsGenerator.php b/src/Generator/InjectMapperMethodStatementsGenerator.php index 2b4cd3fe..b4013b36 100644 --- a/src/Generator/InjectMapperMethodStatementsGenerator.php +++ b/src/Generator/InjectMapperMethodStatementsGenerator.php @@ -35,7 +35,7 @@ public function __construct() } /** - * @return list + * @return Stmt[] */ public function getStatements(Expr\Variable $automapperRegistryVariable, GeneratorMetadata $metadata): array { diff --git a/src/Generator/MapMethodStatementsGenerator.php b/src/Generator/MapMethodStatementsGenerator.php index 97fb1b36..d669d64a 100644 --- a/src/Generator/MapMethodStatementsGenerator.php +++ b/src/Generator/MapMethodStatementsGenerator.php @@ -47,7 +47,7 @@ public function __construct( } /** - * @return array{0: list, 1: list, 2: list} + * @return array{0: Stmt[], 1: Stmt[], 2: Stmt[]} */ public function getMappingStatements(GeneratorMetadata $metadata): array { @@ -96,9 +96,9 @@ public function getMappingStatements(GeneratorMetadata $metadata): array } /** - * @param list $duplicatedStatements + * @param Stmt[] $duplicatedStatements * - * @return list + * @return Stmt[] */ public function getStatements(GeneratorMetadata $metadata, array $duplicatedStatements, bool $callDoConstruct): array { @@ -305,7 +305,7 @@ private function isSourceIsLazyProxy(GeneratorMetadata $metadata): array * } * ``` * - * @return list + * @return Stmt[] */ private function handleCircularReference(GeneratorMetadata $metadata): array { @@ -350,7 +350,7 @@ private function handleCircularReference(GeneratorMetadata $metadata): array } /** - * @return list + * @return Stmt[] */ private function initializeTargetToPopulate(GeneratorMetadata $metadata): array { @@ -412,7 +412,7 @@ private function initializeTargetToPopulate(GeneratorMetadata $metadata): array } /** - * @return list + * @return Stmt[] */ private function initializeTargetFromProvider(GeneratorMetadata $metadata): array { @@ -510,7 +510,7 @@ private function initializeTargetFromProvider(GeneratorMetadata $metadata): arra } /** - * @return list + * @return Stmt[] */ private function handleDependencies(GeneratorMetadata $metadata): array { diff --git a/src/Generator/MapperConstructorGenerator.php b/src/Generator/MapperConstructorGenerator.php index c7a69ffc..ee5d7f1f 100644 --- a/src/Generator/MapperConstructorGenerator.php +++ b/src/Generator/MapperConstructorGenerator.php @@ -23,7 +23,7 @@ public function __construct( } /** - * @return list + * @return Stmt[] */ public function getStatements(GeneratorMetadata $metadata): array { diff --git a/src/Generator/MapperGenerator.php b/src/Generator/MapperGenerator.php index 6644e971..c8a63d7b 100644 --- a/src/Generator/MapperGenerator.php +++ b/src/Generator/MapperGenerator.php @@ -144,7 +144,7 @@ private function constructorMethod(GeneratorMetadata $metadata): Stmt\ClassMetho * } * ``` * - * @param list $duplicatedStatements + * @param Stmt[] $duplicatedStatements */ private function mapMethod(GeneratorMetadata $metadata, array $duplicatedStatements, bool $callDoConstruct): Stmt\ClassMethod { @@ -174,7 +174,7 @@ private function mapMethod(GeneratorMetadata $metadata, array $duplicatedStateme * } * ``` * - * @param list $constructorStatements + * @param Stmt[] $constructorStatements */ private function doConstructMethod(GeneratorMetadata $metadata, array $constructorStatements): Stmt\ClassMethod { @@ -197,7 +197,7 @@ private function doConstructMethod(GeneratorMetadata $metadata, array $construct * } * ``` * - * @param list $setterStatements + * @param Stmt[] $setterStatements */ private function doMapMethod(GeneratorMetadata $metadata, array $setterStatements): Stmt\ClassMethod { diff --git a/src/Generator/PropertyConditionsGenerator.php b/src/Generator/PropertyConditionsGenerator.php index d512a69d..8ad73a9c 100644 --- a/src/Generator/PropertyConditionsGenerator.php +++ b/src/Generator/PropertyConditionsGenerator.php @@ -182,7 +182,7 @@ private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups new Expr\Array_() ) ), - new Arg(new Expr\Array_(array_map(function (string $group) { + new Arg(new Expr\Array_(array_map(static function (string $group) { return create_expr_array_item(new Scalar\String_($group)); }, $groups))), ]) diff --git a/src/Generator/PropertyStatementsGenerator.php b/src/Generator/PropertyStatementsGenerator.php index c71ea732..24dce11d 100644 --- a/src/Generator/PropertyStatementsGenerator.php +++ b/src/Generator/PropertyStatementsGenerator.php @@ -23,7 +23,7 @@ public function __construct( } /** - * @return list + * @return Stmt[] */ public function generate(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): array { @@ -35,7 +35,7 @@ public function generate(GeneratorMetadata $metadata, PropertyMetadata $property $fieldValueExpr = $propertyMetadata->source->accessor?->getExpression($variableRegistry->getSourceInput()); if (null === $fieldValueExpr) { - if (!($propertyMetadata->transformer instanceof AllowNullValueTransformerInterface)) { + if (!$propertyMetadata->transformer instanceof AllowNullValueTransformerInterface) { return []; } diff --git a/src/Generator/Shared/ClassDiscriminatorResolver.php b/src/Generator/Shared/ClassDiscriminatorResolver.php index ca25fa4a..b7170183 100644 --- a/src/Generator/Shared/ClassDiscriminatorResolver.php +++ b/src/Generator/Shared/ClassDiscriminatorResolver.php @@ -35,7 +35,7 @@ public function getDiscriminatorPropertyMetadata(GeneratorMetadata $metadata, bo } return array_find($metadata->propertiesMetadata, - fn ($propertyMetadata, + static fn ($propertyMetadata, ) => ($fromSource ? $propertyMetadata->source->property : $propertyMetadata->target->property) === $discriminator->propertyName ); } diff --git a/src/Generator/Shared/DiscriminatorStatementsGenerator.php b/src/Generator/Shared/DiscriminatorStatementsGenerator.php index 8b8643ba..760aca5d 100644 --- a/src/Generator/Shared/DiscriminatorStatementsGenerator.php +++ b/src/Generator/Shared/DiscriminatorStatementsGenerator.php @@ -27,7 +27,7 @@ public function __construct( } /** - * @return list + * @return Stmt[] * * We return the object created with the correct mapper depending on the variant, this will skip the next mapping phase in this situation * @@ -111,7 +111,7 @@ public function createTargetStatements(GeneratorMetadata $metadata): array ); } - $isDefinedExpression = $propertyMetadata->source->accessor?->getIsDefinedExpression($variableRegistry->getSourceInput()); + $isDefinedExpression = $propertyMetadata->source->accessor->getIsDefinedExpression($variableRegistry->getSourceInput()); if (!$isDefinedExpression) { return $discriminateStatements; diff --git a/src/Lazy/LazyMap.php b/src/Lazy/LazyMap.php index 11c59ddf..0f5070c2 100644 --- a/src/Lazy/LazyMap.php +++ b/src/Lazy/LazyMap.php @@ -10,7 +10,7 @@ */ final class LazyMap implements \ArrayAccess, \JsonSerializable, \IteratorAggregate { - /** @var array */ + /** @var array */ private mixed $mappedValue = []; private bool $initialized = false; @@ -41,6 +41,9 @@ public function offsetGet(mixed $offset): mixed return $this->mappedValue[$offset]; } + /** + * @param string $offset + */ public function offsetSet(mixed $offset, mixed $value): void { $this->initialize(); diff --git a/src/Loader/FileLoader.php b/src/Loader/FileLoader.php index d3bc1625..82e22bad 100644 --- a/src/Loader/FileLoader.php +++ b/src/Loader/FileLoader.php @@ -24,8 +24,8 @@ final class FileLoader implements ClassLoaderInterface { private readonly PrettyPrinterAbstract $printer; - /** @var array|null */ - private ?array $registry = null; + /** @var array */ + private array $registry; public function __construct( private readonly MapperGenerator $generator, @@ -107,7 +107,7 @@ public function createGeneratedMapper(MapperMetadata $mapperMetadata): string */ private function addHashToRegistry(string $className, string $hash): void { - if (null === $this->registry) { + if (!isset($this->registry)) { $this->registry = []; } @@ -119,7 +119,7 @@ private function addHashToRegistry(string $className, string $hash): void /** @return array */ private function getRegistry(): array { - if (null === $this->registry) { + if (!isset($this->registry)) { $registryPath = $this->directory . \DIRECTORY_SEPARATOR . 'registry.php'; if (!file_exists($registryPath)) { diff --git a/src/MapperContext.php b/src/MapperContext.php index 330f6727..d0a98b1a 100644 --- a/src/MapperContext.php +++ b/src/MapperContext.php @@ -14,13 +14,12 @@ * * @author Joel Wurtz * - * @phpstan-type CircularReferenceHandler (callable(mixed, array): mixed) * @phpstan-type MapperContextArray array{ * "groups"?: string[]|null, * "allowed_attributes"?: string[]|array|null, * "ignored_attributes"?: string[]|array|null, * "circular_reference_limit"?: int|null, - * "circular_reference_handler"?: callable|null, + * "circular_reference_handler"?: (callable(mixed, array $context): mixed)|null, * "circular_reference_registry"?: array, * "circular_count_reference_registry"?: array, * "depth"?: int, diff --git a/src/Normalizer/AutoMapperNormalizer.php b/src/Normalizer/AutoMapperNormalizer.php index 23dadf71..6856b2eb 100644 --- a/src/Normalizer/AutoMapperNormalizer.php +++ b/src/Normalizer/AutoMapperNormalizer.php @@ -26,7 +26,7 @@ */ readonly class AutoMapperNormalizer implements NormalizerInterface, DenormalizerInterface { - private const SERIALIZER_CONTEXT_MAPPING = [ + private const array SERIALIZER_CONTEXT_MAPPING = [ AbstractNormalizer::GROUPS => MapperContext::GROUPS, AbstractNormalizer::ATTRIBUTES => MapperContext::ALLOWED_ATTRIBUTES, AbstractNormalizer::IGNORED_ATTRIBUTES => MapperContext::IGNORED_ATTRIBUTES, @@ -46,7 +46,7 @@ public function __construct( * @param object $object * @param array $context * - * @return array + * @return array|null */ public function normalize(mixed $object, ?string $format = null, array $context = []): ?array { @@ -160,6 +160,10 @@ private function createAutoMapperContext(?string $format = null, array $serializ } if (\array_key_exists(AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS, $serializerContext) && is_iterable($serializerContext[AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS])) { + /** + * @var string $class + * @var array $keyArgs + */ foreach ($serializerContext[AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS] as $class => $keyArgs) { foreach ($keyArgs as $key => $value) { $context[MapperContext::CONSTRUCTOR_ARGUMENTS][$class][$key] = $value; @@ -180,9 +184,9 @@ private function createAutoMapperContext(?string $format = null, array $serializ } if (\array_key_exists(AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER, $serializerContext)) { - /** @var callable(object, string, array) $callback */ + /** @var (callable(mixed, string|null, array): mixed) $callback */ $callback = $serializerContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER]; - $context[MapperContext::CIRCULAR_REFERENCE_HANDLER] = function ($object, array $context) use ($format, $callback) { + $context[MapperContext::CIRCULAR_REFERENCE_HANDLER] = static function ($object, array $context) use ($format, $callback) { return $callback($object, $format, $context); }; diff --git a/src/ObjectMapper/ObjectMapper.php b/src/ObjectMapper/ObjectMapper.php index 0f5595f9..e8732708 100644 --- a/src/ObjectMapper/ObjectMapper.php +++ b/src/ObjectMapper/ObjectMapper.php @@ -33,12 +33,13 @@ public function map(object $source, object|string|null $target = null): object $map = $this->getMapTarget($metadata, null, $source, null); if (null === $target) { - /** @var class-string|object $target */ + /** @var class-string $target */ $target = $map?->target; } if ($target && $map && $map->transform) { // Support only one transform for object mapper at the moment + /** @var (string|callable(mixed $value, object $source, ?object $target): mixed) $transform */ $transform = \is_array($map->transform) ? $map->transform[0] : $map->transform; if ($fn = $this->getCallable($transform)) { @@ -73,7 +74,7 @@ public function map(object $source, object|string|null $target = null): object } /** - * @param callable(mixed $value, object $source, ?object $target): mixed $fn + * @param (callable(mixed $value, object $source, ?object $target): mixed)|callable-string $fn */ private function call(callable $fn, mixed $value, object $source, ?object $target = null): mixed { @@ -114,7 +115,7 @@ private function getCallable(string|callable $fn): ?callable } if ($this->serviceLocator?->has($fn)) { - /** @var callable(mixed $value, object $source, ?object $target): mixed) */ + /** @var callable(mixed $value, object $source, ?object $target): mixed */ return $this->serviceLocator->get($fn); } diff --git a/src/Provider/ApiPlatform/IriProvider.php b/src/Provider/ApiPlatform/IriProvider.php index 9da520fe..a2b82baa 100644 --- a/src/Provider/ApiPlatform/IriProvider.php +++ b/src/Provider/ApiPlatform/IriProvider.php @@ -18,7 +18,7 @@ public function __construct( ) { } - public function provide(string $targetType, mixed $source, array $context, mixed $id): object|array|null + public function provide(string $targetType, mixed $source, array $context, mixed $id): ?object { if (($context[MapperContext::NORMALIZER_FORMAT] ?? false) !== 'jsonld') { return null; diff --git a/src/Provider/Doctrine/DoctrineProvider.php b/src/Provider/Doctrine/DoctrineProvider.php index d93d97d5..6bd5e840 100644 --- a/src/Provider/Doctrine/DoctrineProvider.php +++ b/src/Provider/Doctrine/DoctrineProvider.php @@ -17,7 +17,7 @@ public function __construct( /** * @param class-string $targetType The class name of the */ - public function provide(string $targetType, mixed $source, array $context, mixed $id): object|array|null + public function provide(string $targetType, mixed $source, array $context, mixed $id): ?object { if ($id !== null) { return $this->objectManager->find($targetType, $id); diff --git a/src/Symfony/Bundle/Command/DebugMapperCommand.php b/src/Symfony/Bundle/Command/DebugMapperCommand.php index 48872744..f0e3a466 100644 --- a/src/Symfony/Bundle/Command/DebugMapperCommand.php +++ b/src/Symfony/Bundle/Command/DebugMapperCommand.php @@ -60,7 +60,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $style->table( ['Mapper', 'Source', 'Target'], array_map( - fn (Dependency $dependency) => [ + static fn (Dependency $dependency) => [ $dependency->mapperDependency->name, $dependency->mapperDependency->source, $dependency->mapperDependency->target, @@ -74,14 +74,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int $style->table( [\sprintf('%s -> %s', $source, $target), 'If', 'Transformer', 'Groups', 'MaxDepth'], array_map( - fn (PropertyMetadata $property) => [ + static fn (PropertyMetadata $property) => [ $property->source->property . ' (' . $property->source->type . ') -> ' . $property->target->property . ' (' . $property->target->type . ') ', $property->if, $property->transformer instanceof \Stringable ? (string) $property->transformer : \get_class($property->transformer), $property->disableGroupsCheck ? 'Disabled' : implode(', ', $property->groups ?? []), $property->maxDepth, ], - array_filter($metadata->propertiesMetadata, fn (PropertyMetadata $property) => !$property->ignored) + array_filter($metadata->propertiesMetadata, static fn (PropertyMetadata $property) => !$property->ignored) ) ); @@ -90,11 +90,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int $style->table( [\sprintf('%s -> %s', $source, $target), 'Not used reason'], array_map( - fn (PropertyMetadata $property) => [ + static fn (PropertyMetadata $property) => [ $property->source->property . ' (' . $property->source->type . ') -> ' . $property->target->property . ' (' . $property->target->type . ') ', $property->ignoreReason, ], - array_filter($metadata->propertiesMetadata, fn (PropertyMetadata $property) => $property->ignored) + array_filter($metadata->propertiesMetadata, static fn (PropertyMetadata $property) => $property->ignored) ) ); diff --git a/src/Symfony/Bundle/DataCollector/MetadataCollector.php b/src/Symfony/Bundle/DataCollector/MetadataCollector.php index 8c226b6e..b53c6401 100644 --- a/src/Symfony/Bundle/DataCollector/MetadataCollector.php +++ b/src/Symfony/Bundle/DataCollector/MetadataCollector.php @@ -91,15 +91,15 @@ function (PropertyMetadata $property) { 'code' => $this->highlightStatements($propStatements), ]; }, - array_filter($metadata->propertiesMetadata, fn (PropertyMetadata $property) => !$property->ignored) + array_filter($metadata->propertiesMetadata, static fn (PropertyMetadata $property) => !$property->ignored) ), 'notUsedProperties' => array_map( - fn (PropertyMetadata $property) => [ + static fn (PropertyMetadata $property) => [ 'source' => $property->source, 'target' => $property->target, 'reason' => $property->ignoreReason, ], - array_filter($metadata->propertiesMetadata, fn (PropertyMetadata $property) => $property->ignored) + array_filter($metadata->propertiesMetadata, static fn (PropertyMetadata $property) => $property->ignored) ), 'fileCode' => $fileCode, ]; diff --git a/src/Symfony/Bundle/DependencyInjection/AutoMapperExtension.php b/src/Symfony/Bundle/DependencyInjection/AutoMapperExtension.php index 626366b4..da1cea09 100644 --- a/src/Symfony/Bundle/DependencyInjection/AutoMapperExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/AutoMapperExtension.php @@ -21,7 +21,6 @@ use AutoMapper\Transformer\PropertyTransformer\PropertyTransformerInterface; use AutoMapper\Transformer\PropertyTransformer\PropertyTransformerSupportInterface; use AutoMapper\Transformer\SymfonyUidTransformerFactory; -use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; @@ -32,20 +31,42 @@ use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Uid\AbstractUid; +/** + * @phpstan-type AutoMapperConfig array{ + * class_prefix: string, + * constructor_strategy: string, + * date_time_format: string, + * check_attributes: bool, + * auto_register: bool, + * map_private_properties: bool, + * allow_readonly_target_to_populate: bool, + * normalizer: array{ + * enabled: bool, + * only_registered_mapping: bool, + * priority: int, + * }, + * serializer_attributes: bool, + * api_platform: bool, + * object_mapper: bool, + * doctrine: bool, + * name_converter: string|null, + * loader: array{ + * eval: bool, + * cache_dir: string, + * reload_strategy: string, + * }, + * mapping: array{ + * paths: string[], + * mappers: array, + * } + * } + */ class AutoMapperExtension extends Extension { - /** - * @param array $config - */ - public function getConfiguration(array $config, ContainerBuilder $container): ?ConfigurationInterface - { - return new Configuration(); - } - public function load(array $configs, ContainerBuilder $container): void { - /** @var Configuration $configuration */ - $configuration = $this->getConfiguration($configs, $container); + $configuration = new Configuration(); + /** @var AutoMapperConfig $config */ $config = $this->processConfiguration($configuration, $configs); $loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); diff --git a/src/Symfony/Bundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DependencyInjection/Configuration.php index 7020bb7e..601d0af1 100644 --- a/src/Symfony/Bundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/DependencyInjection/Configuration.php @@ -24,13 +24,13 @@ public function getConfigTreeBuilder(): TreeBuilder ->children() ->scalarNode('class_prefix')->defaultValue('Symfony_Mapper_')->end() ->enumNode('constructor_strategy') - ->values(array_map(fn (ConstructorStrategy $strategy) => $strategy->value, ConstructorStrategy::cases())) + ->values(array_map(static fn (ConstructorStrategy $strategy) => $strategy->value, ConstructorStrategy::cases())) ->defaultValue(ConstructorStrategy::AUTO->value) ->end() ->scalarNode('date_time_format')->defaultValue(\DateTimeInterface::RFC3339)->end() ->booleanNode('check_attributes')->defaultTrue()->end() ->booleanNode('auto_register')->defaultTrue()->end() - ->booleanNode('map_private_properties')->defaultTrue()->end() + ->booleanNode('map_private_properties')->defaultFalse()->end() ->booleanNode('allow_readonly_target_to_populate')->defaultFalse()->end() ->arrayNode('normalizer') ->children() @@ -49,12 +49,10 @@ public function getConfigTreeBuilder(): TreeBuilder ->children() ->booleanNode('eval')->defaultFalse()->end() ->scalarNode('cache_dir')->defaultValue('%kernel.cache_dir%/automapper')->end() - ->enumNode('reload_strategy')->values(array_map(fn (FileReloadStrategy $value) => $value->value, FileReloadStrategy::cases()))->defaultNull()->end() + ->enumNode('reload_strategy')->values(array_map(static fn (FileReloadStrategy $value) => $value->value, FileReloadStrategy::cases()))->defaultNull()->end() ->end() ->addDefaultsIfNotSet() ->end() - ->scalarNode('date_time_format')->defaultValue(\DateTimeInterface::RFC3339)->end() - ->booleanNode('map_private_properties')->defaultFalse()->end() ->arrayNode('mapping') ->children() ->arrayNode('paths') diff --git a/src/Symfony/Bundle/ReflectionClassRecursiveIterator.php b/src/Symfony/Bundle/ReflectionClassRecursiveIterator.php index 1cddae08..9b043ba1 100644 --- a/src/Symfony/Bundle/ReflectionClassRecursiveIterator.php +++ b/src/Symfony/Bundle/ReflectionClassRecursiveIterator.php @@ -20,6 +20,8 @@ private function __construct() */ public static function getReflectionClassesFromDirectories(array $directories): iterable { + $includedFiles = []; + foreach ($directories as $path) { $iterator = new \RegexIterator( new \RecursiveIteratorIterator( diff --git a/src/Symfony/ExpressionLanguageProvider.php b/src/Symfony/ExpressionLanguageProvider.php index bbce7a2e..b6911ab1 100644 --- a/src/Symfony/ExpressionLanguageProvider.php +++ b/src/Symfony/ExpressionLanguageProvider.php @@ -28,7 +28,7 @@ public function getFunctions(): array foreach ($this->functions->getProvidedServices() as $function => $type) { $functions[] = new ExpressionFunction( $function, - static fn (...$args) => \sprintf('($this->expressionLanguageProvider->get(%s)(%s))', var_export($function, true), implode(', ', $args)), + static fn (string ...$args) => \sprintf('($this->expressionLanguageProvider->get(%s)(%s))', var_export($function, true), implode(', ', $args)), fn ($values, ...$args) => $this->get($function)(...$args) ); } diff --git a/src/Transformer/AbstractArrayTransformer.php b/src/Transformer/AbstractArrayTransformer.php index 89c42d59..4e2f69ca 100644 --- a/src/Transformer/AbstractArrayTransformer.php +++ b/src/Transformer/AbstractArrayTransformer.php @@ -68,7 +68,7 @@ public function transform(Expr $input, Expr $target, PropertyMetadata $propertyM new Expr\ConstFetch(new Name('false')) ); - if ($propertyMapping->target->readAccessor !== null && $this->itemTransformer instanceof IdentifierHashInterface) { + if ($this->itemTransformer instanceof IdentifierHashInterface) { $targetHashVar = new Expr\Variable($uniqueVariableScope->getUniqueName('targetHash')); $loopExistingStatements[] = new Stmt\If_($isDeepPopulateExpr, [ diff --git a/src/Transformer/ApiPlatform/JsonLdContextTransformer.php b/src/Transformer/ApiPlatform/JsonLdContextTransformer.php index 5e841074..b099c7dc 100644 --- a/src/Transformer/ApiPlatform/JsonLdContextTransformer.php +++ b/src/Transformer/ApiPlatform/JsonLdContextTransformer.php @@ -31,6 +31,7 @@ public function transform(mixed $value, object|array $source, array $context, mi if ($this->contextBuilder instanceof AnonymousContextBuilderInterface) { return $this->contextBuilder->getAnonymousResourceContext( $source, + /* @phpstan-ignore-next-line */ ($context['output'] ?? []) + ['api_resource' => $context['api_resource'] ?? null] ); } diff --git a/src/Transformer/ApiPlatform/JsonLdObjectToIdTransformer.php b/src/Transformer/ApiPlatform/JsonLdObjectToIdTransformer.php index 9be8b3d6..6cf96c46 100644 --- a/src/Transformer/ApiPlatform/JsonLdObjectToIdTransformer.php +++ b/src/Transformer/ApiPlatform/JsonLdObjectToIdTransformer.php @@ -105,7 +105,7 @@ public function transform( new Expr\Array_() ) ), - new Arg(new Expr\Array_(array_map(function (string $group) { + new Arg(new Expr\Array_(array_map(static function (string $group) { return create_expr_array_item(new Scalar\String_($group)); }, $this->groups))), ]) diff --git a/src/Transformer/ArrayToDoctrineCollectionTransformer.php b/src/Transformer/ArrayToDoctrineCollectionTransformer.php index 887adcb7..dc7d6e14 100644 --- a/src/Transformer/ArrayToDoctrineCollectionTransformer.php +++ b/src/Transformer/ArrayToDoctrineCollectionTransformer.php @@ -22,7 +22,7 @@ final class ArrayToDoctrineCollectionTransformer implements \Stringable, TransformerInterface, DependentTransformerInterface { public function __construct( - protected TransformerInterface $itemTransformer, + private TransformerInterface $itemTransformer, ) { } diff --git a/src/Transformer/ArrayTransformer.php b/src/Transformer/ArrayTransformer.php index bc60bf40..fd995c70 100644 --- a/src/Transformer/ArrayTransformer.php +++ b/src/Transformer/ArrayTransformer.php @@ -35,7 +35,7 @@ protected function getAssignExpr(Expr $valuesVar, Expr $outputVar, Expr $loopKey return new Expr\Assign(new Expr\ArrayDimFetch($valuesVar), $outputVar); } - public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): ?Expr + public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): Expr { $isArrayCheck = new Expr\FuncCall( new Name('is_array'), diff --git a/src/Transformer/BuiltinTransformer.php b/src/Transformer/BuiltinTransformer.php index 32ccc47b..ed74e023 100644 --- a/src/Transformer/BuiltinTransformer.php +++ b/src/Transformer/BuiltinTransformer.php @@ -24,44 +24,47 @@ */ final readonly class BuiltinTransformer implements TransformerInterface, CheckTypeInterface { - private const CAST_MAPPING = [ + /** + * @var array>> + */ + private const array CAST_MAPPING = [ TypeIdentifier::BOOL->value => [ TypeIdentifier::INT->value => Cast\Int_::class, TypeIdentifier::STRING->value => Cast\String_::class, - TypeIdentifier::FLOAT->value => 'toFloat', - TypeIdentifier::ARRAY->value => 'toArray', - TypeIdentifier::ITERABLE->value => 'toArray', + TypeIdentifier::FLOAT->value => [self::class, 'toFloat'], + TypeIdentifier::ARRAY->value => [self::class, 'toArray'], + TypeIdentifier::ITERABLE->value => [self::class, 'toArray'], ], TypeIdentifier::MIXED->value => [ TypeIdentifier::INT->value => Cast\Int_::class, TypeIdentifier::STRING->value => Cast\String_::class, - TypeIdentifier::FLOAT->value => 'toFloat', + TypeIdentifier::FLOAT->value => [self::class, 'toFloat'], TypeIdentifier::BOOL->value => Cast\Bool_::class, - TypeIdentifier::ARRAY->value => 'toArray', - TypeIdentifier::ITERABLE->value => 'toArray', + TypeIdentifier::ARRAY->value => [self::class, 'toArray'], + TypeIdentifier::ITERABLE->value => [self::class, 'toArray'], ], TypeIdentifier::FLOAT->value => [ TypeIdentifier::STRING->value => Cast\String_::class, TypeIdentifier::INT->value => Cast\Int_::class, TypeIdentifier::BOOL->value => Cast\Bool_::class, - TypeIdentifier::ARRAY->value => 'toArray', - TypeIdentifier::ITERABLE->value => 'toArray', + TypeIdentifier::ARRAY->value => [self::class, 'toArray'], + TypeIdentifier::ITERABLE->value => [self::class, 'toArray'], ], TypeIdentifier::INT->value => [ - TypeIdentifier::FLOAT->value => 'toFloat', + TypeIdentifier::FLOAT->value => [self::class, 'toFloat'], TypeIdentifier::STRING->value => Cast\String_::class, TypeIdentifier::BOOL->value => Cast\Bool_::class, - TypeIdentifier::ARRAY->value => 'toArray', - TypeIdentifier::ITERABLE->value => 'toArray', + TypeIdentifier::ARRAY->value => [self::class, 'toArray'], + TypeIdentifier::ITERABLE->value => [self::class, 'toArray'], ], TypeIdentifier::ITERABLE->value => [ - TypeIdentifier::ARRAY->value => 'fromIteratorToArray', + TypeIdentifier::ARRAY->value => [self::class, 'fromIteratorToArray'], ], TypeIdentifier::ARRAY->value => [], TypeIdentifier::STRING->value => [ - TypeIdentifier::ARRAY->value => 'toArray', - TypeIdentifier::ITERABLE->value => 'toArray', - TypeIdentifier::FLOAT->value => 'toFloat', + TypeIdentifier::ARRAY->value => [self::class, 'toArray'], + TypeIdentifier::ITERABLE->value => [self::class, 'toArray'], + TypeIdentifier::FLOAT->value => [self::class, 'toFloat'], TypeIdentifier::INT->value => Cast\Int_::class, TypeIdentifier::BOOL->value => Cast\Bool_::class, ], @@ -110,15 +113,17 @@ public function transform(Expr $input, Expr $target, PropertyMetadata $propertyM return [$input, []]; } - foreach (self::CAST_MAPPING[$this->sourceType->getTypeIdentifier()->value] as $castType => $castMethod) { + foreach (self::CAST_MAPPING[$this->sourceType->getTypeIdentifier()->value] ?? [] as $castType => $castMethod) { if (\in_array($castType, $targetTypes, true)) { - if (method_exists($this, $castMethod)) { - /* + if (\is_callable($castMethod)) { + /** + * @var (callable(Expr $input): Expr) $castMethod + * * Use specific cast expression if callback exist in this class * * $array = [$source->property]; */ - return [$this->$castMethod($input), []]; + return [$castMethod($input), []]; } if (!class_exists($castMethod)) { @@ -156,17 +161,17 @@ public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $ ); } - private function toArray(Expr $input): Expr + public static function toArray(Expr $input): Expr { return new Expr\Array_([create_expr_array_item($input)]); } - private function toFloat(Expr $input): Expr + public static function toFloat(Expr $input): Expr { return new Cast\Double($input, ['kind' => Cast\Double::KIND_FLOAT]); } - private function fromIteratorToArray(Expr $input): Expr + public static function fromIteratorToArray(Expr $input): Expr { return new Expr\FuncCall(new Name('iterator_to_array'), [ new Arg($input), diff --git a/src/Transformer/ChainTransformerFactory.php b/src/Transformer/ChainTransformerFactory.php index 4973fa35..aa0e4004 100644 --- a/src/Transformer/ChainTransformerFactory.php +++ b/src/Transformer/ChainTransformerFactory.php @@ -33,12 +33,10 @@ public function __construct( public function getTransformer(SourcePropertyMetadata $source, TargetPropertyMetadata $target, MapperMetadata $mapperMetadata): ?TransformerInterface { foreach ($this->factories as $factory) { - if ($factory instanceof TransformerFactoryInterface) { - $transformer = $factory->getTransformer($source, $target, $mapperMetadata); + $transformer = $factory->getTransformer($source, $target, $mapperMetadata); - if (null !== $transformer) { - return $transformer; - } + if (null !== $transformer) { + return $transformer; } } diff --git a/src/Transformer/DateTimeToStringTransformer.php b/src/Transformer/DateTimeToStringTransformer.php index 5eaf3588..7bf7e04c 100644 --- a/src/Transformer/DateTimeToStringTransformer.php +++ b/src/Transformer/DateTimeToStringTransformer.php @@ -43,7 +43,7 @@ public function transform(Expr $input, Expr $target, PropertyMetadata $propertyM ]), []]; } - public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): ?Expr + public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): Expr { return new Expr\Instanceof_($input, new FullyQualified(\DateTimeInterface::class)); } diff --git a/src/Transformer/DateTimeTransformerFactory.php b/src/Transformer/DateTimeTransformerFactory.php index 0132c5a0..2cb23fa9 100644 --- a/src/Transformer/DateTimeTransformerFactory.php +++ b/src/Transformer/DateTimeTransformerFactory.php @@ -37,7 +37,7 @@ public function getTransformer(SourcePropertyMetadata $source, TargetPropertyMet return null; } - protected function createTransformerForSourceAndTarget(?Type $targetType): ?TransformerInterface + private function createTransformerForSourceAndTarget(?Type $targetType): TransformerInterface { // if target is mutable if ($this->isDateTimeMutable($targetType)) { @@ -48,7 +48,7 @@ protected function createTransformerForSourceAndTarget(?Type $targetType): ?Tran return new DateTimeInterfaceToImmutableTransformer(); } - protected function createTransformerForSource(?Type $targetType, SourcePropertyMetadata $metadata): ?TransformerInterface + private function createTransformerForSource(?Type $targetType, SourcePropertyMetadata $metadata): ?TransformerInterface { if ($targetType !== null && $targetType->isIdentifiedBy(TypeIdentifier::STRING)) { return new DateTimeToStringTransformer($metadata->dateTimeFormat); @@ -57,7 +57,7 @@ protected function createTransformerForSource(?Type $targetType, SourcePropertyM return null; } - protected function createTransformerForTarget(?Type $sourceType, ?Type $targetType, TargetPropertyMetadata $metadata): ?TransformerInterface + private function createTransformerForTarget(?Type $sourceType, ?Type $targetType, TargetPropertyMetadata $metadata): ?TransformerInterface { if ($sourceType !== null && $sourceType->isIdentifiedBy(TypeIdentifier::STRING)) { return new StringToDateTimeTransformer($this->getClassName($targetType), $metadata->dateTimeFormat); diff --git a/src/Transformer/DictionaryTransformer.php b/src/Transformer/DictionaryTransformer.php index 7f28665a..8f0ee68a 100644 --- a/src/Transformer/DictionaryTransformer.php +++ b/src/Transformer/DictionaryTransformer.php @@ -35,7 +35,7 @@ protected function getAssignExpr(Expr $valuesVar, Expr $outputVar, Expr $loopKey return new Expr\Assign(new Expr\ArrayDimFetch($valuesVar, $loopKeyVar), $outputVar); } - public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): ?Expr + public function getCheckExpression(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source): Expr { $isArrayCheck = new Expr\FuncCall( new Name('is_iterable'), diff --git a/src/Transformer/DoctrineCollectionTransformerFactory.php b/src/Transformer/DoctrineCollectionTransformerFactory.php index 142f6e74..671eb86d 100644 --- a/src/Transformer/DoctrineCollectionTransformerFactory.php +++ b/src/Transformer/DoctrineCollectionTransformerFactory.php @@ -27,7 +27,7 @@ public function getTransformer(SourcePropertyMetadata $source, TargetPropertyMet return null; } - $isDoctrineCollection = $target->type->isSatisfiedBy(function (Type $type) { + $isDoctrineCollection = $target->type->isSatisfiedBy(static function (Type $type) { if (!$type instanceof Type\ObjectType) { return false; } diff --git a/src/Transformer/MultipleTransformer.php b/src/Transformer/MultipleTransformer.php index 0124834c..776bf27a 100644 --- a/src/Transformer/MultipleTransformer.php +++ b/src/Transformer/MultipleTransformer.php @@ -98,7 +98,7 @@ public function getDependencies(): array public function __toString(): string { $transformerStrings = array_map( - function ($transformerData) { + static function ($transformerData) { if ($transformerData['transformer'] instanceof \Stringable) { return (string) $transformerData['transformer']; } diff --git a/src/Transformer/PropertyTransformer/PropertyTransformerFactory.php b/src/Transformer/PropertyTransformer/PropertyTransformerFactory.php index 5e47f8be..a7b7c288 100644 --- a/src/Transformer/PropertyTransformer/PropertyTransformerFactory.php +++ b/src/Transformer/PropertyTransformer/PropertyTransformerFactory.php @@ -19,8 +19,8 @@ */ final class PropertyTransformerFactory implements PrioritizedTransformerFactoryInterface, TransformerFactoryInterface { - /** @var array|null */ - private $prioritizedPropertyTransformers; + /** @var array */ + private array $prioritizedPropertyTransformers; private Parser $parser; @@ -40,7 +40,7 @@ public function getPriority(): int public function getTransformer(SourcePropertyMetadata $source, TargetPropertyMetadata $target, MapperMetadata $mapperMetadata): ?TransformerInterface { foreach ($this->prioritizedPropertyTransformers() as $id => $propertyTransformer) { - if ($propertyTransformer instanceof PropertyTransformerSupportInterface && $propertyTransformer->supports($source, $target, $mapperMetadata)) { + if ($propertyTransformer->supports($source, $target, $mapperMetadata)) { if ($propertyTransformer instanceof PropertyTransformerComputeInterface) { $computedValueCode = $propertyTransformer->compute($source, $target, $mapperMetadata); $stmts = $this->parser->parse('prioritizedPropertyTransformers) { + if (!isset($this->prioritizedPropertyTransformers)) { $this->prioritizedPropertyTransformers = iterator_to_array($this->propertyTransformersSupportList); uasort( diff --git a/src/Transformer/SymfonyUidTransformerFactory.php b/src/Transformer/SymfonyUidTransformerFactory.php index ddf9e566..29276d27 100644 --- a/src/Transformer/SymfonyUidTransformerFactory.php +++ b/src/Transformer/SymfonyUidTransformerFactory.php @@ -50,10 +50,10 @@ private function getUid(?Type $type): array return [false, false, null]; } - /** @var class-string|null $typeClassName */ + /** @var class-string $typeClassName */ $typeClassName = $type->getClassName(); - if (null === $typeClassName || !class_exists($typeClassName)) { + if (!class_exists($typeClassName)) { return [false, false, null]; } diff --git a/tests/AutoMapperMapToTest.php b/tests/AutoMapperMapToTest.php index 644c3ef0..683ef7a6 100644 --- a/tests/AutoMapperMapToTest.php +++ b/tests/AutoMapperMapToTest.php @@ -22,7 +22,7 @@ */ class AutoMapperMapToTest extends AutoMapperTestCase { - public function testMapTo() + public function testMapTo(): void { $foo = new FooMapTo('foo'); $bar = $this->autoMapper->map($foo, Bar::class); @@ -34,10 +34,10 @@ public function testMapTo() $this->assertSame('d', $bar->getB()); } - public function testMapToArray() + public function testMapToArray(): void { $expressionLanguageProvider = new ExpressionLanguageProvider(new ServiceLocator([ - 'transformerWithDependency' => fn () => fn () => new TransformerWithDependency(new FooDependency()), + 'transformerWithDependency' => static fn () => static fn () => new TransformerWithDependency(new FooDependency()), ])); $this->autoMapper = AutoMapperBuilder::buildAutoMapper(propertyTransformers: [new TransformerWithDependency(new FooDependency())], expressionLanguageProvider: $expressionLanguageProvider); @@ -84,10 +84,10 @@ public function testMapToArray() $this->assertSame(0.0, $bar['fooFloat']); } - public function testMapToArrayGroups() + public function testMapToArrayGroups(): void { $expressionLanguageProvider = new ExpressionLanguageProvider(new ServiceLocator([ - 'transformerWithDependency' => fn () => fn () => new TransformerWithDependency(new FooDependency()), + 'transformerWithDependency' => static fn () => static fn () => new TransformerWithDependency(new FooDependency()), ])); $this->autoMapper = AutoMapperBuilder::buildAutoMapper(propertyTransformers: [new TransformerWithDependency(new FooDependency())], expressionLanguageProvider: $expressionLanguageProvider); @@ -107,7 +107,7 @@ public function testMapToArrayGroups() self::assertArrayNotHasKey('externalProperty', $bar); } - public function testMapFromArray() + public function testMapFromArray(): void { $foo = ['b' => 'foo', 'bar' => 'bar', 'baz' => 'baz', 'foo' => 'foo', 'c' => 'foo', 'd' => 'foo']; $bar = $this->autoMapper->map($foo, Bar::class); @@ -120,7 +120,7 @@ public function testMapFromArray() $this->assertSame('', $bar->getB()); } - public function testPriority() + public function testPriority(): void { $foo = new PriorityMapTo('foo'); @@ -130,7 +130,7 @@ public function testPriority() self::assertSame('foo', $result['foo']); } - public function testBadDefinitionOnTransformer() + public function testBadDefinitionOnTransformer(): void { $foo = new BadMapToTransformer('foo'); diff --git a/tests/AutoMapperTest.php b/tests/AutoMapperTest.php index 352fd8db..caf1cfb5 100644 --- a/tests/AutoMapperTest.php +++ b/tests/AutoMapperTest.php @@ -65,7 +65,7 @@ protected function setUp(): void parent::setUp(); $this->setUpVarDumper([ - \Throwable::class => function (\Throwable $e) { + \Throwable::class => static function (\Throwable $e) { return [ 'class' => $e::class, 'message' => $e->getMessage(), @@ -354,7 +354,7 @@ public function testGroupsToArray(): void public function testSkippedGroups(): void { $eventDispatcher = new EventDispatcher(); - $eventDispatcher->addListener(PropertyMetadataEvent::class, function (PropertyMetadataEvent $event) { + $eventDispatcher->addListener(PropertyMetadataEvent::class, static function (PropertyMetadataEvent $event) { $event->disableGroupsCheck = true; }); @@ -646,7 +646,7 @@ public function testCircularReferenceHandlerOnContext(): void $nodeA->parent = $nodeA; $context = new MapperContext(); - $context->setCircularReferenceHandler(function () { + $context->setCircularReferenceHandler(static function () { return 'foo'; }); diff --git a/tests/AutoMapperTest/ArrayAccess/map.php b/tests/AutoMapperTest/ArrayAccess/map.php index da186c4f..698ed717 100644 --- a/tests/AutoMapperTest/ArrayAccess/map.php +++ b/tests/AutoMapperTest/ArrayAccess/map.php @@ -18,7 +18,7 @@ class Foo public int $bar = 2; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map(new LikeArray(['foo' => 'foofoo', 'bar' => 10]), Foo::class); diff --git a/tests/AutoMapperTest/ArrayConsistency/map.php b/tests/AutoMapperTest/ArrayConsistency/map.php index ac8b666a..41f99c74 100644 --- a/tests/AutoMapperTest/ArrayConsistency/map.php +++ b/tests/AutoMapperTest/ArrayConsistency/map.php @@ -79,7 +79,7 @@ public function getValues(): Collection } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $from = new From(); diff --git a/tests/AutoMapperTest/ArrayDefaultWithKey/map.php b/tests/AutoMapperTest/ArrayDefaultWithKey/map.php index 02de44b6..fe148546 100644 --- a/tests/AutoMapperTest/ArrayDefaultWithKey/map.php +++ b/tests/AutoMapperTest/ArrayDefaultWithKey/map.php @@ -14,7 +14,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $foo = new Foo([ diff --git a/tests/AutoMapperTest/ArrayNested/map.php b/tests/AutoMapperTest/ArrayNested/map.php index 10920e34..ede2ed9a 100644 --- a/tests/AutoMapperTest/ArrayNested/map.php +++ b/tests/AutoMapperTest/ArrayNested/map.php @@ -28,7 +28,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $classContainer = new ClassContainer(); diff --git a/tests/AutoMapperTest/ArrayNotNested/map.php b/tests/AutoMapperTest/ArrayNotNested/map.php index be377bda..b9bdcf1c 100644 --- a/tests/AutoMapperTest/ArrayNotNested/map.php +++ b/tests/AutoMapperTest/ArrayNotNested/map.php @@ -14,13 +14,13 @@ class UserApiResource #[\AllowDynamicProperties] class UserEntity { - public function setRoles(array $roles) + public function setRoles(array $roles): void { $this->roles = $roles; // [["ROLE_USER"]]; } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $userApiResource = new UserApiResource(); diff --git a/tests/AutoMapperTest/ArraySourceCastAlreadyCorrect/map.php b/tests/AutoMapperTest/ArraySourceCastAlreadyCorrect/map.php index c1c9ca36..85de224f 100644 --- a/tests/AutoMapperTest/ArraySourceCastAlreadyCorrect/map.php +++ b/tests/AutoMapperTest/ArraySourceCastAlreadyCorrect/map.php @@ -15,7 +15,7 @@ class Dto public array $names; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); // Values already match target types — should pass through without issues diff --git a/tests/AutoMapperTest/ArraySourceCastDateTime/map.php b/tests/AutoMapperTest/ArraySourceCastDateTime/map.php index 19a54454..4fee2e93 100644 --- a/tests/AutoMapperTest/ArraySourceCastDateTime/map.php +++ b/tests/AutoMapperTest/ArraySourceCastDateTime/map.php @@ -12,7 +12,7 @@ class Dto public array $dates; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastDictionary/map.php b/tests/AutoMapperTest/ArraySourceCastDictionary/map.php index 5fb6c27f..94892d6c 100644 --- a/tests/AutoMapperTest/ArraySourceCastDictionary/map.php +++ b/tests/AutoMapperTest/ArraySourceCastDictionary/map.php @@ -15,7 +15,7 @@ class Dto public array $rates; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastInnerValues/map.php b/tests/AutoMapperTest/ArraySourceCastInnerValues/map.php index 7c18b447..f8ffef27 100644 --- a/tests/AutoMapperTest/ArraySourceCastInnerValues/map.php +++ b/tests/AutoMapperTest/ArraySourceCastInnerValues/map.php @@ -21,7 +21,7 @@ class Dto public array $flags; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastNested/map.php b/tests/AutoMapperTest/ArraySourceCastNested/map.php index 73182198..4bb82a54 100644 --- a/tests/AutoMapperTest/ArraySourceCastNested/map.php +++ b/tests/AutoMapperTest/ArraySourceCastNested/map.php @@ -12,7 +12,7 @@ class Dto public array $matrix; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastNullable/map.php b/tests/AutoMapperTest/ArraySourceCastNullable/map.php index 04a2bdab..574b1367 100644 --- a/tests/AutoMapperTest/ArraySourceCastNullable/map.php +++ b/tests/AutoMapperTest/ArraySourceCastNullable/map.php @@ -12,7 +12,7 @@ class Dto public array $values; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastObjects/map.php b/tests/AutoMapperTest/ArraySourceCastObjects/map.php index cd221f93..2a1fed48 100644 --- a/tests/AutoMapperTest/ArraySourceCastObjects/map.php +++ b/tests/AutoMapperTest/ArraySourceCastObjects/map.php @@ -18,7 +18,7 @@ class ContainerDto public array $items; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastShape/map.php b/tests/AutoMapperTest/ArraySourceCastShape/map.php index 46176104..ceb20ee1 100644 --- a/tests/AutoMapperTest/ArraySourceCastShape/map.php +++ b/tests/AutoMapperTest/ArraySourceCastShape/map.php @@ -12,7 +12,7 @@ class Dto public array $profile; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastShapeComplex/map.php b/tests/AutoMapperTest/ArraySourceCastShapeComplex/map.php index d1581375..2f47cd4f 100644 --- a/tests/AutoMapperTest/ArraySourceCastShapeComplex/map.php +++ b/tests/AutoMapperTest/ArraySourceCastShapeComplex/map.php @@ -47,7 +47,7 @@ class DtoMixedDepth public array $data; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); // 1. Object field + collection of objects + scalar casts diff --git a/tests/AutoMapperTest/ArraySourceCastShapeNested/map.php b/tests/AutoMapperTest/ArraySourceCastShapeNested/map.php index 74d6269f..ef51f6aa 100644 --- a/tests/AutoMapperTest/ArraySourceCastShapeNested/map.php +++ b/tests/AutoMapperTest/ArraySourceCastShapeNested/map.php @@ -12,7 +12,7 @@ class Dto public array $data; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map([ diff --git a/tests/AutoMapperTest/ArraySourceCastShapeOptional/map.php b/tests/AutoMapperTest/ArraySourceCastShapeOptional/map.php index 1b167be0..b0341515 100644 --- a/tests/AutoMapperTest/ArraySourceCastShapeOptional/map.php +++ b/tests/AutoMapperTest/ArraySourceCastShapeOptional/map.php @@ -12,7 +12,7 @@ class Dto public array $profile; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); // With optional key present diff --git a/tests/AutoMapperTest/ArraySourceCastShapeTypedSource/map.php b/tests/AutoMapperTest/ArraySourceCastShapeTypedSource/map.php index d5b10541..21c38099 100644 --- a/tests/AutoMapperTest/ArraySourceCastShapeTypedSource/map.php +++ b/tests/AutoMapperTest/ArraySourceCastShapeTypedSource/map.php @@ -18,7 +18,7 @@ class TargetDto public array $data; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $source = new SourceDto(); diff --git a/tests/AutoMapperTest/ArraySourcePropertyType/map.php b/tests/AutoMapperTest/ArraySourcePropertyType/map.php index 97de05b9..d0e0c407 100644 --- a/tests/AutoMapperTest/ArraySourcePropertyType/map.php +++ b/tests/AutoMapperTest/ArraySourcePropertyType/map.php @@ -14,7 +14,7 @@ class Dto public array $age; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield $autoMapper->map(['age' => ['10']], Dto::class); diff --git a/tests/AutoMapperTest/ConstructorWithRelation/map.php b/tests/AutoMapperTest/ConstructorWithRelation/map.php index 008f81fd..7d26830c 100644 --- a/tests/AutoMapperTest/ConstructorWithRelation/map.php +++ b/tests/AutoMapperTest/ConstructorWithRelation/map.php @@ -29,7 +29,7 @@ public function __construct(IntDto $int, string $name, int $age = 30) } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $user = ['name' => 'foo']; diff --git a/tests/AutoMapperTest/ConstructorWithSerializedName/map.php b/tests/AutoMapperTest/ConstructorWithSerializedName/map.php index 5f978eba..5bbb09d9 100644 --- a/tests/AutoMapperTest/ConstructorWithSerializedName/map.php +++ b/tests/AutoMapperTest/ConstructorWithSerializedName/map.php @@ -16,7 +16,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield 'to_array' => $autoMapper->map(new Bar(true), 'array'); diff --git a/tests/AutoMapperTest/DeepPopulateMergeExisting/map.php b/tests/AutoMapperTest/DeepPopulateMergeExisting/map.php index 080782c3..b48c155a 100644 --- a/tests/AutoMapperTest/DeepPopulateMergeExisting/map.php +++ b/tests/AutoMapperTest/DeepPopulateMergeExisting/map.php @@ -66,7 +66,7 @@ class FooWithArrayCollection public ArrayCollection $bars; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(mapPrivatePropertiesAndMethod: true); $data = [ diff --git a/tests/AutoMapperTest/DeepPopulateWithArrayCollection/map.php b/tests/AutoMapperTest/DeepPopulateWithArrayCollection/map.php index 4d3da859..6d11e63a 100644 --- a/tests/AutoMapperTest/DeepPopulateWithArrayCollection/map.php +++ b/tests/AutoMapperTest/DeepPopulateWithArrayCollection/map.php @@ -24,7 +24,7 @@ class FooWithArrayCollection public ArrayCollection $bars; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $data = [ diff --git a/tests/AutoMapperTest/DiscriminatorAttributeArray/map.php b/tests/AutoMapperTest/DiscriminatorAttributeArray/map.php index 598b3878..af8ce20c 100644 --- a/tests/AutoMapperTest/DiscriminatorAttributeArray/map.php +++ b/tests/AutoMapperTest/DiscriminatorAttributeArray/map.php @@ -48,7 +48,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(mapPrivatePropertiesAndMethod: true); $pet = new Dog('Rex', 'German Shepherd'); diff --git a/tests/AutoMapperTest/DiscriminatorFromAndTo/map.php b/tests/AutoMapperTest/DiscriminatorFromAndTo/map.php index 4250812b..14fa9054 100644 --- a/tests/AutoMapperTest/DiscriminatorFromAndTo/map.php +++ b/tests/AutoMapperTest/DiscriminatorFromAndTo/map.php @@ -84,7 +84,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(mapPrivatePropertiesAndMethod: true); $pet = new Dog('Rex', 'German Shepherd'); diff --git a/tests/AutoMapperTest/DiscriminatorMapAndInterface/map.php b/tests/AutoMapperTest/DiscriminatorMapAndInterface/map.php index 6d0d5bb0..82efdb4d 100644 --- a/tests/AutoMapperTest/DiscriminatorMapAndInterface/map.php +++ b/tests/AutoMapperTest/DiscriminatorMapAndInterface/map.php @@ -40,7 +40,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(mapPrivatePropertiesAndMethod: true); $something = [ diff --git a/tests/AutoMapperTest/DoctrineCollections/map.php b/tests/AutoMapperTest/DoctrineCollections/map.php index 6eba093d..5d358436 100644 --- a/tests/AutoMapperTest/DoctrineCollections/map.php +++ b/tests/AutoMapperTest/DoctrineCollections/map.php @@ -22,7 +22,7 @@ class Library public Collection $books; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $library = new Library(); diff --git a/tests/AutoMapperTest/Ignore/map.php b/tests/AutoMapperTest/Ignore/map.php index 5782c09a..2b2d466f 100644 --- a/tests/AutoMapperTest/Ignore/map.php +++ b/tests/AutoMapperTest/Ignore/map.php @@ -21,7 +21,7 @@ public function getId(): int } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $foo = new FooIgnore(); diff --git a/tests/AutoMapperTest/Nested/map.php b/tests/AutoMapperTest/Nested/map.php index d73b9e4e..addbaa77 100644 --- a/tests/AutoMapperTest/Nested/map.php +++ b/tests/AutoMapperTest/Nested/map.php @@ -39,7 +39,7 @@ class Address public string $city; } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $dto = new UserDto( userAddressZipcode: '12345', diff --git a/tests/AutoMapperTest/ObjectWithPropertyAsUnknownArray/map.php b/tests/AutoMapperTest/ObjectWithPropertyAsUnknownArray/map.php index a31fa3a5..cfc5a7c9 100644 --- a/tests/AutoMapperTest/ObjectWithPropertyAsUnknownArray/map.php +++ b/tests/AutoMapperTest/ObjectWithPropertyAsUnknownArray/map.php @@ -32,7 +32,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $entity = new Page(); $entity->components[] = ['name' => 'my name']; diff --git a/tests/AutoMapperTest/Paramters/map.php b/tests/AutoMapperTest/Paramters/map.php index f7f01948..cb420fa1 100644 --- a/tests/AutoMapperTest/Paramters/map.php +++ b/tests/AutoMapperTest/Paramters/map.php @@ -36,7 +36,7 @@ public function setParameters(array $parameters): void } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); $arguments = ['foo', 'bar', 'baz']; diff --git a/tests/AutoMapperTest/PrivatePropertyInConstructors/map.php b/tests/AutoMapperTest/PrivatePropertyInConstructors/map.php index 511c0821..76f66d6f 100644 --- a/tests/AutoMapperTest/PrivatePropertyInConstructors/map.php +++ b/tests/AutoMapperTest/PrivatePropertyInConstructors/map.php @@ -42,7 +42,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield 'from-array' => $autoMapper->map( diff --git a/tests/AutoMapperTest/Provider/map.php b/tests/AutoMapperTest/Provider/map.php index 1318a054..05b66da0 100644 --- a/tests/AutoMapperTest/Provider/map.php +++ b/tests/AutoMapperTest/Provider/map.php @@ -30,7 +30,7 @@ class MyObject public string $bar; } -return (function () { +return (static function () { $myObject = new MyObject(); $myObject->foo = 'bar'; diff --git a/tests/AutoMapperTest/StringUnionProperty/map.php b/tests/AutoMapperTest/StringUnionProperty/map.php index 23e212f6..f2f5162a 100644 --- a/tests/AutoMapperTest/StringUnionProperty/map.php +++ b/tests/AutoMapperTest/StringUnionProperty/map.php @@ -15,7 +15,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield 'bar' => $autoMapper->map(new ObjectsUnionProperty('bar'), 'array'); diff --git a/tests/AutoMapperTest/SymfonyUId/map.php b/tests/AutoMapperTest/SymfonyUId/map.php index 4f8aea3d..6dceae69 100644 --- a/tests/AutoMapperTest/SymfonyUId/map.php +++ b/tests/AutoMapperTest/SymfonyUId/map.php @@ -56,7 +56,7 @@ public function getUuid(): Uuid } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); // array -> object diff --git a/tests/AutoMapperTest/UnionProperty/map.php b/tests/AutoMapperTest/UnionProperty/map.php index 42faa8c9..dbe00d2b 100644 --- a/tests/AutoMapperTest/UnionProperty/map.php +++ b/tests/AutoMapperTest/UnionProperty/map.php @@ -30,7 +30,7 @@ public function __construct( } } -return (function () { +return (static function () { $autoMapper = AutoMapperBuilder::buildAutoMapper(); yield 'bar' => $autoMapper->map(new ObjectsUnionProperty(new Bar('bar')), 'array'); diff --git a/tests/Bundle/Resources/App/AppKernel.php b/tests/Bundle/Resources/App/AppKernel.php index 14607255..ca783df7 100644 --- a/tests/Bundle/Resources/App/AppKernel.php +++ b/tests/Bundle/Resources/App/AppKernel.php @@ -38,6 +38,10 @@ public function getProjectDir(): string public function getCacheDir(): string { + if ($this->getEnvironment() === 'dev') { + return parent::getCacheDir(); + } + return parent::getCacheDir() . '/' . md5($this->additionalConfigFile ?? ''); } } diff --git a/tests/Bundle/Resources/App/Entity/Pet.php b/tests/Bundle/Resources/App/Entity/Pet.php index 12df3f64..e9c245db 100644 --- a/tests/Bundle/Resources/App/Entity/Pet.php +++ b/tests/Bundle/Resources/App/Entity/Pet.php @@ -6,12 +6,10 @@ use Symfony\Component\Serializer\Attribute\DiscriminatorMap; -#[ - DiscriminatorMap(typeProperty: 'type', mapping: [ +#[DiscriminatorMap(typeProperty: 'type', mapping: [ 'cat' => Cat::class, 'dog' => Dog::class, - ]) -] + ])] class Pet { /** @var string */ diff --git a/tests/Bundle/Resources/App/Entity/UserDTO.php b/tests/Bundle/Resources/App/Entity/UserDTO.php index 50a903c0..0e6a7e03 100644 --- a/tests/Bundle/Resources/App/Entity/UserDTO.php +++ b/tests/Bundle/Resources/App/Entity/UserDTO.php @@ -56,7 +56,7 @@ class UserDTO */ public $languages = []; - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/Bundle/Resources/bin/console b/tests/Bundle/Resources/bin/console old mode 100644 new mode 100755 diff --git a/tests/Bundle/ServiceInstantiationTest.php b/tests/Bundle/ServiceInstantiationTest.php index d253aa8c..4fdc9918 100644 --- a/tests/Bundle/ServiceInstantiationTest.php +++ b/tests/Bundle/ServiceInstantiationTest.php @@ -292,7 +292,7 @@ protected function tearDown(): void } #[DataProvider('mapProvider')] - public function testObjectMapper($expect, $args, array $deps = []) + public function testObjectMapper($expect, $args, array $deps = []): void { static::bootKernel(); $mapper = static::$kernel->getContainer()->get(ObjectMapperInterface::class); diff --git a/tests/Doctrine/DoctrineTest.php b/tests/Doctrine/DoctrineTest.php index 85780879..6092c281 100644 --- a/tests/Doctrine/DoctrineTest.php +++ b/tests/Doctrine/DoctrineTest.php @@ -32,7 +32,7 @@ protected function setUp(): void $this->autoMapper = AutoMapperBuilder::buildAutoMapper(objectManager: $this->entityManager); } - private function buildDatabase() + private function buildDatabase(): void { // delete the database file if (file_exists(__DIR__ . '/db.sqlite')) { diff --git a/tests/Fixtures/MapTo/Bar.php b/tests/Fixtures/MapTo/Bar.php index acf5e8fa..58e117e5 100644 --- a/tests/Fixtures/MapTo/Bar.php +++ b/tests/Fixtures/MapTo/Bar.php @@ -26,7 +26,7 @@ public function __construct( } #[MapFrom(source: FooMapTo::class, property: 'd')] - public function setB(string $b) + public function setB(string $b): void { $this->b = $b; } diff --git a/tests/Fixtures/Normalizer/DeepObjectPopulateChildDummy.php b/tests/Fixtures/Normalizer/DeepObjectPopulateChildDummy.php index 54ae1a12..3ec43ce3 100644 --- a/tests/Fixtures/Normalizer/DeepObjectPopulateChildDummy.php +++ b/tests/Fixtures/Normalizer/DeepObjectPopulateChildDummy.php @@ -16,12 +16,12 @@ public function getFoo() return $this->foo; } - public function setFoo($foo) + public function setFoo($foo): void { $this->foo = $foo; } - public function setBar($bar) + public function setBar($bar): void { $this->bar = $bar; } diff --git a/tests/Fixtures/Normalizer/DeepObjectPopulateParentDummy.php b/tests/Fixtures/Normalizer/DeepObjectPopulateParentDummy.php index 3dd73801..efd7d44a 100644 --- a/tests/Fixtures/Normalizer/DeepObjectPopulateParentDummy.php +++ b/tests/Fixtures/Normalizer/DeepObjectPopulateParentDummy.php @@ -11,7 +11,7 @@ class DeepObjectPopulateParentDummy */ private $child; - public function setChild(?DeepObjectPopulateChildDummy $child) + public function setChild(?DeepObjectPopulateChildDummy $child): void { $this->child = $child; } diff --git a/tests/Fixtures/Normalizer/GroupDummy.php b/tests/Fixtures/Normalizer/GroupDummy.php index 26597b31..5f07d166 100644 --- a/tests/Fixtures/Normalizer/GroupDummy.php +++ b/tests/Fixtures/Normalizer/GroupDummy.php @@ -18,7 +18,7 @@ class GroupDummy extends GroupDummyParent implements GroupDummyInterface private $symfony; #[Groups(['b'])] - public function setBar($bar) + public function setBar($bar): void { $this->bar = $bar; } @@ -29,7 +29,7 @@ public function getBar() return $this->bar; } - public function setFoo($foo) + public function setFoo($foo): void { $this->foo = $foo; } @@ -39,7 +39,7 @@ public function getFoo() return $this->foo; } - public function setFooBar($fooBar) + public function setFooBar($fooBar): void { $this->fooBar = $fooBar; } @@ -50,7 +50,7 @@ public function isFooBar() return $this->fooBar; } - public function setSymfony($symfony) + public function setSymfony($symfony): void { $this->symfony = $symfony; } diff --git a/tests/Fixtures/Normalizer/GroupDummyParent.php b/tests/Fixtures/Normalizer/GroupDummyParent.php index 6833338f..8a23f53a 100644 --- a/tests/Fixtures/Normalizer/GroupDummyParent.php +++ b/tests/Fixtures/Normalizer/GroupDummyParent.php @@ -12,7 +12,7 @@ class GroupDummyParent private $kevin; private $coopTilleuls; - public function setKevin($kevin) + public function setKevin($kevin): void { $this->kevin = $kevin; } @@ -22,7 +22,7 @@ public function getKevin() return $this->kevin; } - public function setCoopTilleuls($coopTilleuls) + public function setCoopTilleuls($coopTilleuls): void { $this->coopTilleuls = $coopTilleuls; } diff --git a/tests/Fixtures/Normalizer/ToBeProxyfiedDummy.php b/tests/Fixtures/Normalizer/ToBeProxyfiedDummy.php index 39142bd0..23bb556b 100644 --- a/tests/Fixtures/Normalizer/ToBeProxyfiedDummy.php +++ b/tests/Fixtures/Normalizer/ToBeProxyfiedDummy.php @@ -8,7 +8,7 @@ class ToBeProxyfiedDummy { private $foo; - public function setFoo($foo) + public function setFoo($foo): void { $this->foo = $foo; } diff --git a/tests/Fixtures/ReflectionExtractorTestFixture.php b/tests/Fixtures/ReflectionExtractorTestFixture.php index 6696d3e7..73daa298 100644 --- a/tests/Fixtures/ReflectionExtractorTestFixture.php +++ b/tests/Fixtures/ReflectionExtractorTestFixture.php @@ -15,7 +15,7 @@ public function getFoo(): string return 'string'; } - public function setFoo(string $foo) + public function setFoo(string $foo): void { } @@ -34,11 +34,11 @@ public function hasFoz(): bool return false; } - public function __get($name) + public function __get($name): void { } - public function __set($name, $value) + public function __set($name, $value): void { } } diff --git a/tests/Fixtures/Transformer/CustomTransformer/FromSourceCustomModelTransformer.php b/tests/Fixtures/Transformer/CustomTransformer/FromSourceCustomModelTransformer.php index 3dbd5b0b..aee3d817 100644 --- a/tests/Fixtures/Transformer/CustomTransformer/FromSourceCustomModelTransformer.php +++ b/tests/Fixtures/Transformer/CustomTransformer/FromSourceCustomModelTransformer.php @@ -16,7 +16,7 @@ { public function supports(SourcePropertyMetadata $source, TargetPropertyMetadata $target, MapperMetadata $mapperMetadata): bool { - if (!$source->type->isSatisfiedBy(fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { + if (!$source->type->isSatisfiedBy(static fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { return false; } diff --git a/tests/Fixtures/Transformer/CustomTransformer/FromTargetCustomModelTransformer.php b/tests/Fixtures/Transformer/CustomTransformer/FromTargetCustomModelTransformer.php index 6868808b..5338d79d 100644 --- a/tests/Fixtures/Transformer/CustomTransformer/FromTargetCustomModelTransformer.php +++ b/tests/Fixtures/Transformer/CustomTransformer/FromTargetCustomModelTransformer.php @@ -21,7 +21,7 @@ public function supports(SourcePropertyMetadata $source, TargetPropertyMetadata return false; } - if (!$target->type->isSatisfiedBy(fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { + if (!$target->type->isSatisfiedBy(static fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { return false; } diff --git a/tests/Fixtures/Transformer/CustomTransformer/SourceTargetCustomModelTransformer.php b/tests/Fixtures/Transformer/CustomTransformer/SourceTargetCustomModelTransformer.php index 48ebf6ec..1817bed6 100644 --- a/tests/Fixtures/Transformer/CustomTransformer/SourceTargetCustomModelTransformer.php +++ b/tests/Fixtures/Transformer/CustomTransformer/SourceTargetCustomModelTransformer.php @@ -17,11 +17,11 @@ { public function supports(SourcePropertyMetadata $source, TargetPropertyMetadata $target, MapperMetadata $mapperMetadata): bool { - if (!$source->type->isSatisfiedBy(fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { + if (!$source->type->isSatisfiedBy(static fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === AddressDTO::class)) { return false; } - if (!$target->type->isSatisfiedBy(fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === Address::class)) { + if (!$target->type->isSatisfiedBy(static fn (Type $type) => $type instanceof Type\ObjectType && $type->getClassName() === Address::class)) { return false; } diff --git a/tests/Fixtures/UserDTO.php b/tests/Fixtures/UserDTO.php index 38172d70..9ee689d0 100644 --- a/tests/Fixtures/UserDTO.php +++ b/tests/Fixtures/UserDTO.php @@ -63,7 +63,7 @@ class UserDTO /** @var \DateTimeInterface[]|int[] */ public array $times = []; - public function setName($name) + public function setName($name): void { $this->name = $name; } diff --git a/tests/MapperContextTest.php b/tests/MapperContextTest.php index a0de72a4..88897f54 100644 --- a/tests/MapperContextTest.php +++ b/tests/MapperContextTest.php @@ -24,9 +24,9 @@ public function testIsAllowedAttribute(): void $user = new UserDTO(); - self::assertTrue(MapperContext::isAllowedAttribute($context->toArray(), 'id', function () use ($user) { return !isset($user->id) && null === $user->id; }, false)); - self::assertFalse(MapperContext::isAllowedAttribute($context->toArray(), 'age', function () use ($user) { return !isset($user->age) && null === $user->age; }, false)); - self::assertFalse(MapperContext::isAllowedAttribute($context->toArray(), 'name', function () { return false; }, false)); + self::assertTrue(MapperContext::isAllowedAttribute($context->toArray(), 'id', static function () use ($user) { return !isset($user->id) && null === $user->id; }, false)); + self::assertFalse(MapperContext::isAllowedAttribute($context->toArray(), 'age', static function () use ($user) { return !isset($user->age) && null === $user->age; }, false)); + self::assertFalse(MapperContext::isAllowedAttribute($context->toArray(), 'name', static function () { return false; }, false)); } public function testCircularReferenceLimit(): void @@ -64,7 +64,7 @@ public function testCircularReferenceHandler(): void { $object = new \stdClass(); $context = new MapperContext(); - $context->setCircularReferenceHandler(function ($object) { + $context->setCircularReferenceHandler(static function ($object) { return $object; }); $context = MapperContext::withReference($context->toArray(), 'reference', $object); @@ -138,7 +138,7 @@ public function testWithNewContextAllowedAttributesNested(): void ], ]; - self::assertTrue(MapperContext::isAllowedAttribute($context, 'foo', function () use ($data) { return !isset($data->foo) && null === $data->foo; }, false)); + self::assertTrue(MapperContext::isAllowedAttribute($context, 'foo', static function () use ($data) { return !isset($data->foo) && null === $data->foo; }, false)); $newContext = MapperContext::withNewContext($context, 'foo'); self::assertEquals(['bar'], $newContext[MapperContext::ALLOWED_ATTRIBUTES]); @@ -148,7 +148,7 @@ public function testSkipNullValues(): void { $data = new UserDTO(); $context = [MapperContext::SKIP_NULL_VALUES => true]; - self::assertFalse(MapperContext::isAllowedAttribute($context, 'id', function () use ($data) { return !isset($data->id) && null === $data->id; }, false)); + self::assertFalse(MapperContext::isAllowedAttribute($context, 'id', static function () use ($data) { return !isset($data->id) && null === $data->id; }, false)); } #[DataProvider('forcedTimeZoneProvider')] diff --git a/tests/Normalizer/Features/AttributesTestTrait.php b/tests/Normalizer/Features/AttributesTestTrait.php index 2aa836b7..745eefb5 100644 --- a/tests/Normalizer/Features/AttributesTestTrait.php +++ b/tests/Normalizer/Features/AttributesTestTrait.php @@ -26,7 +26,7 @@ abstract protected function getNormalizerForAttributes(): NormalizerInterface; abstract protected function getDenormalizerForAttributes(): DenormalizerInterface; - public function testAttributesNormalize() + public function testAttributesNormalize(): void { $normalizer = $this->getNormalizerForAttributes(); @@ -60,7 +60,7 @@ public function testAttributesNormalize() ); } - public function testAttributesContextDenormalize() + public function testAttributesContextDenormalize(): void { $normalizer = $this->getDenormalizerForAttributes(); @@ -81,7 +81,7 @@ public function testAttributesContextDenormalize() ], ObjectOuter::class, null, $context)); } - public function testAttributesContextDenormalizeIgnoreExtraAttributes() + public function testAttributesContextDenormalizeIgnoreExtraAttributes(): void { $normalizer = $this->getDenormalizerForAttributes(); diff --git a/tests/Normalizer/Features/CallbacksObject.php b/tests/Normalizer/Features/CallbacksObject.php index 3dbc27df..5862bc31 100644 --- a/tests/Normalizer/Features/CallbacksObject.php +++ b/tests/Normalizer/Features/CallbacksObject.php @@ -33,7 +33,7 @@ public function getBar() return $this->bar; } - public function setBar($bar) + public function setBar($bar): void { $this->bar = $bar; } @@ -43,7 +43,7 @@ public function getFoo(): ?string return $this->foo; } - public function setFoo(?string $foo) + public function setFoo(?string $foo): void { $this->foo = $foo; } diff --git a/tests/Normalizer/Features/CallbacksTestTrait.php b/tests/Normalizer/Features/CallbacksTestTrait.php index 48b87442..f2ed9230 100644 --- a/tests/Normalizer/Features/CallbacksTestTrait.php +++ b/tests/Normalizer/Features/CallbacksTestTrait.php @@ -30,7 +30,7 @@ abstract protected function getNormalizerForCallbacks(): NormalizerInterface; abstract protected function getNormalizerForCallbacksWithPropertyTypeExtractor(): NormalizerInterface; #[DataProvider('provideNormalizeCallbacks')] - public function testNormalizeCallbacks($callbacks, $valueBar, $result) + public function testNormalizeCallbacks($callbacks, $valueBar, $result): void { self::markTestSkipped('Callbacks not supported.'); @@ -43,7 +43,7 @@ public function testNormalizeCallbacks($callbacks, $valueBar, $result) } #[DataProvider('provideNormalizeCallbacks')] - public function testNormalizeCallbacksWithTypedProperty($callbacks, $valueBar, $result) + public function testNormalizeCallbacksWithTypedProperty($callbacks, $valueBar, $result): void { self::markTestSkipped('Callbacks not supported.'); @@ -56,7 +56,7 @@ public function testNormalizeCallbacksWithTypedProperty($callbacks, $valueBar, $ } #[DataProvider('provideDenormalizeCallbacks')] - public function testDenormalizeCallbacks($callbacks, $valueBar, $result) + public function testDenormalizeCallbacks($callbacks, $valueBar, $result): void { self::markTestSkipped('Callbacks not supported.'); @@ -68,7 +68,7 @@ public function testDenormalizeCallbacks($callbacks, $valueBar, $result) } #[DataProvider('providerDenormalizeCallbacksWithTypedProperty')] - public function testDenormalizeCallbacksWithTypedProperty($callbacks, $valueBar, $result) + public function testDenormalizeCallbacksWithTypedProperty($callbacks, $valueBar, $result): void { self::markTestSkipped('Callbacks not supported.'); @@ -80,7 +80,7 @@ public function testDenormalizeCallbacksWithTypedProperty($callbacks, $valueBar, } #[DataProvider('providerDenormalizeCallbacksWithTypedProperty')] - public function testDenormalizeCallbacksWithNoConstructorArgument($callbacks, $valueBar, $result) + public function testDenormalizeCallbacksWithNoConstructorArgument($callbacks, $valueBar, $result): void { self::markTestSkipped('Callbacks not supported.'); @@ -98,7 +98,7 @@ public function __construct() } #[DataProvider('provideInvalidCallbacks')] - public function testUncallableCallbacks($callbacks) + public function testUncallableCallbacks($callbacks): void { self::markTestSkipped('Callbacks not supported.'); @@ -151,7 +151,7 @@ public static function provideNormalizeCallbacks() ], 'Collect a property' => [ [ - 'bar' => function (array $bars) { + 'bar' => static function (array $bars) { $result = ''; foreach ($bars as $bar) { $result .= $bar->bar; @@ -165,7 +165,7 @@ public static function provideNormalizeCallbacks() ], 'Count a property' => [ [ - 'bar' => fn (array $bars) => \count($bars), + 'bar' => static fn (array $bars) => \count($bars), ], [new CallbacksObject(), new CallbacksObject()], ['bar' => 2, 'foo' => null], @@ -213,7 +213,7 @@ public static function provideDenormalizeCallbacks(): array ], 'Collect a property' => [ [ - 'bar' => function (array $bars) { + 'bar' => static function (array $bars) { $result = ''; foreach ($bars as $bar) { $result .= $bar->bar; @@ -227,7 +227,7 @@ public static function provideDenormalizeCallbacks(): array ], 'Count a property' => [ [ - 'bar' => fn (array $bars) => \count($bars), + 'bar' => static fn (array $bars) => \count($bars), ], [new CallbacksObject(), new CallbacksObject()], new CallbacksObject(2), diff --git a/tests/Normalizer/Features/CircularReferenceTestTrait.php b/tests/Normalizer/Features/CircularReferenceTestTrait.php index 26514e14..eea962d4 100644 --- a/tests/Normalizer/Features/CircularReferenceTestTrait.php +++ b/tests/Normalizer/Features/CircularReferenceTestTrait.php @@ -35,7 +35,7 @@ public static function provideUnableToNormalizeCircularReference(): array } #[DataProvider('provideUnableToNormalizeCircularReference')] - public function testUnableToNormalizeCircularReference(array $context, int $expectedLimit) + public function testUnableToNormalizeCircularReference(array $context, int $expectedLimit): void { $normalizer = $this->getNormalizerForCircularReference(); @@ -46,7 +46,7 @@ public function testUnableToNormalizeCircularReference(array $context, int $expe $normalizer->normalize($obj, null, $context); } - public function testCircularReferenceHandler() + public function testCircularReferenceHandler(): void { $normalizer = $this->getNormalizerForCircularReference(); diff --git a/tests/Normalizer/Features/ConstructorArgumentsTestTrait.php b/tests/Normalizer/Features/ConstructorArgumentsTestTrait.php index 722c4e88..24c6b5eb 100644 --- a/tests/Normalizer/Features/ConstructorArgumentsTestTrait.php +++ b/tests/Normalizer/Features/ConstructorArgumentsTestTrait.php @@ -20,7 +20,7 @@ trait ConstructorArgumentsTestTrait { abstract protected function getDenormalizerForConstructArguments(): DenormalizerInterface; - public function testDefaultConstructorArguments() + public function testDefaultConstructorArguments(): void { $data = [ 'foo' => 10, @@ -37,7 +37,7 @@ public function testDefaultConstructorArguments() $this->assertEquals(new ConstructorArgumentsObject(10, '', null), $result); } - public function testMetadataAwareNameConvertorWithNotSerializedConstructorParameter() + public function testMetadataAwareNameConvertorWithNotSerializedConstructorParameter(): void { $denormalizer = $this->getDenormalizerForConstructArguments(); @@ -56,7 +56,7 @@ public function testMetadataAwareNameConvertorWithNotSerializedConstructorParame ); } - public function testConstructorWithMissingData() + public function testConstructorWithMissingData(): void { $data = [ 'bar' => 10, @@ -73,7 +73,7 @@ public function testConstructorWithMissingData() } } - public function testExceptionsAreCollectedForConstructorWithMissingData() + public function testExceptionsAreCollectedForConstructorWithMissingData(): void { self::markTestSkipped('Exceptions collection is not supported yet.'); @@ -107,7 +107,7 @@ public function getBar() return $this->bar; } - public function setBar($bar) + public function setBar($bar): void { $this->bar = $bar; } diff --git a/tests/Normalizer/Features/ContextMetadataTestTrait.php b/tests/Normalizer/Features/ContextMetadataTestTrait.php index c689c496..48456cbd 100644 --- a/tests/Normalizer/Features/ContextMetadataTestTrait.php +++ b/tests/Normalizer/Features/ContextMetadataTestTrait.php @@ -33,7 +33,7 @@ trait ContextMetadataTestTrait /** * @dataProvider contextMetadataDummyProvider */ - public function testContextMetadataNormalize(string $contextMetadataDummyClass) + public function testContextMetadataNormalize(string $contextMetadataDummyClass): void { $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor()); @@ -56,7 +56,7 @@ public function testContextMetadataNormalize(string $contextMetadataDummyClass) /** * @dataProvider contextMetadataDummyProvider */ - public function testContextMetadataContextDenormalize(string $contextMetadataDummyClass) + public function testContextMetadataContextDenormalize(string $contextMetadataDummyClass): void { $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor()); @@ -88,7 +88,7 @@ public function contextMetadataDummyProvider(): array ]; } - public function testContextDenormalizeWithNameConverter() + public function testContextDenormalizeWithNameConverter(): void { $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new ObjectNormalizer($classMetadataFactory, new CamelCaseToSnakeCaseNameConverter(), null, new PhpDocExtractor()); diff --git a/tests/Normalizer/Features/GroupsTestTrait.php b/tests/Normalizer/Features/GroupsTestTrait.php index bb6267a1..ffb8e6e3 100644 --- a/tests/Normalizer/Features/GroupsTestTrait.php +++ b/tests/Normalizer/Features/GroupsTestTrait.php @@ -26,7 +26,7 @@ abstract protected function getNormalizerForGroups(): NormalizerInterface; abstract protected function getDenormalizerForGroups(): DenormalizerInterface; - public function testGroupsNormalize() + public function testGroupsNormalize(): void { $normalizer = $this->getNormalizerForGroups(); @@ -52,7 +52,7 @@ public function testGroupsNormalize() ], $normalizer->normalize($obj, null, ['groups' => ['a', 'c']])); } - public function testGroupsDenormalize() + public function testGroupsDenormalize(): void { $normalizer = $this->getDenormalizerForGroups(); @@ -80,7 +80,7 @@ public function testGroupsDenormalize() $this->assertEquals($obj, $normalized); } - public function testNormalizeNoPropertyInGroup() + public function testNormalizeNoPropertyInGroup(): void { $normalizer = $this->getNormalizerForGroups(); diff --git a/tests/Normalizer/Features/IgnoredAttributesTestTrait.php b/tests/Normalizer/Features/IgnoredAttributesTestTrait.php index c4e24602..bb5dd520 100644 --- a/tests/Normalizer/Features/IgnoredAttributesTestTrait.php +++ b/tests/Normalizer/Features/IgnoredAttributesTestTrait.php @@ -25,7 +25,7 @@ abstract protected function getNormalizerForIgnoredAttributes(): NormalizerInter abstract protected function getDenormalizerForIgnoredAttributes(): DenormalizerInterface; - public function testIgnoredAttributesNormalize() + public function testIgnoredAttributesNormalize(): void { $normalizer = $this->getNormalizerForIgnoredAttributes(); @@ -60,7 +60,7 @@ public function testIgnoredAttributesNormalize() ); } - public function testIgnoredAttributesContextDenormalize() + public function testIgnoredAttributesContextDenormalize(): void { $normalizer = $this->getDenormalizerForIgnoredAttributes(); @@ -76,7 +76,7 @@ public function testIgnoredAttributesContextDenormalize() ], ObjectOuter::class, null, $context)); } - public function testIgnoredAttributesContextDenormalizeInherit() + public function testIgnoredAttributesContextDenormalizeInherit(): void { $normalizer = $this->getDenormalizerForIgnoredAttributes(); diff --git a/tests/Normalizer/Features/MaxDepthTestTrait.php b/tests/Normalizer/Features/MaxDepthTestTrait.php index cb166606..df8bbd6b 100644 --- a/tests/Normalizer/Features/MaxDepthTestTrait.php +++ b/tests/Normalizer/Features/MaxDepthTestTrait.php @@ -23,7 +23,7 @@ trait MaxDepthTestTrait { abstract protected function getNormalizerForMaxDepth(): NormalizerInterface; - public function testMaxDepth() + public function testMaxDepth(): void { $normalizer = $this->getNormalizerForMaxDepth(); @@ -62,7 +62,7 @@ public function testMaxDepth() $this->assertEquals($expected, $result); } - public function testMaxDepthHandler() + public function testMaxDepthHandler(): void { self::markTestSkipped('Max depth handler is not supported.'); diff --git a/tests/Normalizer/Features/ObjectDummy.php b/tests/Normalizer/Features/ObjectDummy.php index 1b4b30f5..35f17eff 100644 --- a/tests/Normalizer/Features/ObjectDummy.php +++ b/tests/Normalizer/Features/ObjectDummy.php @@ -32,7 +32,7 @@ public function getFoo() return $this->foo; } - public function setFoo($foo) + public function setFoo($foo): void { $this->foo = $foo; } @@ -42,7 +42,7 @@ public function isBaz() return $this->baz; } - public function setBaz($baz) + public function setBaz($baz): void { $this->baz = $baz; } @@ -57,17 +57,17 @@ public function getCamelCase() return $this->camelCase; } - public function setCamelCase($camelCase) + public function setCamelCase($camelCase): void { $this->camelCase = $camelCase; } - public function otherMethod() + public function otherMethod(): void { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } - public function setObject($object) + public function setObject($object): void { $this->object = $object; } @@ -77,7 +77,7 @@ public function getObject() return $this->object; } - public function setGo($go) + public function setGo($go): void { $this->go = $go; } diff --git a/tests/Normalizer/Features/ObjectOuter.php b/tests/Normalizer/Features/ObjectOuter.php index a4775664..bf9e0c7f 100644 --- a/tests/Normalizer/Features/ObjectOuter.php +++ b/tests/Normalizer/Features/ObjectOuter.php @@ -53,12 +53,12 @@ public function getInner() return $this->inner; } - public function setInner(ObjectInner $inner) + public function setInner(ObjectInner $inner): void { $this->inner = $inner; } - public function setDate(\DateTimeInterface $date) + public function setDate(\DateTimeInterface $date): void { $this->date = $date; } @@ -68,7 +68,7 @@ public function getDate(): ?\DateTime return $this->date; } - public function setInners(array $inners) + public function setInners(array $inners): void { $this->inners = $inners; } diff --git a/tests/Normalizer/Features/ObjectToPopulateTestTrait.php b/tests/Normalizer/Features/ObjectToPopulateTestTrait.php index 8bd7a503..27b2884b 100644 --- a/tests/Normalizer/Features/ObjectToPopulateTestTrait.php +++ b/tests/Normalizer/Features/ObjectToPopulateTestTrait.php @@ -23,7 +23,7 @@ trait ObjectToPopulateTestTrait { abstract protected function getDenormalizerForObjectToPopulate(): DenormalizerInterface; - public function testObjectToPopulate() + public function testObjectToPopulate(): void { $dummy = new ObjectDummy(); $dummy->bar = 'bar'; @@ -42,7 +42,7 @@ public function testObjectToPopulate() $this->assertEquals('bar', $obj->bar); } - public function testObjectToPopulateWithProxy() + public function testObjectToPopulateWithProxy(): void { $proxyDummy = new ProxyDummy(); @@ -54,7 +54,7 @@ public function testObjectToPopulateWithProxy() $this->assertSame('bar', $proxyDummy->getFoo()); } - public function testObjectToPopulateNoMatch() + public function testObjectToPopulateNoMatch(): void { $denormalizer = $this->getDenormalizerForObjectToPopulate(); @@ -76,7 +76,7 @@ public function testObjectToPopulateNoMatch() $this->assertNull($inner->foo); } - public function testDeepObjectToPopulate() + public function testDeepObjectToPopulate(): void { $child = new DeepObjectPopulateChildDummy(); $child->bar = 'bar-old'; diff --git a/tests/Normalizer/Features/SkipNullValuesTestTrait.php b/tests/Normalizer/Features/SkipNullValuesTestTrait.php index d4880bd9..3cf34d59 100644 --- a/tests/Normalizer/Features/SkipNullValuesTestTrait.php +++ b/tests/Normalizer/Features/SkipNullValuesTestTrait.php @@ -23,7 +23,7 @@ trait SkipNullValuesTestTrait { abstract protected function getNormalizerForSkipNullValues(): NormalizerInterface; - public function testSkipNullValues() + public function testSkipNullValues(): void { $dummy = new ObjectDummy(); $dummy->bar = 'present'; diff --git a/tests/Normalizer/Features/SkipUninitializedValuesTestTrait.php b/tests/Normalizer/Features/SkipUninitializedValuesTestTrait.php index abed8a6c..796b8f41 100644 --- a/tests/Normalizer/Features/SkipUninitializedValuesTestTrait.php +++ b/tests/Normalizer/Features/SkipUninitializedValuesTestTrait.php @@ -24,7 +24,7 @@ trait SkipUninitializedValuesTestTrait abstract protected function getNormalizerForSkipUninitializedValues(): NormalizerInterface; #[DataProvider('skipUninitializedValuesFlagProvider')] - public function testSkipUninitializedValues(array $context) + public function testSkipUninitializedValues(array $context): void { self::markTestSkipped('Uninitialized properties are not supported yet'); @@ -50,7 +50,7 @@ public static function skipUninitializedValuesFlagProvider(): iterable yield 'using default context value' => [['groups' => ['foo']]]; } - public function testWithoutSkipUninitializedValues() + public function testWithoutSkipUninitializedValues(): void { $object = new TypedPropertiesObjectWithGetters(); diff --git a/tests/Normalizer/Features/TypeEnforcementNumberObject.php b/tests/Normalizer/Features/TypeEnforcementNumberObject.php index 35c0057d..4783c3fc 100644 --- a/tests/Normalizer/Features/TypeEnforcementNumberObject.php +++ b/tests/Normalizer/Features/TypeEnforcementNumberObject.php @@ -20,7 +20,7 @@ class TypeEnforcementNumberObject */ public $number; - public function setNumber($number) + public function setNumber($number): void { $this->number = $number; } diff --git a/tests/Normalizer/Features/TypeEnforcementTestTrait.php b/tests/Normalizer/Features/TypeEnforcementTestTrait.php index b4b65ad1..b81b3382 100644 --- a/tests/Normalizer/Features/TypeEnforcementTestTrait.php +++ b/tests/Normalizer/Features/TypeEnforcementTestTrait.php @@ -24,7 +24,7 @@ trait TypeEnforcementTestTrait { abstract protected function getDenormalizerForTypeEnforcement(): DenormalizerInterface; - public function testRejectInvalidType() + public function testRejectInvalidType(): void { $denormalizer = $this->getDenormalizerForTypeEnforcement(); @@ -32,7 +32,7 @@ public function testRejectInvalidType() $denormalizer->denormalize(['date' => 'foo'], ObjectOuter::class); } - public function testDoNotRejectInvalidTypeOnDisableTypeEnforcementContextOption() + public function testDoNotRejectInvalidTypeOnDisableTypeEnforcementContextOption(): void { $denormalizer = $this->getDenormalizerForTypeEnforcement(); diff --git a/tests/ObjectMapper/Fixtures/InitializedConstructor/B.php b/tests/ObjectMapper/Fixtures/InitializedConstructor/B.php index 10ad7569..c7c55622 100644 --- a/tests/ObjectMapper/Fixtures/InitializedConstructor/B.php +++ b/tests/ObjectMapper/Fixtures/InitializedConstructor/B.php @@ -22,12 +22,12 @@ public function __construct() $this->tags = []; } - public function addTag($tag) + public function addTag($tag): void { $this->tags[] = $tag; } - public function removeTag($tag) + public function removeTag($tag): void { } } diff --git a/tests/ObjectMapper/ObjectMapperTest.php b/tests/ObjectMapper/ObjectMapperTest.php index b49da15c..443bf614 100644 --- a/tests/ObjectMapper/ObjectMapperTest.php +++ b/tests/ObjectMapper/ObjectMapperTest.php @@ -103,7 +103,7 @@ protected function setUp(): void } #[DataProvider('mapProvider')] - public function testMap($expect, $args, array $deps = []) + public function testMap($expect, $args, array $deps = []): void { $mapper = $this->createObjectMapper(); $mapped = $mapper->map(...$args); @@ -148,28 +148,28 @@ public static function mapProvider(): iterable yield [new MultipleTargetsC(foo: 'bar'), [new MultipleTargetsA()]]; } - public function testHasNothingToMapTo() + public function testHasNothingToMapTo(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage('Mapping target not found for source "class@anonymous".'); $this->createObjectMapper()->map(new class {}); } - public function testHasNothingToMapToWithNamedClass() + public function testHasNothingToMapToWithNamedClass(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage(\sprintf('Mapping target not found for source "%s".', ClassWithoutTarget::class)); $this->createObjectMapper()->map(new ClassWithoutTarget()); } - public function testTargetNotFound() + public function testTargetNotFound(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage(\sprintf('Mapping target class "InexistantClass" does not exist for source "%s".', ClassWithoutTarget::class)); $this->createObjectMapper()->map(new ClassWithoutTarget(), 'InexistantClass'); } - public function testRecursion() + public function testRecursion(): void { $ab = new AB(); $ab->ab = $ab; @@ -179,7 +179,7 @@ public function testRecursion() $this->assertSame($mapped, $mapped->dto); } - public function testDeeperRecursion() + public function testDeeperRecursion(): void { $recursive = new Recursive(); $recursive->name = 'hi'; @@ -192,7 +192,7 @@ public function testDeeperRecursion() $this->assertInstanceOf(RelationDto::class, $mapped->relation); } - public function testMapWithInitializedConstructor() + public function testMapWithInitializedConstructor(): void { $a = new InitializedConstructorA(); $mapper = $this->createObjectMapper(); @@ -201,7 +201,7 @@ public function testMapWithInitializedConstructor() $this->assertEquals($b->tags, ['foo', 'bar']); } - public function testMapReliesOnConstructorsOwnInitialization() + public function testMapReliesOnConstructorsOwnInitialization(): void { $expected = 'bar'; @@ -216,7 +216,7 @@ public function testMapReliesOnConstructorsOwnInitialization() $this->assertEquals($expected, $c->bar); } - public function testMapConstructorArgumentsDifferFromClassFields() + public function testMapConstructorArgumentsDifferFromClassFields(): void { $expected = 'bar'; @@ -231,7 +231,7 @@ public function testMapConstructorArgumentsDifferFromClassFields() $this->assertStringContainsStringIgnoringCase($expected, $actual->barUpperCase); } - public function testMapToWithInstanceHook() + public function testMapToWithInstanceHook(): void { $a = new InstanceCallbackA(); $mapper = $this->createObjectMapper(); @@ -241,7 +241,7 @@ public function testMapToWithInstanceHook() $this->assertSame($b->name, 'test'); } - public function testMapToWithInstanceHookWithArguments() + public function testMapToWithInstanceHookWithArguments(): void { $a = new InstanceCallbackWithArgumentsA(); $mapper = $this->createObjectMapper(); @@ -250,7 +250,7 @@ public function testMapToWithInstanceHookWithArguments() $this->assertSame($a, $b->transformSource); } - public function testMultipleMapProperty() + public function testMultipleMapProperty(): void { $u = new User(email: 'hello@example.com', profile: new UserProfile(firstName: 'soyuka', lastName: 'arakusa')); $mapper = $this->createObjectMapper(); @@ -260,7 +260,7 @@ public function testMultipleMapProperty() $this->assertSame($b->lastName, 'arakusa'); } - public function testServiceLocator() + public function testServiceLocator(): void { $a = new ServiceLocatorA(); $a->foo = 'nok'; @@ -277,7 +277,7 @@ public function testServiceLocator() $this->assertSame($b->bar, 'transformedok'); } - public function testSourceOnly() + public function testSourceOnly(): void { $a = new \stdClass(); $a->name = 'test'; @@ -287,7 +287,7 @@ public function testSourceOnly() $this->assertSame('test', $mapped->mappedName); } - public function testSourceOnlyWithMagicMethods() + public function testSourceOnlyWithMagicMethods(): void { $mapper = $this->createObjectMapper(); $a = new class { @@ -310,7 +310,7 @@ public function __get(string $key): string $this->assertSame('test', $mapped->mappedName); } - public function testTransformToWrongValueType() + public function testTransformToWrongValueType(): void { $this->expectException(MappingTransformException::class); $this->expectExceptionMessage('Cannot map "stdClass" to a non-object target of type "string".'); @@ -319,12 +319,12 @@ public function testTransformToWrongValueType() $u->foo = 'bar'; $metadata = $this->createStub(ObjectMapperMetadataFactoryInterface::class); - $metadata->method('create')->with($u)->willReturn([new Mapping(target: \stdClass::class, transform: fn () => 'str')]); + $metadata->method('create')->with($u)->willReturn([new Mapping(target: \stdClass::class, transform: static fn () => 'str')]); $mapper = new ObjectMapper(metadataFactory: $metadata); $mapper->map($u); } - public function testTransformToWrongObject() + public function testTransformToWrongObject(): void { $this->expectException(MappingException::class); $this->expectExceptionMessage(\sprintf('Expected the mapped object to be an instance of "%s" but got "stdClass".', ClassWithoutTarget::class)); @@ -333,12 +333,12 @@ public function testTransformToWrongObject() $u->foo = 'bar'; $metadata = $this->createStub(ObjectMapperMetadataFactoryInterface::class); - $metadata->method('create')->with($u)->willReturn([new Mapping(target: ClassWithoutTarget::class, transform: fn () => new \stdClass())]); + $metadata->method('create')->with($u)->willReturn([new Mapping(target: ClassWithoutTarget::class, transform: static fn () => new \stdClass())]); $mapper = new ObjectMapper(metadataFactory: $metadata); $mapper->map($u); } - public function testMapTargetToSource() + public function testMapTargetToSource(): void { $a = new MapTargetToSourceA('str'); $mapper = $this->createObjectMapper(); @@ -347,7 +347,7 @@ public function testMapTargetToSource() $this->assertSame('str', $b->target); } - public function testMultipleTargetMapProperty() + public function testMultipleTargetMapProperty(): void { $u = new MultipleTargetPropertyA(); @@ -362,7 +362,7 @@ public function testMultipleTargetMapProperty() $this->assertEquals('foo', $c->doesNotExistInTargetB); } - public function testDefaultValueStdClass() + public function testDefaultValueStdClass(): void { $this->markTestSkipped('This use case is supported by AutoMapper, as we skip non existing properties by default.'); @@ -373,7 +373,7 @@ public function testDefaultValueStdClass() $b = $mapper->map($u, TargetDto::class); } - public function testDefaultValueStdClassWithPropertyInfo() + public function testDefaultValueStdClassWithPropertyInfo(): void { $u = new \stdClass(); $u->id = 'abc'; @@ -385,7 +385,7 @@ public function testDefaultValueStdClassWithPropertyInfo() } #[DataProvider('objectMapperProvider')] - public function testUpdateObjectWithConstructorPromotedProperties(ObjectMapperInterface $mapper) + public function testUpdateObjectWithConstructorPromotedProperties(ObjectMapperInterface $mapper): void { $a = new PromotedConstructorSource(1, 'foo'); $b = new PromotedConstructorTarget(1, 'bar'); @@ -394,7 +394,7 @@ public function testUpdateObjectWithConstructorPromotedProperties(ObjectMapperIn } #[DataProvider('objectMapperProvider')] - public function testUpdateMappedObjectWithAdditionalConstructorPromotedProperties(ObjectMapperInterface $mapper) + public function testUpdateMappedObjectWithAdditionalConstructorPromotedProperties(ObjectMapperInterface $mapper): void { $a = new PromotedConstructorWithMetadataSource(3, 'foo-will-get-updated'); $b = new PromotedConstructorWithMetadataTarget('notOnSourceButRequired', 1, 'bar'); @@ -413,7 +413,7 @@ public static function objectMapperProvider(): iterable yield [new ObjectMapper()]; } - public function testMapInitializesLazyObject() + public function testMapInitializesLazyObject(): void { $lazy = new LazyFoo(); $mapper = $this->createObjectMapper(); @@ -422,10 +422,10 @@ public function testMapInitializesLazyObject() } #[RequiresPhp('>=8.4.0')] - public function testMapInitializesNativePhp84LazyObject() + public function testMapInitializesNativePhp84LazyObject(): void { $initialized = false; - $initializer = function () use (&$initialized) { + $initializer = static function () use (&$initialized) { $initialized = true; $p = new MyProxy(); @@ -443,7 +443,7 @@ public function testMapInitializesNativePhp84LazyObject() $this->assertTrue($initialized); } - public function testDecorateObjectMapper() + public function testDecorateObjectMapper(): void { $this->markTestSkipped('This use case is not supported by AutoMapper.'); @@ -485,7 +485,7 @@ public function map(object $source, object|string|null $target = null): object } #[DataProvider('validPartialInputProvider')] - public function testMapPartially(PartialInput $actual, FinalInput $expected) + public function testMapPartially(PartialInput $actual, FinalInput $expected): void { $mapper = $this->createObjectMapper(); $this->assertEquals($expected, $mapper->map($actual)); @@ -525,7 +525,7 @@ public static function validPartialInputProvider(): iterable yield [$p, $f]; } - public function testMapWithSourceTransform() + public function testMapWithSourceTransform(): void { $source = new SourceEntity(); $source->name = 'test'; @@ -538,7 +538,7 @@ public function testMapWithSourceTransform() $this->assertSame('test', $target->name); } - public function testTransformCollection() + public function testTransformCollection(): void { $u = new TransformCollectionA(); $u->foo = [new TransformCollectionC('a'), new TransformCollectionC('b')]; @@ -550,7 +550,7 @@ public function testTransformCollection() } #[RequiresPhp('>=8.4.0')] - public function testEmbedsAreLazyLoadedByDefault() + public function testEmbedsAreLazyLoadedByDefault(): void { $this->markTestSkipped('Lazy Loading is not enable by default and works differently.'); @@ -569,7 +569,7 @@ public function testEmbedsAreLazyLoadedByDefault() $this->assertFalse($refl->isUninitializedLazyObject($target->user)); } - public function testSkipLazyGhostWithClassTransform() + public function testSkipLazyGhostWithClassTransform(): void { $mapper = $this->createObjectMapper(); @@ -584,7 +584,7 @@ public function testSkipLazyGhostWithClassTransform() $this->assertSame('test', $result->relation->name); } - public function testMapEmbeddedProperties() + public function testMapEmbeddedProperties(): void { $dto = new UserDto( userAddressZipcode: '12345', @@ -602,7 +602,7 @@ public function testMapEmbeddedProperties() $this->assertSame('Test City', $user->address->city); } - public function testBugReportLazyLoadingPromotedReadonlyProperty() + public function testBugReportLazyLoadingPromotedReadonlyProperty(): void { $source = new ReadOnlyPromotedPropertyA( b: new ReadOnlyPromotedPropertyB( diff --git a/tests/Transformer/BuiltinTransformerTest.php b/tests/Transformer/BuiltinTransformerTest.php index 84d868b4..fb6aeecc 100644 --- a/tests/Transformer/BuiltinTransformerTest.php +++ b/tests/Transformer/BuiltinTransformerTest.php @@ -261,7 +261,7 @@ public function testIterableToArray(): void { $transformer = new BuiltinTransformer(Type::builtin('iterable'), Type::builtin('array')); - $closure = function () { + $closure = static function () { yield 1; yield 2; }; @@ -283,7 +283,7 @@ public function testToUnknowCast(): void { $transformer = new BuiltinTransformer(Type::callable(), Type::string()); - $output = $this->evalTransformer($transformer, function ($test) { + $output = $this->evalTransformer($transformer, static function ($test) { return $test; });