Completed
Push — master ( 895aee...c5d013 )
by Arthur
8s
created

PropertyGuesser::getAccessor()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.439
cc 5
eloc 17
nc 12
nop 2
1
<?php
2
namespace Arthem\GraphQLMapper\Mapping\Guesser;
3
4
use Arthem\GraphQLMapper\Mapping\Context\FieldContext;
5
use Arthem\GraphQLMapper\Mapping\Guesser\Guess\Guess;
6
use Arthem\GraphQLMapper\Mapping\Type;
7
use Arthem\GraphQLMapper\Utils\StringHelper;
8
9
class PropertyGuesser implements FieldResolveGuesserInterface
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14
    public function guessFieldResolveConfig(FieldContext $fieldContext)
15
    {
16
        /** @var Type $type */
17
        $type = $fieldContext->getContainer();
18
19
        if (!empty($type->getModel())) {
20
            $className = $type->getModel();
21
            if (null !== $accessor = $this->getAccessor($className, $fieldContext)) {
22
                return new ResolveConfigGuess([
23
                    'method'  => $accessor,
24
                    'handler' => 'property',
25
                ], Guess::HIGH_CONFIDENCE);
26
            }
27
        }
28
    }
29
30
    /**
31
     * @param string       $className
32
     * @param FieldContext $fieldContext
33
     * @return string|null
34
     */
35
    private function getAccessor($className, FieldContext $fieldContext)
36
    {
37
        $field = $fieldContext->getField();
38
39
        $class = new \ReflectionClass($className);
40
41
        $property  = $field->getProperty() ?: $field->getName();
42
        $camelName = StringHelper::camelize($property);
43
44
        $getter    = 'get' . $camelName;
45
        $getsetter = lcfirst($camelName);
46
        $isser     = 'is' . $camelName;
47
        $hasser    = 'has' . $camelName;
48
        $test      = [$getter, $getsetter, $isser, $hasser];
49
50
        $reflMethods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
51
        $methods     = [];
52
        foreach ($reflMethods as $reflMethod) {
53
            $methods[$reflMethod->getName()] = true;
54
        }
55
        foreach ($test as $method) {
56
            if (isset($methods[$method])) {
57
                return $method;
58
            }
59
        }
60
    }
61
}
62