4
4
5
5
namespace Knp \DictionaryBundle \ValueTransformer ;
6
6
7
+ use Exception ;
7
8
use Knp \DictionaryBundle \ValueTransformer ;
8
9
use ReflectionClass ;
9
10
10
11
final class Constant implements ValueTransformer
11
12
{
12
- private string $ pattern = '/^(?P<class>.*)::(?P<constant>.*)$/ ' ;
13
+ private const PATTERN = '/^(?P<class>.*)::(?P<constant>.*)$/ ' ;
13
14
14
15
public function supports ($ value ): bool
15
16
{
@@ -19,7 +20,7 @@ public function supports($value): bool
19
20
20
21
$ matches = [];
21
22
22
- if (0 === preg_match ( $ this ->pattern , $ value, $ matches )) {
23
+ if (null === $ matches = $ this ->extract ( $ value )) {
23
24
return false ;
24
25
}
25
26
@@ -36,12 +37,27 @@ public function supports($value): bool
36
37
37
38
public function transform ($ value )
38
39
{
39
- $ matches = [];
40
-
41
- preg_match ( $ this -> pattern , $ value , $ matches );
40
+ if ( null === $ matches = $ this -> extract ( $ value )) {
41
+ throw new Exception ( " Unable to resolve constant { $ value } . " );
42
+ }
42
43
43
44
return (new ReflectionClass ($ matches ['class ' ]))
44
45
->getConstant ($ matches ['constant ' ])
45
46
;
46
47
}
48
+
49
+ /**
50
+ * @return ?array{class: class-string, constant: string}
51
+ */
52
+ private function extract (string $ value ): ?array
53
+ {
54
+ if (preg_match (self ::PATTERN , $ value , $ matches )) {
55
+ /**
56
+ * @var array{class: class-string, constant: string} $matches
57
+ */
58
+ return $ matches ;
59
+ }
60
+
61
+ return null ;
62
+ }
47
63
}
0 commit comments