1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Overblog\GraphQLBundle\Resolver; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use GraphQL\Type\Definition\ResolveInfo; |
9
|
|
|
use function is_array; |
10
|
|
|
use function is_callable; |
11
|
|
|
use function is_object; |
12
|
|
|
use function str_replace; |
13
|
|
|
|
14
|
|
|
class FieldResolver |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Allowed method prefixes |
18
|
|
|
*/ |
19
|
|
|
private const PREFIXES = ['get', 'is', 'has', '']; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param mixed $parentValue |
23
|
|
|
* @param mixed $args |
24
|
44 |
|
* @param mixed $context |
25
|
|
|
* |
26
|
44 |
|
* @return mixed|null |
27
|
44 |
|
*/ |
28
|
|
|
public function __invoke($parentValue, $args, $context, ResolveInfo $info) |
29
|
44 |
|
{ |
30
|
|
|
$fieldName = $info->fieldName; |
31
|
|
|
$value = static::valueFromObjectOrArray($parentValue, $fieldName); |
32
|
|
|
|
33
|
|
|
return $value instanceof Closure ? $value($parentValue, $args, $context, $info) : $value; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
45 |
|
* @param object|array $objectOrArray |
38
|
|
|
* |
39
|
45 |
|
* @return mixed|null |
40
|
45 |
|
*/ |
41
|
35 |
|
public static function valueFromObjectOrArray($objectOrArray, string $fieldName) |
42
|
24 |
|
{ |
43
|
22 |
|
if (is_array($objectOrArray) && isset($objectOrArray[$fieldName])) { |
44
|
17 |
|
return $objectOrArray[$fieldName]; |
45
|
5 |
|
} |
46
|
1 |
|
|
47
|
4 |
|
if (is_object($objectOrArray)) { |
48
|
1 |
|
foreach (static::PREFIXES as $prefix) { |
49
|
3 |
|
$method = $prefix.str_replace('_', '', $fieldName); |
50
|
2 |
|
|
51
|
|
|
if (is_callable([$objectOrArray, $method])) { |
52
|
|
|
return $objectOrArray->$method(); |
53
|
|
|
} |
54
|
45 |
|
} |
55
|
|
|
|
56
|
|
|
if (isset($objectOrArray->$fieldName)) { |
57
|
22 |
|
return $objectOrArray->$fieldName; |
58
|
|
|
} |
59
|
22 |
|
} |
60
|
19 |
|
|
61
|
|
|
return null; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|