QueryType::resolveEnumValues()   B
last analyzed

Complexity

Conditions 10
Paths 11

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 10.0145

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 18
cts 19
cp 0.9474
rs 7.6666
c 0
b 0
f 0
cc 10
nc 11
nop 2
crap 10.0145

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Date: 03.12.15
4
 *
5
 * @author Portey Vasil <[email protected]>
6
 */
7
8
namespace Youshido\GraphQL\Introspection;
9
10
use Youshido\GraphQL\Execution\ResolveInfo;
11
use Youshido\GraphQL\Field\Field;
12
use Youshido\GraphQL\Introspection\Traits\TypeCollectorTrait;
13
use Youshido\GraphQL\Type\AbstractType;
14
use Youshido\GraphQL\Type\CompositeTypeInterface;
15
use Youshido\GraphQL\Type\Enum\AbstractEnumType;
16
use Youshido\GraphQL\Type\InputObject\AbstractInputObjectType;
17
use Youshido\GraphQL\Type\ListType\ListType;
18
use Youshido\GraphQL\Type\NonNullType;
19
use Youshido\GraphQL\Type\Object\AbstractObjectType;
20
use Youshido\GraphQL\Type\Scalar\BooleanType;
21
use Youshido\GraphQL\Type\TypeMap;
22
use Youshido\GraphQL\Type\Union\AbstractUnionType;
23
24
class QueryType extends AbstractObjectType
25
{
26
27
    use TypeCollectorTrait;
28
29
    /**
30
     * @return String type name
31
     */
32 74
    public function getName()
33
    {
34 74
        return '__Type';
35
    }
36
37 6
    public function resolveOfType(AbstractType $value)
38
    {
39 6
        if ($value instanceof CompositeTypeInterface) {
40 5
            return $value->getTypeOf();
41
        }
42
43 6
        return null;
44
    }
45
46 6
    public function resolveInputFields($value)
47
    {
48 6
        if ($value instanceof AbstractInputObjectType) {
49
            /** @var AbstractObjectType $value */
50 1
            return $value->getConfig()->getFields();
0 ignored issues
show
Documentation Bug introduced by
The method getFields does not exist on object<Youshido\GraphQL\Config\AbstractConfig>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
51
        }
52
53 6
        return null;
54
    }
55
56 5
    public function resolveEnumValues($value, $args)
57
    {
58
        /** @var $value AbstractType|AbstractEnumType */
59 5
        if ($value && $value->getKind() == TypeMap::KIND_ENUM) {
60 5
            $data = [];
61 5
            foreach ($value->getValues() as $enumValue) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Youshido\GraphQL\Type\AbstractType as the method getValues() does only exist in the following sub-classes of Youshido\GraphQL\Type\AbstractType: Examples\Blog\Schema\PostStatus, Youshido\GraphQL\Introsp...n\DirectiveLocationType, Youshido\GraphQL\Type\Enum\AbstractEnumType, Youshido\GraphQL\Type\Enum\EnumType, Youshido\Tests\DataProvider\TestEnumType, Youshido\Tests\Issues\Issue171\KpiStatusType, Youshido\Tests\StarWars\Schema\EpisodeEnum. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
62 5
                if(!$args['includeDeprecated'] && (isset($enumValue['isDeprecated']) && $enumValue['isDeprecated'])) {
63
                    continue;
64
                }
65
66 5
                if (!array_key_exists('description', $enumValue)) {
67 5
                    $enumValue['description'] = '';
68 5
                }
69 5
                if (!array_key_exists('isDeprecated', $enumValue)) {
70 5
                    $enumValue['isDeprecated'] = false;
71 5
                }
72 5
                if (!array_key_exists('deprecationReason', $enumValue)) {
73 5
                    $enumValue['deprecationReason'] = null;
74 5
                }
75
76 5
                $data[] = $enumValue;
77 5
            }
78
79 5
            return $data;
80
        }
81
82 5
        return null;
83
    }
84
85 7
    public function resolveFields($value, $args)
86
    {
87
        /** @var AbstractType $value */
88 7
        if (!$value ||
89 7
            in_array($value->getKind(), [TypeMap::KIND_SCALAR, TypeMap::KIND_UNION, TypeMap::KIND_INPUT_OBJECT, TypeMap::KIND_ENUM])
90 7
        ) {
91 6
            return null;
92
        }
93
94
        /** @var AbstractObjectType $value */
95 7
        return array_filter($value->getConfig()->getFields(), function ($field) use ($args) {
0 ignored issues
show
Documentation Bug introduced by
The method getFields does not exist on object<Youshido\GraphQL\Config\AbstractConfig>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
96
            /** @var $field Field */
97 7
            if (in_array($field->getName(), ['__type', '__schema']) || (!$args['includeDeprecated'] && $field->isDeprecated())) {
98 7
                return false;
99
            }
100
101 7
            return true;
102 7
        });
103
    }
104
105 6
    public function resolveInterfaces($value)
106
    {
107
        /** @var $value AbstractType */
108 6
        if ($value->getKind() == TypeMap::KIND_OBJECT) {
109
            /** @var $value AbstractObjectType */
110 6
            return $value->getConfig()->getInterfaces() ?: [];
0 ignored issues
show
Documentation Bug introduced by
The method getInterfaces does not exist on object<Youshido\GraphQL\Config\AbstractConfig>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
111
        }
112
113 5
        return null;
114
    }
115
116 6
    public function resolvePossibleTypes($value, $args, ResolveInfo $info)
117
    {
118
        /** @var $value AbstractObjectType */
119 6
        if ($value->getKind() == TypeMap::KIND_INTERFACE) {
120 3
            $schema = $info->getExecutionContext()->getSchema();
121 3
            $this->collectTypes($schema->getQueryType());
122 3
            foreach ($schema->getTypesList()->getTypes() as $type) {
123
              $this->collectTypes($type);
124 3
            }
125
126 3
            $possibleTypes = [];
127 3
            foreach ($this->types as $type) {
128
                /** @var $type AbstractObjectType */
129 3
                if ($type->getKind() == TypeMap::KIND_OBJECT) {
130 3
                    $interfaces = $type->getConfig()->getInterfaces();
0 ignored issues
show
Documentation Bug introduced by
The method getInterfaces does not exist on object<Youshido\GraphQL\Config\AbstractConfig>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
131
132 3
                    if ($interfaces) {
133 3
                        foreach ($interfaces as $interface) {
134 3
                            if ($interface->getName() == $value->getName()) {
135 3
                                $possibleTypes[] = $type;
136 3
                            }
137 3
                        }
138 3
                    }
139 3
                }
140 3
            }
141
142 3
            return $possibleTypes;
143 6
        } elseif ($value->getKind() == TypeMap::KIND_UNION) {
144
            /** @var $value AbstractUnionType */
145 1
            return $value->getTypes();
146
        }
147
148 6
        return null;
149
    }
150
151 11
    public function build($config)
152
    {
153
        $config
154 11
            ->addField('name', TypeMap::TYPE_STRING)
155 11
            ->addField('kind', new NonNullType(TypeMap::TYPE_STRING))
156 11
            ->addField('description', TypeMap::TYPE_STRING)
157 11
            ->addField('ofType', [
158 11
                'type'    => new QueryType(),
159 11
                'resolve' => [$this, 'resolveOfType']
160 11
            ])
161 11
            ->addField(new Field([
162 11
                'name'    => 'inputFields',
163 11
                'type'    => new ListType(new NonNullType(new InputValueType())),
164 11
                'resolve' => [$this, 'resolveInputFields']
165 11
            ]))
166 11
            ->addField(new Field([
167 11
                'name'    => 'enumValues',
168
                'args'    => [
169
                    'includeDeprecated' => [
170 11
                        'type'    => new BooleanType(),
171
                        'defaultValue' => false
172 11
                    ]
173 11
                ],
174 11
                'type'    => new ListType(new NonNullType(new EnumValueType())),
175 11
                'resolve' => [$this, 'resolveEnumValues']
176 11
            ]))
177 11
            ->addField(new Field([
178 11
                'name'    => 'fields',
179
                'args'    => [
180
                    'includeDeprecated' => [
181 11
                        'type'    => new BooleanType(),
182
                        'defaultValue' => false
183 11
                    ]
184 11
                ],
185 11
                'type'    => new ListType(new NonNullType(new FieldType())),
186 11
                'resolve' => [$this, 'resolveFields']
187 11
            ]))
188 11
            ->addField(new Field([
189 11
                'name'    => 'interfaces',
190 11
                'type'    => new ListType(new NonNullType(new QueryType())),
191 11
                'resolve' => [$this, 'resolveInterfaces']
192 11
            ]))
193 11
            ->addField('possibleTypes', [
194 11
                'type'    => new ListType(new NonNullType(new QueryType())),
195 11
                'resolve' => [$this, 'resolvePossibleTypes']
196 11
            ]);
197 11
    }
198
199
}
200