|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Overblog\GraphQLBundle\Config\Parser\MetadataParser\TypeGuesser; |
|
6
|
|
|
|
|
7
|
|
|
use ReflectionClass; |
|
8
|
|
|
use ReflectionMethod; |
|
9
|
|
|
use ReflectionNamedType; |
|
10
|
|
|
use ReflectionParameter; |
|
11
|
|
|
use ReflectionProperty; |
|
12
|
|
|
use Reflector; |
|
13
|
|
|
|
|
14
|
|
|
class TypeHintTypeGuesser extends PhpTypeGuesser |
|
15
|
|
|
{ |
|
16
|
|
|
public function getName(): string |
|
17
|
|
|
{ |
|
18
|
|
|
return 'Type Hint'; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function supports(Reflector $reflector): bool |
|
22
|
|
|
{ |
|
23
|
|
|
return $reflector instanceof ReflectionProperty || $reflector instanceof ReflectionParameter || $reflector instanceof ReflectionMethod; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param ReflectionProperty|ReflectionParameter|ReflectionMethod $reflector |
|
28
|
|
|
*/ |
|
29
|
|
|
public function guessType(ReflectionClass $reflectionClass, Reflector $reflector, array $filterGraphQLTypes = []): ?string |
|
30
|
|
|
{ |
|
31
|
|
|
$type = null; |
|
32
|
|
|
$hasDefaultValue = false; |
|
33
|
|
|
|
|
34
|
|
|
switch (true) { |
|
35
|
|
|
case $reflector instanceof ReflectionParameter: |
|
36
|
|
|
/** @var ReflectionParameter $reflector */ |
|
37
|
|
|
$hasDefaultValue = $reflector->isDefaultValueAvailable(); |
|
38
|
|
|
// no break |
|
39
|
|
|
case $reflector instanceof ReflectionProperty: |
|
40
|
|
|
/** @var ReflectionProperty $reflector */ |
|
41
|
|
|
$type = $reflector->hasType() ? $reflector->getType() : null; |
|
42
|
|
|
|
|
43
|
|
|
break; |
|
44
|
|
|
case $reflector instanceof ReflectionMethod: |
|
45
|
|
|
/** @var ReflectionMethod $reflector */ |
|
46
|
|
|
$type = $reflector->hasReturnType() ? $reflector->getReturnType() : null; |
|
47
|
|
|
break; |
|
48
|
|
|
} |
|
49
|
|
|
/** @var ReflectionNamedType|null $type */ |
|
50
|
|
|
if (!$type) { |
|
51
|
|
|
throw new TypeGuessingException('No type-hint'); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$sType = $type->getName(); |
|
55
|
|
|
if ($type->isBuiltin()) { |
|
56
|
|
|
$gqlType = $this->resolveTypeFromPhpType($sType); |
|
57
|
|
|
if (null === $gqlType) { |
|
58
|
|
|
throw new TypeGuessingException(sprintf('No corresponding GraphQL type found for builtin type "%s"', $sType)); |
|
59
|
|
|
} |
|
60
|
|
|
} else { |
|
61
|
|
|
$gqlType = $this->map->resolveType($sType, $filterGraphQLTypes); |
|
62
|
|
|
if (null === $gqlType) { |
|
63
|
|
|
throw new TypeGuessingException(sprintf('No corresponding GraphQL %s found for class "%s"', $filterGraphQLTypes ? implode(',', $filterGraphQLTypes) : 'object', $sType)); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
$nullable = $hasDefaultValue || $type->allowsNull(); |
|
67
|
|
|
|
|
68
|
|
|
return sprintf('%s%s', $gqlType, $nullable ? '' : '!'); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|