Skip to content

Instantly share code, notes, and snippets.

@vudaltsov
Created May 3, 2020 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vudaltsov/db7fb0832a5e2d23fe530f02c0eefd17 to your computer and use it in GitHub Desktop.
Save vudaltsov/db7fb0832a5e2d23fe530f02c0eefd17 to your computer and use it in GitHub Desktop.
Symfony <5.1 PHP 7.4 property types support
<?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;
}
}
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