10
10
use function is_callable ;
11
11
use function is_object ;
12
12
use function str_replace ;
13
- use function ucwords ;
14
13
15
14
class FieldResolver
16
15
{
16
+ /**
17
+ * Allowed method prefixes
18
+ */
19
+ private const PREFIXES = ['get ' , 'is ' , 'has ' , '' ];
20
+
17
21
/**
18
22
* @param mixed $parentValue
19
23
* @param mixed $args
@@ -24,7 +28,7 @@ class FieldResolver
24
28
public function __invoke ($ parentValue , $ args , $ context , ResolveInfo $ info )
25
29
{
26
30
$ fieldName = $ info ->fieldName ;
27
- $ value = self ::valueFromObjectOrArray ($ parentValue , $ fieldName );
31
+ $ value = static ::valueFromObjectOrArray ($ parentValue , $ fieldName );
28
32
29
33
return $ value instanceof Closure ? $ value ($ parentValue , $ args , $ context , $ info ) : $ value ;
30
34
}
@@ -36,28 +40,22 @@ public function __invoke($parentValue, $args, $context, ResolveInfo $info)
36
40
*/
37
41
public static function valueFromObjectOrArray ($ objectOrArray , string $ fieldName )
38
42
{
39
- $ value = null ;
40
43
if (is_array ($ objectOrArray ) && isset ($ objectOrArray [$ fieldName ])) {
41
- $ value = $ objectOrArray [$ fieldName ];
42
- } elseif (is_object ($ objectOrArray )) {
43
- if (null !== $ getter = self ::guessObjectMethod ($ objectOrArray , $ fieldName , 'get ' )) {
44
- $ value = $ objectOrArray ->$ getter ();
45
- } elseif (null !== $ getter = self ::guessObjectMethod ($ objectOrArray , $ fieldName , 'is ' )) {
46
- $ value = $ objectOrArray ->$ getter ();
47
- } elseif (null !== $ getter = self ::guessObjectMethod ($ objectOrArray , $ fieldName , '' )) {
48
- $ value = $ objectOrArray ->$ getter ();
49
- } elseif (isset ($ objectOrArray ->$ fieldName )) {
50
- $ value = $ objectOrArray ->$ fieldName ;
51
- }
44
+ return $ objectOrArray [$ fieldName ];
52
45
}
53
46
54
- return $ value ;
55
- }
47
+ if (is_object ($ objectOrArray )) {
48
+ foreach (static ::PREFIXES as $ prefix ) {
49
+ $ method = $ prefix .str_replace ('_ ' , '' , $ fieldName );
56
50
57
- private static function guessObjectMethod (object $ object , string $ fieldName , string $ prefix ): ?string
58
- {
59
- if (is_callable ([$ object , $ method = $ prefix .str_replace (' ' , '' , ucwords (str_replace ('_ ' , ' ' , $ fieldName )))])) {
60
- return $ method ;
51
+ if (is_callable ([$ objectOrArray , $ method ])) {
52
+ return $ objectOrArray ->$ method ();
53
+ }
54
+ }
55
+
56
+ if (isset ($ objectOrArray ->$ fieldName )) {
57
+ return $ objectOrArray ->$ fieldName ;
58
+ }
61
59
}
62
60
63
61
return null ;
0 commit comments