-
-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathEnumFormTypeGuesser.php
More file actions
78 lines (64 loc) · 2.17 KB
/
EnumFormTypeGuesser.php
File metadata and controls
78 lines (64 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Form\Guess\TypeGuess;
use Symfony\Component\Form\Guess\ValueGuess;
final class EnumFormTypeGuesser implements FormTypeGuesserInterface
{
/**
* @var array<string, array<string, string|false>>
*/
private array $cache = [];
public function guessType(string $class, string $property): ?TypeGuess
{
if (!($enum = $this->getPropertyType($class, $property))) {
return null;
}
return new TypeGuess(EnumType::class, ['class' => ltrim($enum, '?')], Guess::HIGH_CONFIDENCE);
}
public function guessRequired(string $class, string $property): ?ValueGuess
{
if (!($enum = $this->getPropertyType($class, $property))) {
return null;
}
return new ValueGuess('?' !== $enum[0], Guess::HIGH_CONFIDENCE);
}
public function guessMaxLength(string $class, string $property): ?ValueGuess
{
return null;
}
public function guessPattern(string $class, string $property): ?ValueGuess
{
return null;
}
private function getPropertyType(string $class, string $property): string|false
{
if (isset($this->cache[$class][$property])) {
return $this->cache[$class][$property];
}
try {
$propertyReflection = new \ReflectionProperty($class, $property);
} catch (\ReflectionException) {
return $this->cache[$class][$property] = false;
}
$type = $propertyReflection->getType();
if (!$type instanceof \ReflectionNamedType || !enum_exists($type->getName())) {
$enum = false;
} else {
$enum = $type->getName();
if ($type->allowsNull()) {
$enum = '?'.$enum;
}
}
return $this->cache[$class][$property] = $enum;
}
}