Completed
Push — 8.x-1.x ( c7f9df...c0c90f )
by Philipp
01:32
created

GraphQLTemplateTrait::display()   C

Complexity

Conditions 11
Paths 67

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 67
nop 2
dl 0
loc 64
rs 6.6387
c 0
b 0
f 0

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\Core\Template\TwigEnvironment;
7
use Drupal\graphql\GraphQL\Execution\QueryProcessor;
8
use GraphQL\Server\OperationParams;
9
10
/**
11
 * Trait that will be attached to all GraphQL enabled Twig templates.
12
 */
13
trait GraphQLTemplateTrait {
14
15
  /**
16
   * @return bool
17
   */
18
  abstract public static function hasGraphQLOperations();
19
20
  /**
21
   * @var string
22
   */
23
  abstract public static function rawGraphQLQuery();
24
25
  /**
26
   * @return string
27
   */
28
  abstract public static function rawGraphQLParent();
29
30
  /**
31
   * @return string[]
32
   */
33
  abstract public static function rawGraphQLIncludes();
34
35
  /**
36
   * @return string[]
37
   */
38
  abstract public static function rawGraphQLArguments();
39
40
  /**
41
   * The GraphQL query processor.
42
   *
43
   * @var \Drupal\graphql\GraphQL\Execution\QueryProcessor
44
   */
45
  protected $queryProcessor;
46
47
  /**
48
   * Debug mode flag.
49
   *
50
   * @var bool
51
   */
52
  protected $debug = FALSE;
53
54
  /**
55
   * Inject the query processor.
56
   *
57
   * @param \Drupal\graphql\GraphQL\Execution\QueryProcessor $queryProcessor
58
   *   The query processor instance.
59
   */
60
  public function setQueryProcessor(QueryProcessor $queryProcessor) {
61
    $this->queryProcessor = $queryProcessor;
62
  }
63
64
  /**
65
   * Set debug mode for this template.
66
   *
67
   * @param bool $debug
68
   *   Boolean flag for debug mode.
69
   */
70
  public function setDebug($debug) {
71
    $this->debug = $debug;
72
  }
73
74
  /**
75
   * {@inheritdoc}
76
   */
77
  public function display(array $context, array $blocks = array()) {
78
    if (!static::hasGraphQLOperations()) {
79
      parent::display($context, $blocks);
80
      return;
81
    }
82
83
    if (isset($context['graphql_arguments'])) {
84
      $context = $context['graphql_arguments'];
85
    }
86
87
    $query = trim($this->getGraphQLQuery());
88
89
    if (!$query) {
90
      parent::display($context, $blocks);
91
      return;
92
    }
93
94
    $arguments = [];
95
    foreach (static::rawGraphQLArguments() as $var) {
96
      if (isset($context[$var])) {
97
        $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...
98
      }
99
    }
100
101
102
    $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...
103
      'query' => $query,
104
      'variables' => $arguments,
105
    ]));
106
107
    $build = [
108
      '#cache' => [
109
        'contexts' => $queryResult->getCacheContexts(),
110
        'tags' => $queryResult->getCacheTags(),
111
        'max-age' => $queryResult->getCacheMaxAge(),
112
      ],
113
    ];
114
115
    $this->env->getRenderer()->render($build);
116
117
    if ($this->debug) {
118
      echo printf(
119
        '<div class="%s" data-graphql-query="%s" data-graphql-variables="%s">',
120
        'graphql-twig-debug-wrapper',
121
        htmlspecialchars(json_encode($arguments))
122
      );
123
    }
124
125
    if ($queryResult->errors) {
126
      print('<ul class="graphql-twig-errors">');
127
      foreach ($queryResult->errors as $error) {
128
        printf('<li>%s</li>', $error->message);
129
      }
130
      print('</ul>');
131
    }
132
    else {
133
      $context['graphql'] = $queryResult->data;
134
      parent::display($context, $blocks);
135
    }
136
137
    if ($this->debug) {
138
      print('</div>');
139
    }
140
  }
141
142
  /**
143
   * Recursively build the GraphQL query.
144
   *
145
   * Builds the templates GraphQL query by iterating through all included or
146
   * embedded templates recursively.
147
   */
148
  public function getGraphQLQuery() {
149
150
    $query = '';
151
    $includes = [];
152
153
    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...
154
      $query = $this->getGraphQLFragment();
155
156
      $includes = array_keys($this->getGraphQLIncludes());
157
158
      // Recursively collect all included fragments.
159
      $includes = array_map(function ($template) {
160
        return $this->env->loadTemplate($template)->getGraphQLFragment();
161
      }, $includes);
162
163
      // Always add includes from parent templates.
164
      if ($parent = $this->getGraphQLParent()) {
165
        $includes += array_map(function ($template) {
166
          return $this->env->loadTemplate($template)->getGraphQLQuery();
167
        }, array_keys($parent->getGraphQLIncludes()));
168
      }
169
    }
170
171
172
    return implode("\n", [-1 => $query] + $includes);
173
  }
174
175
  /**
176
   * Get the files parent template.
177
   *
178
   * @return \Twig_Template|null
179
   *   The parent template or null.
180
   */
181
  protected function getGraphQLParent() {
182
    return static::rawGraphQLParent() ? $this->env->loadTemplate(static::rawGraphQLParent()) : NULL;
183
  }
184
185
  /**
186
   * Retrieve the files graphql fragment.
187
   *
188
   * @return string
189
   *   The GraphQL fragment.
190
   */
191
  public function getGraphQLFragment() {
192
    // If there is no query for this template, try to get one from the
193
    // parent template.
194
    if (!($query = static::rawGraphQLQuery()) && ($parent = $this->getGraphQLParent())) {
195
      $query = $parent->getGraphQLFragment();
196
    }
197
    return $query;
198
  }
199
200
  /**
201
   * Retrieve a list of all direct or indirect included templates.
202
   *
203
   * @param string[] $recursed
204
   *   The list of templates already recursed into. Used internally.
205
   *
206
   * @return string[]
207
   *   The list of included templates.
208
   */
209
  public function getGraphQLIncludes(&$recursed = []) {
210
211
    $includes = array_flip(static::rawGraphQLIncludes());
212
    foreach ($includes as $include => $key) {
213
      if (in_array($include, $recursed)) {
214
        continue;
215
      }
216
217
      $recursed[] = $include;
218
219
      // TODO: operate on template class instead.
220
      $includes += $this->env->loadTemplate($include)->getGraphQLIncludes($recursed);
221
    }
222
223
    return $includes;
224
  }
225
}
226