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

Reducer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 6
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\Visitor\VisitorInterface;
6
use Drupal\graphql\GraphQL\Utility\TypeCollector;
7
use Youshido\GraphQL\Execution\Context\ExecutionContext;
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\Type\AbstractType;
18
use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
19
use Youshido\GraphQL\Type\Object\AbstractObjectType;
20
21
class Reducer {
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
   * @var \Youshido\GraphQL\Execution\Context\ExecutionContext
40
   */
41
  protected $context;
42
43
  /**
44
   * QueryReducer constructor.
45
   *
46
   */
47
  public function __construct(ExecutionContext $executionContext) {
48
    $this->context = $executionContext;
49
    $this->schema = $executionContext->getSchema();
50
    $this->request = $executionContext->getRequest();
51
    $this->types = TypeCollector::collectTypes($this->schema);
52
  }
53
54
  /**
55
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
56
   *
57
   * @return mixed|\Youshido\GraphQL\Parser\Ast\Query
58
   */
59
  public function reduceRequest(VisitorInterface $visitor) {
60
    $operations = $this->request->getAllOperations();
61
62
    return array_reduce($operations, function ($carry, $current) use ($visitor) {
63
      $type = $current instanceof Mutation ? $this->schema->getMutationType() : $this->schema->getQueryType();
64
      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...
65
    }, $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...
66
  }
67
68
  /**
69
   * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $query
70
   * @param \Youshido\GraphQL\Type\AbstractType $type
71
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
72
   *
73
   * @return mixed|void
74
   */
75
  protected function reduceOperation(AbstractAst $query, AbstractType $type, VisitorInterface $visitor) {
76
    $carry = $visitor->initial();
77
    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...
78
      return $carry;
79
    }
80
81
    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...
82
      $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...
83
      $walker = $this->walkQuery($query, $operation, $visitor);
84
85
      while ($walker->valid()) {
86
        /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
87
        /** @var \Youshido\GraphQL\Field\Field $ast */
88
        list($field, $ast, $child) = $walker->current();
89
90
        $args = $field->getKeyValueArguments();
91
        $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...
92
        $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...
93
94
        $walker->send($result);
95
      }
96
    }
97
98
    return $carry;
99
  }
100
101
  /**
102
   * @param $node
103
   * @param \Youshido\GraphQL\Field\FieldInterface $current
104
   * @param \Drupal\graphql\GraphQL\Execution\Visitor\VisitorInterface $visitor
105
   *
106
   * @return \Generator
107
   */
108
  protected function walkQuery(AbstractAst $node, FieldInterface $current, VisitorInterface $visitor) {
109
    $carry = $visitor->initial();
110
111
    if (!($node instanceof Field)) {
112
      /** @var \Youshido\GraphQL\Parser\Ast\Field $field */
113
      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...
114
        if ($field instanceof FragmentInterface) {
115
          if ($field instanceof FragmentReference) {
116
            $field = $this->request->getFragment($field->getName());
117
          }
118
119
          $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 116 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...
120
          $next = $walker->current();
121
122 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...
123
            $received = (yield $next);
124
            $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...
125
            $next = $walker->send($received);
126
          }
127
        }
128
        else {
129
          $type = $this->getType($node, $current);
130
          $name = $field->getName();
131
132
          if (($type instanceof AbstractObjectType || $type instanceof AbstractInterfaceType) && $type->hasField($name)) {
133
            $ast = $type->getField($name);
134
            $walker = $this->walkQuery($field, $ast, $visitor);
135
            $next = $walker->current();
136
137 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...
138
              $received = (yield $next);
139
              $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...
140
              $next = $walker->send($received);
141
            }
142
          }
143
        }
144
      }
145
    }
146
147
    if ($node instanceof Query || $node instanceof Field) {
148
      yield [$node, $current, $carry];
149
    }
150
  }
151
152
  /**
153
   * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $node
154
   * @param \Youshido\GraphQL\Field\FieldInterface $current
155
   *
156
   * @return null|\Youshido\GraphQL\Type\AbstractType|\Youshido\GraphQL\Type\TypeInterface
157
   */
158
  protected function getType(AbstractAst $node, FieldInterface $current) {
159
    if ($node instanceof Fragment && $name = $node->getModel()) {
160
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
161
    }
162
163
    if ($node instanceof TypedFragmentReference && $name = $node->getTypeName()) {
164
      return isset($this->types[$name]) ? $this->types[$name] : NULL;
165
    }
166
167
    return $current->getType()->getNamedType();
168
  }
169
170
}