Completed
Pull Request — master (#31)
by Sebastian
06:26 queued 02:32
created

QueryType::resolveEnumValues()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
ccs 13
cts 13
cp 1
rs 6.7272
cc 7
eloc 13
nc 10
nop 1
crap 7
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\Field\SchemaField;
13
use Youshido\GraphQL\Introspection\Traits\TypeCollectorTrait;
14
use Youshido\GraphQL\Type\AbstractType;
15
use Youshido\GraphQL\Type\CompositeTypeInterface;
16
use Youshido\GraphQL\Type\Enum\AbstractEnumType;
17
use Youshido\GraphQL\Type\InputObject\AbstractInputObjectType;
18
use Youshido\GraphQL\Type\ListType\ListType;
19
use Youshido\GraphQL\Type\Object\AbstractObjectType;
20
use Youshido\GraphQL\Type\TypeMap;
21
use Youshido\GraphQL\Type\Union\AbstractUnionType;
22
23
class QueryType extends AbstractObjectType
24
{
25
26
    use TypeCollectorTrait;
27
28
    /**
29
     * @return String type name
30
     */
31 22
    public function getName()
32
    {
33 22
        return '__Type';
34
    }
35
36 3
    public static function resolveOfType(AbstractType $value)
37
    {
38 3
        if ($value instanceof CompositeTypeInterface) {
39 2
           return $value->getTypeOf();
40
        }
41
42 3
        return null;
43
    }
44
45 3
    public static function resolveInputFields($value)
46
    {
47 3
        if ($value instanceof AbstractInputObjectType) {
48
            /** @var AbstractObjectType $value */
49
            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...
50
        }
51
52 3
        return null;
53
    }
54
55 2
    public static function resolveEnumValues($value)
56
    {
57
        /** @var $value AbstractType|AbstractEnumType */
58 2
        if ($value && $value->getKind() == TypeMap::KIND_ENUM) {
59 2
            $data = [];
60 2
            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\Type\Enum\AbstractEnumType, Youshido\GraphQL\Type\Enum\EnumType, Youshido\Tests\DataProvider\TestEnumType, 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...
61 2
                if (!array_key_exists('description', $enumValue)) {
62 2
                    $enumValue['description'] = '';
63
                }
64 2
                if (!array_key_exists('isDeprecated', $enumValue)) {
65 2
                    $enumValue['isDeprecated'] = false;
66
                }
67 2
                if (!array_key_exists('deprecationReason', $enumValue)) {
68 2
                    $enumValue['deprecationReason'] = '';
69
                }
70
71 2
                $data[] = $enumValue;
72
            }
73
74 2
            return $data;
75
        }
76
77 2
        return null;
78
    }
79
80 4
    public static function resolveFields($value)
81
    {
82
        /** @var AbstractType $value */
83 4
        if (!$value ||
84 4
            in_array($value->getKind(), [TypeMap::KIND_SCALAR, TypeMap::KIND_UNION, TypeMap::KIND_INPUT_OBJECT, TypeMap::KIND_ENUM])
85
        ) {
86 3
            return null;
87
        }
88
89
        /** @var AbstractObjectType $value */
90 4
        $fields = $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...
91
92 4
        foreach ($fields as $key => $field) {
93 4
            if (in_array($field->getName(), ['__type', '__schema'])) {
94 4
                unset($fields[$key]);
95
            }
96
        }
97
98 4
        return $fields;
99
    }
100
101 3
    public static function resolveInterfaces($value)
102
    {
103
        /** @var $value AbstractType */
104 3
        if ($value->getKind() == TypeMap::KIND_OBJECT) {
105
            /** @var $value AbstractObjectType */
106 3
            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...
107
        }
108
109 2
        return null;
110
    }
111
112 3
    public function resolvePossibleTypes($value, $args, ResolveInfo $info)
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $info is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
113
    {
114
        /** @var $value AbstractObjectType */
115 3
        if ($value->getKind() == TypeMap::KIND_INTERFACE) {
116 2
            $this->collectTypes(SchemaField::$schema->getQueryType());
117
118 2
            $possibleTypes = [];
119 2
            foreach ($this->types as $type) {
120
                /** @var $type AbstractObjectType */
121 2
                if ($type->getKind() == TypeMap::KIND_OBJECT) {
122 2
                    $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...
123
124 2
                    if ($interfaces) {
125 2
                        foreach ($interfaces as $interface) {
126 2
                            if (get_class($interface) == get_class($value)) {
127 2
                                $possibleTypes[] = $type;
128
                            }
129
                        }
130
                    }
131
                }
132
            }
133
134 2
            return $possibleTypes ?: [];
135 3
        } elseif ($value->getKind() == TypeMap::KIND_UNION) {
136
            /** @var $value AbstractUnionType */
137 1
            return $value->getTypes();
138
        }
139
140 3
        return null;
141
    }
142
143 7
    public function build($config)
144
    {
145
        $config
146 7
            ->addField('name', TypeMap::TYPE_STRING)
147 7
            ->addField('kind', TypeMap::TYPE_STRING)
148 7
            ->addField('description', TypeMap::TYPE_STRING)
149 7
            ->addField('ofType', [
150 7
                'type'    => new QueryType(),
151 7
                'resolve' => [get_class($this), 'resolveOfType']
152
            ])
153 7
            ->addField(new Field([
154 7
                'name'    => 'inputFields',
155 7
                'type'    => new ListType(new InputValueType()),
156 7
                'resolve' => [get_class($this), 'resolveInputFields']
157
            ]))
158 7
            ->addField(new Field([
159 7
                'name'    => 'enumValues',
160 7
                'type'    => new ListType(new EnumValueType()),
161 7
                'resolve' => [get_class($this), 'resolveEnumValues']
162
            ]))
163 7
            ->addField(new Field([
164 7
                'name'    => 'fields',
165 7
                'type'    => new ListType(new FieldType()),
166 7
                'resolve' => [get_class($this), 'resolveFields']
167
            ]))
168 7
            ->addField(new Field([
169 7
                'name'    => 'interfaces',
170 7
                'type'    => new ListType(new QueryType()),
171 7
                'resolve' => [get_class($this), 'resolveInterfaces']
172
            ]))
173 7
            ->addField('possibleTypes', [
174 7
                'type'    => new ListType(new QueryType()),
175 7
                'resolve' => [$this, 'resolvePossibleTypes']
176
            ]);
177 7
    }
178
179 6
    public function isValidValue($value)
180
    {
181 6
        return $value instanceof AbstractType;
182
    }
183
184
185
}
186