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

QueryReducer::reduceQuery()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 1
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql\GraphQL\Execution;
4
5
use Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface;
6
use Drupal\graphql\GraphQL\Utility\TypeCollector;
7
use Youshido\GraphQL\Execution\Request;
8
use Youshido\GraphQL\Field\FieldInterface;
9
use Youshido\GraphQL\Parser\Ast\AbstractAst;
10
use Youshido\GraphQL\Parser\Ast\Field;
11
use Youshido\GraphQL\Parser\Ast\Fragment;
12
use Youshido\GraphQL\Parser\Ast\FragmentReference;
13
use Youshido\GraphQL\Parser\Ast\Interfaces\FragmentInterface;
14
use Youshido\GraphQL\Parser\Ast\Mutation;
15
use Youshido\GraphQL\Parser\Ast\Query;
16
use Youshido\GraphQL\Parser\Ast\TypedFragmentReference;
17
use Youshido\GraphQL\Schema\AbstractSchema;
18
use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
19
use Youshido\GraphQL\Type\Object\AbstractObjectType;
20
21
class QueryReducer {
22
23
  /**
24
   * @var \Youshido\GraphQL\Execution\Request
25
   */
26
  protected $request;
27
28
  /**
29
   * @var \Youshido\GraphQL\Schema\AbstractSchema
30
   */
31
  protected $schema;
32
33
  /**
34
   * @var \Youshido\GraphQL\Type\TypeInterface[]
35
   */
36
  protected $types;
37
38
  /**
39
   * QueryReducer constructor.
40
   *
41
   * @param \Youshido\GraphQL\Schema\AbstractSchema $schema
42
   * @param \Youshido\GraphQL\Execution\Request $request
43
   */
44
  public function __construct(AbstractSchema $schema, Request $request) {
45
    $this->schema = $schema;
46
    $this->request = $request;
47
    $this->types = TypeCollector::collectTypes($schema);
48
  }
49
50
  /**
51
   * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor
52
   *
53
   * @return mixed|\Youshido\GraphQL\Parser\Ast\Query
54
   */
55
  public function reduceQuery(QueryVisitorInterface $visitor) {
56
    $operations = $this->request->getAllOperations();
57
58
    return $visitor->finish(array_reduce($operations, function ($carry, $current) use ($visitor) {
59
      $type = $current instanceof Mutation ? $this->schema->getMutationType() : $this->schema->getQueryType();
60
      return $this->reduceOperation($current, $carry, $type, $visitor);
61
    }, $visitor->initial()));
62
  }
63
64
  /**
65
   * @param \Youshido\GraphQL\Parser\Ast\Query $query
66
   * @param $carry
67
   * @param $current
68
   * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor
69
   *
70
   * @return mixed|void
71
   */
72
  protected function reduceOperation(Query $query, $carry, $current, QueryVisitorInterface $visitor) {
73
    if (!($current instanceof AbstractObjectType) || !$current->hasField($query->getName())) {
74
      return;
75
    }
76
77
    if (($name = $query->getName()) && $current->hasField($name)) {
78
      $operation = $current->getField($query->getName());
79
      $walker = $this->walkQuery($query, $operation, $visitor);
80
81
      while ($walker->valid()) {
82
        /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
83
        /** @var \Youshido\GraphQL\Field\Field $ast */
84
        list($field, $ast, $child) = $walker->current();
85
86
        $args = $field->getKeyValueArguments();
87
        $result = $visitor->visit($args, $ast, $child);
88
        $carry = $visitor->reduce($carry, $result);
89
90
        $walker->send($result);
91
      }
92
    }
93
94
    return $carry;
95
  }
96
97
  /**
98
   * @param $node
99
   * @param \Youshido\GraphQL\Field\FieldInterface $current
100
   * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor
101
   *
102
   * @return \Generator
103
   */
104
  protected function walkQuery(AbstractAst $node, FieldInterface $current, QueryVisitorInterface $visitor) {
105
    $carry = $visitor->initial();
106
107
    if (!($node instanceof Field)) {
108
      /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
109
      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...
110
        if ($field instanceof FragmentInterface) {
111
          if ($field instanceof FragmentReference) {
112
            $field = $this->request->getFragment($field->getName());
113
          }
114
115
          $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 112 can also be of type null or object<Youshido\GraphQL\...aces\FragmentInterface>; however, Drupal\graphql\GraphQL\E...eryReducer::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...
116
          $next = $walker->current();
117
118 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...
119
            $received = (yield $next);
120
            $carry = $visitor->reduce($carry, $received);
121
            $next = $walker->send($received);
122
          }
123
        }
124
        else {
125
          $type = $this->getType($node, $current);
126
          $name = $field->getName();
127
128
          if (($type instanceof AbstractObjectType || $type instanceof AbstractInterfaceType) && $type->hasField($name)) {
129
            $ast = $type->getField($name);
130
            $walker = $this->walkQuery($field, $ast, $visitor);
131
            $next = $walker->current();
132
133 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...
134
              $received = (yield $next);
135
              $carry = $visitor->reduce($carry, $received);
136
              $next = $walker->send($received);
137
            }
138
          }
139
        }
140
      }
141
    }
142
143
    if ($node instanceof Query || $node instanceof Field) {
144
      yield [$node, $current, $carry];
145
    }
146
  }
147
148
  /**
149
   * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $node
150
   * @param \Youshido\GraphQL\Field\FieldInterface $current
151
   *
152
   * @return null|\Youshido\GraphQL\Type\AbstractType|\Youshido\GraphQL\Type\TypeInterface
153
   */
154
  protected function getType(AbstractAst $node, FieldInterface $current) {
155
    if ($node instanceof Fragment && $name = $node->getModel()) {
156
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
157
    }
158
159
    if ($node instanceof TypedFragmentReference && $name = $node->getTypeName()) {
160
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
161
    }
162
163
    return $current->getType()->getNamedType();
164
  }
165
166
}