Completed
Push — 8.x-1.x ( 037ca2...d31ec2 )
by Philipp
06:13
created

GraphQLTemplateTrait::display()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 46
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 46
rs 8.4751
cc 6
eloc 28
nc 6
nop 2
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
    $query = trim($this->getGraphQLQuery());
84
85
    if (!$query) {
86
      parent::display($context, $blocks);
87
      return;
88
    }
89
90
    $arguments = [];
91
    foreach (static::rawGraphQLArguments() as $var) {
92
      if (isset($context[$var])) {
93
        $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...
94
      }
95
    }
96
97
98
    $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...
99
      'query' => $query,
100
      'variables' => $arguments,
101
    ]));
102
103
    $build = [
104
      '#cache' => [
105
        'contexts' => $queryResult->getCacheContexts(),
106
        'tags' => $queryResult->getCacheTags(),
107
        'max-age' => $queryResult->getCacheMaxAge(),
108
      ],
109
    ];
110
111
    $this->env->getRenderer()->render($build);
112
113
    $context['graphql'] = [
114
      'data' => $queryResult->data,
115
      'errors' => $queryResult->errors,
116
      'debug' => $this->env->isDebug(),
117
      'query' => $query,
118
      'variables' => htmlspecialchars(json_encode($arguments)),
119
    ];
120
121
    parent::display($context, $blocks);
122
  }
123
124
  /**
125
   * Recursively build the GraphQL query.
126
   *
127
   * Builds the templates GraphQL query by iterating through all included or
128
   * embedded templates recursively.
129
   */
130
  public function getGraphQLQuery() {
131
132
    $query = '';
133
    $includes = [];
134
135
    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...
136
      $query = $this->getGraphQLFragment();
137
138
      $includes = array_keys($this->getGraphQLIncludes());
139
140
      // Recursively collect all included fragments.
141
      $includes = array_map(function ($template) {
142
        return $this->env->loadTemplate($template)->getGraphQLFragment();
143
      }, $includes);
144
145
      // Always add includes from parent templates.
146
      if ($parent = $this->getGraphQLParent()) {
147
        $includes += array_map(function ($template) {
148
          return $this->env->loadTemplate($template)->getGraphQLQuery();
149
        }, array_keys($parent->getGraphQLIncludes()));
150
      }
151
    }
152
153
154
    return implode("\n", [-1 => $query] + $includes);
155
  }
156
157
  /**
158
   * Get the files parent template.
159
   *
160
   * @return \Twig_Template|null
161
   *   The parent template or null.
162
   */
163
  protected function getGraphQLParent() {
164
    return static::rawGraphQLParent() ? $this->env->loadTemplate(static::rawGraphQLParent()) : NULL;
165
  }
166
167
  /**
168
   * Retrieve the files graphql fragment.
169
   *
170
   * @return string
171
   *   The GraphQL fragment.
172
   */
173
  public function getGraphQLFragment() {
174
    // If there is no query for this template, try to get one from the
175
    // parent template.
176
    if (!($query = static::rawGraphQLQuery()) && ($parent = $this->getGraphQLParent())) {
177
      $query = $parent->getGraphQLFragment();
178
    }
179
    return $query;
180
  }
181
182
  /**
183
   * Retrieve a list of all direct or indirect included templates.
184
   *
185
   * @param string[] $recursed
186
   *   The list of templates already recursed into. Used internally.
187
   *
188
   * @return string[]
189
   *   The list of included templates.
190
   */
191
  public function getGraphQLIncludes(&$recursed = []) {
192
193
    $includes = array_flip(static::rawGraphQLIncludes());
194
    foreach ($includes as $include => $key) {
195
      if (in_array($include, $recursed)) {
196
        continue;
197
      }
198
199
      $recursed[] = $include;
200
201
      // TODO: operate on template class instead.
202
      $includes += $this->env->loadTemplate($include)->getGraphQLIncludes($recursed);
203
    }
204
205
    return $includes;
206
  }
207
}
208