GraphQLTemplateTrait::display()   F
last analyzed

Complexity

Conditions 17
Paths 259

Size

Total Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
nc 259
nop 2
dl 0
loc 90
rs 3.1347
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
   * Inject the query processor.
49
   *
50
   * @param \Drupal\graphql\GraphQL\Execution\QueryProcessor $queryProcessor
51
   *   The query processor instance.
52
   */
53
  public function setQueryProcessor(QueryProcessor $queryProcessor) {
54
    $this->queryProcessor = $queryProcessor;
55
  }
56
57
  /**
58
   * {@inheritdoc}
59
   */
60
  public function display(array $context, array $blocks = array()) {
61
    if (!static::hasGraphQLOperations()) {
62
      parent::display($context, $blocks);
63
      return;
64
    }
65
66
    if (isset($context['graphql_arguments'])) {
67
      $context = $context['graphql_arguments'];
68
    }
69
70
    $query = trim($this->getGraphQLQuery());
71
72
    if (!$query) {
73
      parent::display($context, $blocks);
74
      return;
75
    }
76
77
    $arguments = [];
78
    foreach (static::rawGraphQLArguments() as $var) {
79
      if (isset($context[$var])) {
80
        $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...
81
      }
82
    }
83
84
85
    $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...
86
      'query' => $query,
87
      'variables' => $arguments,
88
    ]));
89
90
    $build = [
91
      '#cache' => [
92
        'contexts' => $queryResult->getCacheContexts(),
93
        'tags' => $queryResult->getCacheTags(),
94
        'max-age' => $queryResult->getCacheMaxAge(),
95
      ],
96
    ];
97
98
    $this->env->getRenderer()->render($build);
99
100
    $config = \Drupal::config('graphql_twig.settings');
101
    $debug_placement = $config->get('debug_placement');
102
103
    if ($this->env->isDebug() && \Drupal::currentUser()->hasPermission('use graphql explorer')) {
104
      // Auto-attach the debug assets if necessary.
105
      $template_attached = ['#attached' => ['library' => ['graphql_twig/debug']]];
106
      $this->env->getRenderer()->render($template_attached);
107
    }
108
109
    if ($this->env->isDebug() && $debug_placement == 'wrapped') {
110
      printf(
111
        '<div class="%s" data-graphql-query="%s" data-graphql-variables="%s">',
112
        'graphql-twig-debug-wrapper',
113
        htmlspecialchars($query),
114
        htmlspecialchars(json_encode($arguments))
115
      );
116
    }
117
118
    if ($queryResult->errors) {
119
      print('<ul class="graphql-twig-errors">');
120
      foreach ($queryResult->errors as $error) {
121
        printf('<li>%s</li>', $error->message);
122
      }
123
      print('</ul>');
124
    }
125
    else {
126
      $context['graphql'] = $queryResult->data;
127
      if ($this->env->isDebug() && $debug_placement == 'inside') {
128
        $context['graphql_debug'] = [
129
          '#markup' => sprintf(
130
            '<div class="graphql-twig-debug-child"><div class="%s" data-graphql-query="%s" data-graphql-variables="%s"></div></div>',
131
            'graphql-twig-debug-wrapper',
132
            htmlspecialchars($query),
133
            htmlspecialchars(json_encode($arguments))
134
          ),
135
        ];
136
137
        // Add the debug parent class to the element.
138
        /** @var \Drupal\Core\Template\Attribute $attributes */
139
        $attributes = $context['attributes'];
140
        $attributes->addClass('graphql-twig-debug-parent');
141
      }
142
143
      parent::display($context, $blocks);
144
    }
145
146
    if ($this->env->isDebug() && $debug_placement == 'wrapped') {
147
      print('</div>');
148
    }
149
  }
150
151
  /**
152
   * Recursively build the GraphQL query.
153
   *
154
   * Builds the templates GraphQL query by iterating through all included or
155
   * embedded templates recursively.
156
   */
157
  public function getGraphQLQuery() {
158
159
    $query = '';
160
    $includes = [];
161
162
    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...
163
      $query = $this->getGraphQLFragment();
164
165
      $includes = array_keys($this->getGraphQLIncludes());
166
167
      // Recursively collect all included fragments.
168
      $includes = array_map(function ($template) {
169
        return $this->env->loadTemplate($template)->getGraphQLFragment();
170
      }, $includes);
171
172
      // Always add includes from parent templates.
173
      if ($parent = $this->getGraphQLParent()) {
174
        $includes += array_map(function ($template) {
175
          return $this->env->loadTemplate($template)->getGraphQLQuery();
176
        }, array_keys($parent->getGraphQLIncludes()));
177
      }
178
    }
179
180
181
    return implode("\n", [-1 => $query] + $includes);
182
  }
183
184
  /**
185
   * Get the files parent template.
186
   *
187
   * @return \Twig_Template|null
188
   *   The parent template or null.
189
   */
190
  protected function getGraphQLParent() {
191
    return static::rawGraphQLParent() ? $this->env->loadTemplate(static::rawGraphQLParent()) : NULL;
192
  }
193
194
  /**
195
   * Retrieve the files graphql fragment.
196
   *
197
   * @return string
198
   *   The GraphQL fragment.
199
   */
200
  public function getGraphQLFragment() {
201
    // If there is no query for this template, try to get one from the
202
    // parent template.
203
    if (!($query = static::rawGraphQLQuery()) && ($parent = $this->getGraphQLParent())) {
204
      $query = $parent->getGraphQLFragment();
205
    }
206
    return $query;
207
  }
208
209
  /**
210
   * Retrieve a list of all direct or indirect included templates.
211
   *
212
   * @param string[] $recursed
213
   *   The list of templates already recursed into. Used internally.
214
   *
215
   * @return string[]
216
   *   The list of included templates.
217
   */
218
  public function getGraphQLIncludes(&$recursed = []) {
219
220
    $includes = array_flip(static::rawGraphQLIncludes());
221
    foreach ($includes as $include => $key) {
222
      if (in_array($include, $recursed)) {
223
        continue;
224
      }
225
226
      $recursed[] = $include;
227
228
      // TODO: operate on template class instead.
229
      $includes += $this->env->loadTemplate($include)->getGraphQLIncludes($recursed);
230
    }
231
232
    return $includes;
233
  }
234
}
235