|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SimPod\GraphQL\Utils; |
| 6 | + |
| 7 | +use Closure; |
| 8 | +use GraphQL\Type\Definition\ResolveInfo; |
| 9 | +use Nette\Utils\Strings; |
| 10 | +use function is_array; |
| 11 | +use function is_object; |
| 12 | +use function method_exists; |
| 13 | + |
| 14 | +class DefaultFieldResolver |
| 15 | +{ |
| 16 | + private const METHOD_PREFIX_GET = 'get'; |
| 17 | + private const METHOD_PREFIX_IS = 'is'; |
| 18 | + private const METHOD_PREFIX_HAS = 'has'; |
| 19 | + |
| 20 | + /** |
| 21 | + * @param mixed $source |
| 22 | + * @param mixed[] $arguments |
| 23 | + * @param mixed $context |
| 24 | + * |
| 25 | + * @return mixed|null |
| 26 | + */ |
| 27 | + public static function resolve($source, array $arguments, $context, ResolveInfo $info) |
| 28 | + { |
| 29 | + $fieldName = $info->fieldName; |
| 30 | + $resolvedValue = null; |
| 31 | + |
| 32 | + if (is_array($source) && isset($source[$fieldName])) { |
| 33 | + $resolvedValue = $source[$fieldName]; |
| 34 | + } |
| 35 | + if (is_object($source)) { |
| 36 | + if (isset($source->$fieldName)) { |
| 37 | + $resolvedValue = $source->$fieldName; |
| 38 | + } |
| 39 | + foreach ([self::METHOD_PREFIX_GET, self::METHOD_PREFIX_IS, self::METHOD_PREFIX_HAS] as $getterPrefix) { |
| 40 | + $getterName = $getterPrefix . Strings::firstUpper($fieldName); |
| 41 | + if (! method_exists($source, $getterName)) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + $resolvedValue = $source->$getterName(); |
| 46 | + } |
| 47 | + if (method_exists($source, $fieldName)) { |
| 48 | + $resolvedValue = $source->$fieldName(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return $resolvedValue instanceof Closure |
| 53 | + ? $resolvedValue($source, $arguments, $context) |
| 54 | + : $resolvedValue; |
| 55 | + } |
| 56 | +} |
0 commit comments