Completed
Push — master ( dbf644...4759cd )
by David
01:48 queued 01:46
created

NamingStrategy::getOutputTypeName()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
rs 10
c 0
b 0
f 0
cc 4
nc 6
nop 2
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers;
5
6
7
use function lcfirst;
8
use function strlen;
9
use function strpos;
10
use function substr;
11
use TheCodingMachine\GraphQL\Controllers\Annotations\Factory;
12
use TheCodingMachine\GraphQL\Controllers\Annotations\Type;
13
14
class NamingStrategy implements NamingStrategyInterface
15
{
16
    /**
17
     * Returns the name of the GraphQL interface from a name of a concrete class (when the interface is created
18
     * automatically to manage inheritance)
19
     */
20
    public function getInterfaceNameFromConcreteName(string $concreteType): string
21
    {
22
        return $concreteType.'Interface';
23
    }
24
25
    /**
26
     * Returns the GraphQL output object type name based on the type className and the Type annotation.
27
     */
28
    public function getOutputTypeName(string $typeClassName, Type $type): string
29
    {
30
        if ($prevPos = strrpos($typeClassName, '\\')) {
31
            $typeClassName = substr($typeClassName, $prevPos + 1);
32
        }
33
        // By default, if the class name ends with Type, let's take the name of the class for the type
34
        if (substr($typeClassName, -4) === 'Type') {
35
            return substr($typeClassName, 0, -4);
36
        }
37
        // Else, let's take the name of the targeted class
38
        $typeClassName = $type->getClass();
39
        if ($prevPos = strrpos($typeClassName, '\\')) {
40
            $typeClassName = substr($typeClassName, $prevPos + 1);
41
        }
42
        return $typeClassName;
43
    }
44
45
    public function getInputTypeName(string $className, Factory $factory): string
46
    {
47
        $inputTypeName = $factory->getName();
48
        if ($inputTypeName !== null) {
49
            return $inputTypeName;
50
        }
51
        if ($prevPos = strrpos($className, '\\')) {
52
            $className = substr($className, $prevPos + 1);
53
        }
54
        return $className.'Input';
55
    }
56
57
    /**
58
     * Returns the name of a GraphQL field from the name of the annotated method.
59
     */
60
    public function getFieldNameFromMethodName(string $methodName): string
61
    {
62
        // Let's remove any "get" or "is".
63
        if (strpos($methodName, 'get') === 0 && strlen($methodName) > 3) {
64
            return lcfirst(substr($methodName, 3));
65
        }
66
        if (strpos($methodName, 'is') === 0 && strlen($methodName) > 2) {
67
            return lcfirst(substr($methodName, 2));
68
        }
69
        return $methodName;
70
    }
71
}
72