Created
May 3, 2020 19:49
-
-
Save vudaltsov/db7fb0832a5e2d23fe530f02c0eefd17 to your computer and use it in GitHub Desktop.
Symfony <5.1 PHP 7.4 property types support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\PropertyInfo; | |
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface; | |
use Symfony\Component\PropertyInfo\Type; | |
final class Php74ReflectionExtractor implements PropertyTypeExtractorInterface | |
{ | |
public function getTypes(string $class, string $property, array $context = []): ?array | |
{ | |
if (\PHP_VERSION_ID < 70400) { | |
return null; | |
} | |
try { | |
$reflectionProperty = new \ReflectionProperty($class, $property); | |
} catch (\ReflectionException $e) { | |
return null; | |
} | |
/** @var \ReflectionType|null $reflectionType */ | |
$reflectionType = $reflectionProperty->getType(); | |
if (null === $reflectionType) { | |
return null; | |
} | |
$phpTypeOrClass = $reflectionType->getName(); | |
$nullable = $reflectionType->allowsNull(); | |
if (Type::BUILTIN_TYPE_ARRAY === $phpTypeOrClass) { | |
if ($reflectionProperty->getDocComment()) { | |
return null; | |
} | |
return [new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true)]; | |
} | |
if ('void' === $phpTypeOrClass) { | |
return [new Type(Type::BUILTIN_TYPE_NULL, $nullable)]; | |
} | |
if ($reflectionType->isBuiltin()) { | |
return [new Type($phpTypeOrClass, $nullable)]; | |
} | |
$class = $this->resolveClass($phpTypeOrClass, $reflectionProperty->getDeclaringClass()); | |
return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $class)]; | |
} | |
private function resolveClass(string $name, \ReflectionClass $declaringClass): string | |
{ | |
if ('self' === $lcName = strtolower($name)) { | |
return $declaringClass->name; | |
} | |
if ('parent' === $lcName && $parent = $declaringClass->getParentClass()) { | |
return $parent->name; | |
} | |
return $name; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
HappyJob\PropertyInfo\Php74ReflectionExtractor: | |
tags: | |
- property_info.type_extractor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment