PropertyGuesser   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 5
dl 0
loc 53
c 0
b 0
f 0
rs 10

2 Methods

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