|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace GraphQL\Doctrine; |
|
6
|
|
|
|
|
7
|
|
|
use ArrayAccess; |
|
8
|
|
|
use Closure; |
|
9
|
|
|
use GraphQL\Type\Definition\ResolveInfo; |
|
10
|
|
|
use ReflectionClass; |
|
11
|
|
|
use ReflectionMethod; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* A field resolver that will allow access to public properties and getter. |
|
15
|
|
|
* Arguments, if any, will be forwarded as is to the method. |
|
16
|
|
|
*/ |
|
17
|
|
|
class DefaultFieldResolver |
|
18
|
|
|
{ |
|
19
|
|
|
public function __invoke($source, $args, $context, ResolveInfo $info) |
|
20
|
|
|
{ |
|
21
|
|
|
$fieldName = $info->fieldName; |
|
22
|
|
|
$property = null; |
|
23
|
|
|
|
|
24
|
|
|
if (is_object($source)) { |
|
25
|
|
|
$property = $this->resolveObject($source, $args, $fieldName); |
|
26
|
|
|
} elseif (is_array($source) || $source instanceof ArrayAccess) { |
|
27
|
|
|
$property = $this->resolveArray($source, $fieldName); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return $property instanceof Closure ? $property($source, $args, $context) : $property; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Resolve for an object |
|
35
|
|
|
* @param mixed $source |
|
36
|
|
|
* @param mixed $args |
|
37
|
|
|
* @param string $fieldName |
|
38
|
|
|
* @return mixed |
|
39
|
|
|
*/ |
|
40
|
|
|
private function resolveObject($source, $args, string $fieldName) |
|
41
|
|
|
{ |
|
42
|
|
|
$class = new ReflectionClass($source); |
|
43
|
|
|
$getter = $this->getGetter($fieldName); |
|
44
|
|
|
|
|
45
|
|
|
if ($class->hasMethod($getter) && $class->getMethod($getter)->getModifiers() & ReflectionMethod::IS_PUBLIC) { |
|
46
|
|
|
$args = (array) $args; |
|
47
|
|
|
|
|
48
|
|
|
return $source->$getter(...$args); |
|
49
|
|
|
} elseif (isset($source->{$fieldName})) { |
|
50
|
|
|
return $source->{$fieldName}; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return null; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Resolve for an array |
|
58
|
|
|
* @param mixed $source |
|
59
|
|
|
* @param string $fieldName |
|
60
|
|
|
* @return mixed |
|
61
|
|
|
*/ |
|
62
|
|
|
private function resolveArray($source, string $fieldName) |
|
63
|
|
|
{ |
|
64
|
|
|
return $source[$fieldName] ?? null; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* If not isser, make it a getter |
|
69
|
|
|
* @param string $fieldName |
|
70
|
|
|
* @return string |
|
71
|
|
|
*/ |
|
72
|
|
|
private function getGetter(string $fieldName): string |
|
73
|
|
|
{ |
|
74
|
|
|
if (preg_match('~^(is|has)[A-Z]~', $fieldName)) { |
|
75
|
|
|
return $fieldName; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return 'get' . ucfirst($fieldName); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|