Completed
Pull Request — 8.x-3.x (#519)
by Sebastian
02:35
created

Reducer::getType()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 6
nc 5
nop 2
dl 0
loc 11
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql\GraphQL\Execution;
4
5
use Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface;
6
use Drupal\graphql\GraphQL\Utility\TypeCollector;
7
use Youshido\GraphQL\Exception\ResolveException;
8
use Youshido\GraphQL\Execution\Context\ExecutionContext;
9
use Youshido\GraphQL\Field\FieldInterface;
10
use Youshido\GraphQL\Parser\Ast\AbstractAst;
11
use Youshido\GraphQL\Parser\Ast\Field;
12
use Youshido\GraphQL\Parser\Ast\Fragment;
13
use Youshido\GraphQL\Parser\Ast\FragmentReference;
14
use Youshido\GraphQL\Parser\Ast\Interfaces\FragmentInterface;
15
use Youshido\GraphQL\Parser\Ast\Mutation;
16
use Youshido\GraphQL\Parser\Ast\Query;
17
use Youshido\GraphQL\Parser\Ast\TypedFragmentReference;
18
use Youshido\GraphQL\Type\AbstractType;
19
use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
20
use Youshido\GraphQL\Type\Object\AbstractObjectType;
21
22
class Reducer {
23
24
  /**
25
   * @var \Youshido\GraphQL\Execution\Request
26
   */
27
  protected $request;
28
29
  /**
30
   * @var \Youshido\GraphQL\Schema\AbstractSchema
31
   */
32
  protected $schema;
33
34
  /**
35
   * @var \Youshido\GraphQL\Type\TypeInterface[]
36
   */
37
  protected $types;
38
39
  /**
40
   * @var \Youshido\GraphQL\Execution\Context\ExecutionContext
41
   */
42
  protected $context;
43
44
  /**
45
   * QueryReducer constructor.
46
   *
47
   */
48
  public function __construct(ExecutionContext $executionContext) {
49
    $this->context = $executionContext;
50
    $this->schema = $executionContext->getSchema();
51
    $this->request = $executionContext->getRequest();
52
    $this->types = TypeCollector::collectTypes($this->schema);
53
  }
54
55
  /**
56
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
57
   *
58
   * @return mixed|\Youshido\GraphQL\Parser\Ast\Query
59
   */
60
  public function reduceRequest(VisitorInterface $visitor) {
61
    $operations = $this->request->getAllOperations();
62
63
    return array_reduce($operations, function ($carry, $current) use ($visitor) {
64
      $type = $current instanceof Mutation ? $this->schema->getMutationType() : $this->schema->getQueryType();
65
      return $visitor->reduce($carry, $this->reduceOperation($current, $type, $visitor), $this->context);
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::reduce() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
    }, $visitor->initial($this->context));
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::initial() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
67
  }
68
69
  /**
70
   * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $query
71
   * @param \Youshido\GraphQL\Type\AbstractType $type
72
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
73
   *
74
   * @return mixed|void
75
   */
76
  protected function reduceOperation(AbstractAst $query, AbstractType $type, VisitorInterface $visitor) {
77
    $carry = $visitor->initial();
78
    if (!($type instanceof AbstractObjectType) || !$type->hasField($query->getName())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Youshido\GraphQL\Parser\Ast\AbstractAst as the method getName() does only exist in the following sub-classes of Youshido\GraphQL\Parser\Ast\AbstractAst: Youshido\GraphQL\Parser\Ast\Argument, Youshido\GraphQL\Parser\Ast\ArgumentValue\Variable, Youshido\GraphQL\Parser\...Value\VariableReference, Youshido\GraphQL\Parser\Ast\Directive, Youshido\GraphQL\Parser\Ast\Field, Youshido\GraphQL\Parser\Ast\Fragment, Youshido\GraphQL\Parser\Ast\FragmentReference, Youshido\GraphQL\Parser\Ast\Mutation, Youshido\GraphQL\Parser\Ast\Query. 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...
79
      return $carry;
80
    }
81
82
    if (($name = $query->getName()) && $type->hasField($name)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Youshido\GraphQL\Parser\Ast\AbstractAst as the method getName() does only exist in the following sub-classes of Youshido\GraphQL\Parser\Ast\AbstractAst: Youshido\GraphQL\Parser\Ast\Argument, Youshido\GraphQL\Parser\Ast\ArgumentValue\Variable, Youshido\GraphQL\Parser\...Value\VariableReference, Youshido\GraphQL\Parser\Ast\Directive, Youshido\GraphQL\Parser\Ast\Field, Youshido\GraphQL\Parser\Ast\Fragment, Youshido\GraphQL\Parser\Ast\FragmentReference, Youshido\GraphQL\Parser\Ast\Mutation, Youshido\GraphQL\Parser\Ast\Query. 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...
83
      $operation = $type->getField($query->getName());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Youshido\GraphQL\Parser\Ast\AbstractAst as the method getName() does only exist in the following sub-classes of Youshido\GraphQL\Parser\Ast\AbstractAst: Youshido\GraphQL\Parser\Ast\Argument, Youshido\GraphQL\Parser\Ast\ArgumentValue\Variable, Youshido\GraphQL\Parser\...Value\VariableReference, Youshido\GraphQL\Parser\Ast\Directive, Youshido\GraphQL\Parser\Ast\Field, Youshido\GraphQL\Parser\Ast\Fragment, Youshido\GraphQL\Parser\Ast\FragmentReference, Youshido\GraphQL\Parser\Ast\Mutation, Youshido\GraphQL\Parser\Ast\Query. 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...
84
      $walker = $this->walkQuery($query, $operation, $visitor);
85
86
      while ($walker->valid()) {
87
        /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
88
        /** @var \Youshido\GraphQL\Field\Field $ast */
89
        list($field, $ast, $child) = $walker->current();
90
91
        $args = $field->getKeyValueArguments();
92
        $result = $visitor->visit($args, $ast, $child, $this->context);
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::visit() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
93
        $carry = $visitor->reduce($carry, $result, $this->context);
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::reduce() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
94
95
        $walker->send($result);
96
      }
97
    }
98
99
    return $carry;
100
  }
101
102
  /**
103
   * @param $node
104
   * @param \Youshido\GraphQL\Field\FieldInterface $current
105
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
106
   *
107
   * @return \Generator
108
   */
109
  protected function walkQuery(AbstractAst $node, FieldInterface $current, VisitorInterface $visitor) {
110
    $carry = $visitor->initial();
111
112
    if (!($node instanceof Field)) {
113
      /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
114
      foreach ($node->getFields() as $field) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Youshido\GraphQL\Parser\Ast\AbstractAst as the method getFields() does only exist in the following sub-classes of Youshido\GraphQL\Parser\Ast\AbstractAst: Youshido\GraphQL\Parser\Ast\Field, Youshido\GraphQL\Parser\Ast\Fragment, Youshido\GraphQL\Parser\Ast\Mutation, Youshido\GraphQL\Parser\Ast\Query, Youshido\GraphQL\Parser\Ast\TypedFragmentReference. 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...
115
        if ($field instanceof FragmentInterface) {
116
          if ($field instanceof FragmentReference) {
117
            $field = $this->request->getFragment($field->getName());
118
          }
119
120
          $walker = $this->walkQuery($field, $current, $visitor);
0 ignored issues
show
Bug introduced by
It seems like $field defined by $this->request->getFragment($field->getName()) on line 117 can also be of type null or object<Youshido\GraphQL\...aces\FragmentInterface>; however, Drupal\graphql\GraphQL\E...on\Reducer::walkQuery() does only seem to accept object<Youshido\GraphQL\Parser\Ast\AbstractAst>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
121
          $next = $walker->current();
122
123 View Code Duplication
          while ($walker->valid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
            $received = (yield $next);
125
            $carry = $visitor->reduce($carry, $received, $this->context);
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::reduce() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
126
            $next = $walker->send($received);
127
          }
128
        }
129
        else {
130
          $type = $this->getType($node, $current);
131
          $name = $field->getName();
132
133
          if ($name !== Processor::TYPE_NAME_QUERY && ($type instanceof AbstractObjectType || $type instanceof AbstractInterfaceType)) {
134
            if (!$type->hasField($name)) {
135
              $type = $type->getNamedType()->getName();
136
              $location = $field->getLocation();
137
138
              throw new ResolveException(sprintf('Unknown field %s for type %s.', $name, $type), $location);
139
            }
140
141
            $ast = $type->getField($name);
142
            $walker = $this->walkQuery($field, $ast, $visitor);
143
            $next = $walker->current();
144
145 View Code Duplication
            while ($walker->valid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
146
              $received = (yield $next);
147
              $carry = $visitor->reduce($carry, $received, $this->context);
0 ignored issues
show
Unused Code introduced by
The call to VisitorInterface::reduce() has too many arguments starting with $this->context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
148
              $next = $walker->send($received);
149
            }
150
          }
151
        }
152
      }
153
    }
154
155
    if ($node instanceof Query || $node instanceof Field) {
156
      yield [$node, $current, $carry];
157
    }
158
  }
159
160
  /**
161
   * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $node
162
   * @param \Youshido\GraphQL\Field\FieldInterface $current
163
   *
164
   * @return null|\Youshido\GraphQL\Type\AbstractType|\Youshido\GraphQL\Type\TypeInterface
165
   */
166
  protected function getType(AbstractAst $node, FieldInterface $current) {
167
    if ($node instanceof Fragment && $name = $node->getModel()) {
168
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
169
    }
170
171
    if ($node instanceof TypedFragmentReference && $name = $node->getTypeName()) {
172
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
173
    }
174
175
    return $current->getType()->getNamedType();
176
  }
177
178
}