Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(types): try to get types from read accessor / write mutator first #77

Merged
merged 4 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/Extractor/FromSourceMappingExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace AutoMapper\Extractor;

use AutoMapper\Configuration;
use AutoMapper\Metadata\SourcePropertyMetadata;
use AutoMapper\Metadata\TargetPropertyMetadata;
use AutoMapper\Metadata\TypesMatching;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
Expand All @@ -31,10 +33,12 @@ public function __construct(
parent::__construct($configuration, $propertyInfoExtractor, $readInfoExtractor, $writeInfoExtractor);
}

public function getTypes(string $source, string $sourceProperty, string $target, string $targetProperty): TypesMatching
public function getTypes(string $source, SourcePropertyMetadata $sourceProperty, string $target, TargetPropertyMetadata $targetProperty): TypesMatching
{
$types = new TypesMatching();
$sourceTypes = $this->propertyInfoExtractor->getTypes($source, $sourceProperty) ?? [new Type(Type::BUILTIN_TYPE_NULL)];
$sourceTypes = $this->propertyInfoExtractor->getTypes($source, $sourceProperty->name, [
ReadWriteTypeExtractor::READ_ACCESSOR => $sourceProperty->accessor,
]) ?? [new Type(Type::BUILTIN_TYPE_NULL)];

foreach ($sourceTypes as $type) {
$targetType = $this->transformType($target, $type);
Expand Down
8 changes: 6 additions & 2 deletions src/Extractor/FromTargetMappingExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace AutoMapper\Extractor;

use AutoMapper\Configuration;
use AutoMapper\Metadata\SourcePropertyMetadata;
use AutoMapper\Metadata\TargetPropertyMetadata;
use AutoMapper\Metadata\TypesMatching;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
Expand All @@ -31,10 +33,12 @@ public function __construct(
parent::__construct($configuration, $propertyInfoExtractor, $readInfoExtractor, $writeInfoExtractor);
}

public function getTypes(string $source, string $sourceProperty, string $target, string $targetProperty): TypesMatching
public function getTypes(string $source, SourcePropertyMetadata $sourceProperty, string $target, TargetPropertyMetadata $targetProperty): TypesMatching
{
$types = new TypesMatching();
$targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty) ?? [];
$targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty->name, [
ReadWriteTypeExtractor::WRITE_MUTATOR => $targetProperty->writeMutator,
]) ?? [];

foreach ($targetTypes as $type) {
$sourceType = $this->transformType($source, $type);
Expand Down
144 changes: 144 additions & 0 deletions src/Extractor/GetTypeTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Extractor;

use phpDocumentor\Reflection\Types\ContextFactory;
use PHPStan\PhpDocParser\Ast\PhpDoc\InvalidTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
use Symfony\Component\PropertyInfo\PhpStan\NameScopeFactory;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\PropertyInfo\Util\PhpStanTypeHelper;

/**
* @internal
*/
trait GetTypeTrait
{
/**
* @return Type[]
*/
private function extractFromDocBlock(string|false|null $rawDocNode, string $class, string $declaringClass, string $property, string $tagName): ?array
{
if (!$rawDocNode) {
return null;
}

if (!class_exists(PhpDocParser::class)) {
return null;
}

if (!class_exists(ContextFactory::class)) {
return null;
}

static $phpDocParser = new PhpDocParser(new TypeParser(new ConstExprParser()), new ConstExprParser());
static $lexer = new Lexer();
static $nameScopeFactory = new NameScopeFactory();
static $phpStanTypeHelper = new PhpStanTypeHelper();

$tokens = new TokenIterator($lexer->tokenize($rawDocNode));
$docNode = $phpDocParser->parse($tokens);
$tokens->consumeTokenType(Lexer::TOKEN_END);
$nameScope = $nameScopeFactory->create($class, $declaringClass);

$types = [];

foreach ($docNode->getTagsByName($tagName) as $tagDocNode) {
if ($tagDocNode->value instanceof InvalidTagValueNode) {
continue;
}

if (
$tagDocNode->value instanceof ParamTagValueNode
&& $tagName !== '@param'
&& $tagDocNode->value->parameterName !== '$' . $property
) {
continue;
}

foreach ($phpStanTypeHelper->getTypes($tagDocNode->value, $nameScope) as $type) {
switch ($type->getClassName()) {
case 'self':
case 'static':
$resolvedClass = $class;
break;

case 'parent':
if (false !== $resolvedClass = $parentClass ??= get_parent_class($class)) {
break;
}

// no break
default:
$types[] = $type;
continue 2;
}

$types[] = new Type(Type::BUILTIN_TYPE_OBJECT, $type->isNullable(), $resolvedClass, $type->isCollection(), $type->getCollectionKeyTypes(), $type->getCollectionValueTypes());
}
}

if (!isset($types[0])) {
return null;
}

return $types;
}

/**
* @param \ReflectionClass<object> $declaringClass
*
* @return Type[]
*/
private function extractFromReflectionType(\ReflectionType $reflectionType, \ReflectionClass $declaringClass): array
{
$types = [];
$nullable = $reflectionType->allowsNull();

foreach (($reflectionType instanceof \ReflectionUnionType || $reflectionType instanceof \ReflectionIntersectionType) ? $reflectionType->getTypes() : [$reflectionType] as $type) {
if (!$type instanceof \ReflectionNamedType) {
// Nested composite types are not supported yet.
return [];
}

$phpTypeOrClass = $type->getName();
if ('null' === $phpTypeOrClass || 'mixed' === $phpTypeOrClass || 'never' === $phpTypeOrClass) {
continue;
}

if (Type::BUILTIN_TYPE_ARRAY === $phpTypeOrClass) {
$types[] = new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true);
} elseif ('void' === $phpTypeOrClass) {
$types[] = new Type(Type::BUILTIN_TYPE_NULL, $nullable);
} elseif ($type->isBuiltin()) {
$types[] = new Type($phpTypeOrClass, $nullable);
} else {
$types[] = new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $this->resolveTypeName($phpTypeOrClass, $declaringClass));
}
}

return $types;
}

/**
* @param \ReflectionClass<object> $declaringClass
*/
private function resolveTypeName(string $name, \ReflectionClass $declaringClass): string
{
if ('self' === $lcName = strtolower($name)) {
return $declaringClass->name;
}
if ('parent' === $lcName && $parent = $declaringClass->getParentClass()) {
return $parent->name;
}

return $name;
}
}
4 changes: 3 additions & 1 deletion src/Extractor/MappingExtractorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace AutoMapper\Extractor;

use AutoMapper\Metadata\SourcePropertyMetadata;
use AutoMapper\Metadata\TargetPropertyMetadata;
use AutoMapper\Metadata\TypesMatching;

/**
Expand All @@ -22,7 +24,7 @@ interface MappingExtractorInterface
*/
public function getProperties(string $class): iterable;

public function getTypes(string $source, string $sourceProperty, string $target, string $targetProperty): TypesMatching;
public function getTypes(string $source, SourcePropertyMetadata $sourceProperty, string $target, TargetPropertyMetadata $targetProperty): TypesMatching;

public function getDateTimeFormat(string $class, string $property): string;

Expand Down
75 changes: 75 additions & 0 deletions src/Extractor/ReadAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PhpParser\Node\Param;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
use Symfony\Component\PropertyInfo\Type;

/**
* Read accessor tell how to read from a property.
Expand All @@ -22,6 +23,8 @@
*/
final class ReadAccessor
{
use GetTypeTrait;

public const TYPE_METHOD = 1;
public const TYPE_PROPERTY = 2;
public const TYPE_ARRAY_DIMENSION = 3;
Expand Down Expand Up @@ -279,4 +282,76 @@ public function getExtractIsNullCallback(string $className): ?Expr
new Arg(new Scalar\String_($className)),
]);
}

/**
* @return Type[]|null
*/
public function getTypes(string $class): ?array
{
if (self::TYPE_METHOD === $this->type && class_exists($class)) {
try {
$reflectionMethod = new \ReflectionMethod($class, $this->accessor);

if ($types = $this->extractFromDocBlock(
$reflectionMethod->getDocComment(),
$class,
$reflectionMethod->getDeclaringClass()->getName(),
$this->accessor,
'@return'
)) {
return $types;
}

$reflectionReturnType = $reflectionMethod->getReturnType();

if ($reflectionReturnType === null) {
return null;
}

return $this->extractFromReflectionType($reflectionReturnType, $reflectionMethod->getDeclaringClass());
} catch (\ReflectionException $e) {
return null;
}
}

if (self::TYPE_PROPERTY === $this->type && class_exists($class)) {
try {
$reflectionProperty = new \ReflectionProperty($class, $this->accessor);

if ($reflectionProperty->isPromoted()) {
if ($types = $this->extractFromDocBlock(
$reflectionProperty->getDeclaringClass()->getConstructor()?->getDocComment(),
$class,
$reflectionProperty->getDeclaringClass()->getName(),
$this->accessor,
'@param'
)) {
return $types;
}
}

if ($types = $this->extractFromDocBlock(
$reflectionProperty->getDocComment(),
$class,
$reflectionProperty->getDeclaringClass()->getName(),
$this->accessor,
'@var'
)) {
return $types;
}

$reflectionType = $reflectionProperty->getType();

if ($reflectionType === null) {
return null;
}

return $this->extractFromReflectionType($reflectionType, $reflectionProperty->getDeclaringClass());
} catch (\ReflectionException $e) {
return null;
}
}

return null;
}
}
32 changes: 32 additions & 0 deletions src/Extractor/ReadWriteTypeExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Extractor;

use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;

/**
* @internal
*/
final readonly class ReadWriteTypeExtractor implements PropertyTypeExtractorInterface
{
public const READ_ACCESSOR = 'read_accessor';
public const WRITE_MUTATOR = 'write_mutator';

/**
* @param array<string, mixed> $context
*/
public function getTypes(string $class, string $property, array $context = []): ?array
{
if (($accessor = $context[self::READ_ACCESSOR] ?? false) && $accessor instanceof ReadAccessor) {
return $accessor->getTypes($class);
}

if (($mutator = $context[self::WRITE_MUTATOR] ?? false) && $mutator instanceof WriteMutator) {
return $mutator->getTypes($class);
}

return null;
}
}
8 changes: 5 additions & 3 deletions src/Extractor/SourceTargetMappingExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace AutoMapper\Extractor;

use AutoMapper\Metadata\SourcePropertyMetadata;
use AutoMapper\Metadata\TargetPropertyMetadata;
use AutoMapper\Metadata\TypesMatching;

/**
Expand All @@ -15,10 +17,10 @@
*/
class SourceTargetMappingExtractor extends MappingExtractor
{
public function getTypes(string $source, string $sourceProperty, string $target, string $targetProperty): TypesMatching
public function getTypes(string $source, SourcePropertyMetadata $sourceProperty, string $target, TargetPropertyMetadata $targetProperty): TypesMatching
{
$sourceTypes = $this->propertyInfoExtractor->getTypes($source, $sourceProperty) ?? [];
$targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty) ?? [];
$sourceTypes = $this->propertyInfoExtractor->getTypes($source, $sourceProperty->name, [ReadWriteTypeExtractor::READ_ACCESSOR => $sourceProperty->accessor]) ?? [];
$targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty->name, [ReadWriteTypeExtractor::WRITE_MUTATOR => $targetProperty->writeMutator]) ?? [];

return TypesMatching::fromSourceAndTargetTypes($sourceTypes, $targetTypes);
}
Expand Down
Loading
Loading