Completed
Push — 8.x-1.x ( 8c46ac...86e5ca )
by Philipp
03:33
created

GraphQLTemplateTrait::display()   C

Complexity

Conditions 10
Paths 25

Size

Total Lines 52
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 52
rs 6.2553
cc 10
eloc 30
nc 25
nop 2

How to fix   Long Method    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
namespace Drupal\graphql_twig;
4
5
use Drupal\Core\Entity\EntityInterface;
6
use Drupal\graphql\GraphQL\Execution\QueryProcessor;
7
use GraphQL\Server\OperationParams;
8
9
/**
10
 * Trait that will be attached to all GraphQL enabled Twig templates.
11
 */
12
trait GraphQLTemplateTrait {
13
14
  /**
15
   * @return bool
16
   */
17
  abstract public static function hasGraphQLOperations();
18
19
  /**
20
   * @var string
21
   */
22
  abstract public static function rawGraphQLQuery();
23
24
  /**
25
   * @return string
26
   */
27
  abstract public static function rawGraphQLParent();
28
29
  /**
30
   * @return string[]
31
   */
32
  abstract public static function rawGraphQLIncludes();
33
34
  /**
35
   * @return string[]
36
   */
37
  abstract public static function rawGraphQLArguments();
38
39
  /**
40
   * The GraphQL query processor.
41
   *
42
   * @var \Drupal\graphql\GraphQL\Execution\QueryProcessor
43
   */
44
  protected $queryProcessor;
45
46
  /**
47
   * Debug mode flag.
48
   *
49
   * @var bool
50
   */
51
  protected $debug = FALSE;
52
53
  /**
54
   * Inject the query processor.
55
   *
56
   * @param \Drupal\graphql\GraphQL\Execution\QueryProcessor $queryProcessor
57
   *   The query processor instance.
58
   */
59
  public function setQueryProcessor(QueryProcessor $queryProcessor) {
60
    $this->queryProcessor = $queryProcessor;
61
  }
62
63
  /**
64
   * Set debug mode for this template.
65
   *
66
   * @param bool $debug
67
   *   Boolean flag for debug mode.
68
   */
69
  public function setDebug($debug) {
70
    $this->debug = $debug;
71
  }
72
73
  /**
74
   * {@inheritdoc}
75
   */
76
  public function display(array $context, array $blocks = array()) {
77
78
    if (!$query = $this->getGraphQLQuery()) {
79
      parent::display($context, $blocks);
80
      return;
81
    }
82
83
    $arguments = [];
84
    foreach (static::rawGraphQLArguments() as $var) {
85
      if (isset($context[$var])) {
86
        $arguments[$var] = $context[$var] instanceof EntityInterface ? $context[$var]->id() : $context[$var];
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\EntityInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
87
      }
88
    }
89
90
91
    $queryResult = $this->env->getQueryProcessor()->processQuery('default:default', OperationParams::create([
0 ignored issues
show
Bug introduced by
The property env does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
92
      'query' => $query,
93
      'variables' => $arguments,
94
    ]));
95
96
    $build = [
97
      '#cache' => [
98
        'contexts' => $queryResult->getCacheContexts(),
99
        'tags' => $queryResult->getCacheTags(),
100
        'max-age' => $queryResult->getCacheMaxAge(),
101
      ],
102
    ];
103
104
    $this->env->getRenderer()->render($build);
105
106
    $context['graphql'] = [
107
      'data' => $queryResult->data,
108
      'errors' => $queryResult->errors,
109
    ];
110
111
    if ($this->env->isDebug()) {
112
      echo '<div class="graphql-twig-debug-wrapper" data-query="' . htmlspecialchars($this->getGraphQLQuery()). '" data-variables="' . htmlspecialchars(json_encode($arguments)) . '">';
113
      if (isset($context['graphql']['errors']) && $context['graphql']['errors']) {
114
        echo '<ul class="graphql-twig-errors">';
115
        foreach ($context['graphql']['errors'] as $error) {
116
          echo '<li>' . $error->message . '</li>';
117
        }
118
        echo '</ul>';
119
      }
120
    }
121
122
    parent::display($context, $blocks);
123
124
    if ($this->debug) {
125
      echo '</div>';
126
    }
127
  }
128
129
  /**
130
   * Recursively build the GraphQL query.
131
   *
132
   * Builds the templates GraphQL query by iterating through all included or
133
   * embedded templates recursively.
134
   */
135
  public function getGraphQLQuery() {
136
137
    $query = '';
138
    $includes = [];
139
140
    if ($this instanceof \Twig_Template) {
0 ignored issues
show
Bug introduced by
The class Twig_Template does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
141
      $query = $this->getGraphQLFragment();
142
143
      $includes = array_keys($this->getGraphQLIncludes());
144
145
      // Recursively collect all included fragments.
146
      $includes = array_map(function ($template) {
147
        return $this->loadTemplate($template)->getGraphQLFragment();
0 ignored issues
show
Bug introduced by
It seems like loadTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
148
      }, $includes);
149
150
      // Always add includes from parent templates.
151
      if ($parent = $this->getGraphQLParent()) {
152
        $includes += array_map(function ($template) {
153
          return $this->loadTemplate($template)->getGraphQLQuery();
0 ignored issues
show
Bug introduced by
It seems like loadTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
154
        }, array_keys($parent->getGraphQLIncludes()));
155
      }
156
    }
157
158
159
    return implode("\n", [-1 => $query] + $includes);
160
  }
161
162
  /**
163
   * Get the files parent template.
164
   *
165
   * @return \Twig_Template|null
166
   *   The parent template or null.
167
   */
168
  protected function getGraphQLParent() {
169
    return static::rawGraphQLParent() ? $this->loadTemplate(static::rawGraphQLParent()) : NULL;
0 ignored issues
show
Bug introduced by
It seems like loadTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
170
  }
171
172
  /**
173
   * Retrieve the files graphql fragment.
174
   *
175
   * @return string
176
   *   The GraphQL fragment.
177
   */
178
  public function getGraphQLFragment() {
179
    // If there is no query for this template, try to get one from the
180
    // parent template.
181
    if (!($query = static::rawGraphQLQuery()) && ($parent = $this->getGraphQLParent())) {
182
      $query = $parent->getGraphQLFragment();
183
    }
184
    return $query;
185
  }
186
187
  /**
188
   * Retrieve a list of all direct or indirect included templates.
189
   *
190
   * @return string[]
191
   *   The list of included templates.
192
   */
193
  public function getGraphQLIncludes() {
194
    $includes = array_flip(static::rawGraphQLIncludes());
195
    if ($includes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $includes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
196
      foreach ($includes as $include => $key) {
197
        $includes += $this->loadTemplate($include)->getGraphQLIncludes();
0 ignored issues
show
Bug introduced by
It seems like loadTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
198
      }
199
    }
200
    return $includes;
201
  }
202
}
203