Completed
Pull Request — 8.x-1.x (#20)
by
unknown
01:31
created

GraphQL::submitOptionsForm()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
cc 6
nc 6
nop 2
1
<?php
2
3
/**
4
 * @file
5
 * Contains \Drupal\graphql\Plugin\views\display
6
 */
7
8
namespace Drupal\graphql_views\Plugin\views\display;
9
10
use Drupal\Core\Cache\CacheableMetadata;
11
use Drupal\graphql\Utility\StringHelper;
12
use Drupal\views\Plugin\views\display\DisplayPluginBase;
13
use Drupal\Core\Form\FormStateInterface;
14
15
/**
16
 * Provides a display plugin for GraphQL views.
17
 *
18
 * @ViewsDisplay(
19
 *   id = "graphql",
20
 *   title = @Translation("GraphQL"),
21
 *   help = @Translation("Creates a GraphQL entity list display."),
22
 *   admin = @Translation("GraphQL"),
23
 *   graphql_display = TRUE,
24
 *   returns_response = TRUE
25
 * )
26
 */
27
class GraphQL extends DisplayPluginBase {
28
  /**
29
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAJAX.
30
   */
31
  protected $usesAJAX = FALSE;
32
33
  /**
34
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesPager.
35
   */
36
  protected $usesPager = FALSE;
37
38
  /**
39
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesMore.
40
   */
41
  protected $usesMore = FALSE;
42
43
  /**
44
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAreas.
45
   */
46
  protected $usesAreas = FALSE;
47
48
  /**
49
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesOptions.
50
   */
51
  protected $usesOptions = TRUE;
52
53
  /**
54
   * {@inheritdoc}
55
   */
56
  public function getType() {
57
    return 'graphql';
58
  }
59
60
  /**
61
   * {@inheritdoc}
62
   */
63
  public function usesFields() {
64
    return TRUE;
65
  }
66
67
  /**
68
   * {@inheritdoc}
69
   */
70
  public function usesExposed() {
71
    return TRUE;
72
  }
73
74
  /**
75
   * {@inheritdoc}
76
   */
77
  public function displaysExposed() {
78
    return FALSE;
79
  }
80
81
  /**
82
   * {@inheritdoc}
83
   */
84
  protected function defineOptions() {
85
    $options = parent::defineOptions();
86
87
    // Allow to attach the view to entity types / bundles.
88
    // Similar to the EVA module.
89
    $options['entity_type']['default'] = '';
90
    $options['bundles']['default'] = [];
91
92
    // Set the default plugins to 'graphql'.
93
    $options['style']['contains']['type']['default'] = 'graphql';
94
    $options['exposed_form']['contains']['type']['default'] = 'graphql';
95
    $options['row']['contains']['type']['default'] = 'graphql_entity';
96
97
    $options['defaults']['default']['style'] = FALSE;
98
    $options['defaults']['default']['exposed_form'] = FALSE;
99
    $options['defaults']['default']['row'] = FALSE;
100
101
    // Remove css/exposed form settings, as they are not used for the data display.
102
    unset($options['exposed_block']);
103
    unset($options['css_class']);
104
105
    $options['graphql_query_name'] = ['default' => ''];
106
    return $options;
107
  }
108
109
  /**
110
   * Get the user defined query name or the default one.
111
   *
112
   * @return string
113
   *   Query name.
114
   */
115
  public function getGraphQLQueryName() {
116
    return $this->getGraphQLName();
117
  }
118
119
  /**
120
   * Gets the result name.
121
   *
122
   * @return string
123
   *   Result name.
124
   */
125
  public function getGraphQLResultName() {
126
    return $this->getGraphQLName('result', TRUE);
127
  }
128
129
  /**
130
   * Gets the row name.
131
   *
132
   * @return string
133
   *   Row name.
134
   */
135
  public function getGraphQLRowName() {
136
    return $this->getGraphQLName('row', TRUE);
137
  }
138
139
  /**
140
   * Gets the filter input name..
141
   *
142
   * @return string
143
   *   Result name.
144
   */
145
  public function getGraphQLFilterInputName() {
146
    return $this->getGraphQLName('filter_input', TRUE);
147
  }
148
149
  /**
150
   * Gets the contextual filter input name.
151
   *
152
   * @return string
153
   *   Result name.
154
   */
155
  public function getGraphQLContextualFilterInputName() {
156
    return $this->getGraphQLName('contextual_filter_input', TRUE);
157
  }
158
159
  /**
160
   * Returns the formatted name.
161
   *
162
   * @param string|null $suffix
163
   *   Id suffix, eg. row, result.
164
   * @param bool $type
165
   *   Whether to use camel- or snake case. Uses camel case if TRUE. Defaults to
166
   *   FALSE.
167
   *
168
   * @return string The id.
169
   *   The id.
170
   */
171
  public function getGraphQLName($suffix = NULL, $type = FALSE) {
172
    $queryName = strip_tags($this->getOption('graphql_query_name'));
173
174
    if (empty($queryName)) {
175
      $viewId = $this->view->id();
176
      $displayId = $this->display['id'];
177
      $parts = [$viewId, $displayId, 'view', $suffix];
178
      return $type ? call_user_func_array([StringHelper::class, 'camelCase'], $parts) : call_user_func_array([StringHelper::class, 'propCase'], $parts);
179
    }
180
181
    $parts = array_filter([$queryName, $suffix]);
182
    return $type ? call_user_func_array([StringHelper::class, 'camelCase'], $parts) : call_user_func_array([StringHelper::class, 'propCase'], $parts);
183
  }
184
185
  /**
186
   * {@inheritdoc}
187
   */
188
  public function optionsSummary(&$categories, &$options) {
189
    parent::optionsSummary($categories, $options);
190
191
    unset($categories['title']);
192
    unset($categories['pager'], $categories['exposed'], $categories['access']);
193
194
    unset($options['show_admin_links'], $options['analyze-theme'], $options['link_display']);
195
    unset($options['show_admin_links'], $options['analyze-theme'], $options['link_display']);
196
197
    unset($options['title'], $options['access']);
198
    unset($options['exposed_block'], $options['css_class']);
199
    unset($options['query'], $options['group_by']);
200
201
    $categories['graphql'] = [
202
      'title' => $this->t('GraphQL'),
203
      'column' => 'second',
204
      'build' => [
205
        '#weight' => -10,
206
      ],
207
    ];
208
209
    $options['graphql_query_name'] = [
210
      'category' => 'graphql',
211
      'title' => $this->t('Query name'),
212
      'value' => views_ui_truncate($this->getGraphQLQueryName(), 24),
213
    ];
214
215
    if ($entity_type = $this->getOption('entity_type')) {
216
      $entity_info = \Drupal::entityManager()->getDefinition($entity_type);
217
      $type_name = $entity_info->get('label');
218
219
      $bundle_names = [];
220
      $bundle_info = \Drupal::entityManager()->getBundleInfo($entity_type);
221
      foreach ($this->getOption('bundles') as $bundle) {
222
        $bundle_names[] = $bundle_info[$bundle]['label'];
223
      }
224
    }
225
226
    $options['entity_type'] = [
227
      'category' => 'graphql',
228
      'title' => $this->t('Entity type'),
229
      'value' => empty($type_name) ? $this->t('None') : $type_name,
230
    ];
231
232
    $options['bundles'] = [
233
      'category' => 'graphql',
234
      'title' => $this->t('Bundles'),
235
      'value' => empty($bundle_names) ? $this->t('All') : implode(', ', $bundle_names),
236
    ];
237
238
  }
239
240
  /**
241
   * {@inheritdoc}
242
   */
243
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
244
    parent::buildOptionsForm($form, $form_state);
245
246
    switch ($form_state->get('section')) {
247
      case 'graphql_query_name':
248
        $form['#title'] .= $this->t('Query name');
249
        $form['graphql_query_name'] = [
250
          '#type' => 'textfield',
251
          '#description' => $this->t('This will be the graphQL query name.'),
252
          '#default_value' => $this->getGraphQLQueryName(),
253
        ];
254
        break;
255
256
      case 'entity_type':
257
        $entity_info = \Drupal::entityManager()->getDefinitions();
258
        $entity_names = [NULL => $this->t('None')];
259
        foreach ($entity_info as $type => $info) {
260
          // is this a content/front-facing entity?
261
          if ($info instanceof \Drupal\Core\Entity\ContentEntityType) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\ContentEntityType 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...
262
            $entity_names[$type] = $info->get('label');
263
          }
264
        }
265
266
        $form['#title'] .= $this->t('Entity type');
267
        $form['entity_type'] = [
268
          '#type' => 'radios',
269
          '#required' => FALSE,
270
          '#title' => $this->t('Attach this display to the following entity type'),
271
          '#options' => $entity_names,
272
          '#default_value' => $this->getOption('entity_type'),
273
        ];
274
        break;
275
276
      case 'bundles':
277
        $options = [];
278
        $entity_type = $this->getOption('entity_type');
279
        foreach (\Drupal::entityManager()->getBundleInfo($entity_type) as $bundle => $info) {
280
          $options[$bundle] = $info['label'];
281
        }
282
        $form['#title'] .= $this->t('Bundles');
283
        $form['bundles'] = [
284
          '#type' => 'checkboxes',
285
          '#title' => $this->t('Attach this display to the following bundles.  If no bundles are selected, the display will be attached to all.'),
286
          '#options' => $options,
287
          '#default_value' => $this->getOption('bundles'),
288
        ];
289
        break;
290
    }
291
  }
292
293
  /**
294
   * {@inheritdoc}
295
   */
296
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
297
    parent::submitOptionsForm($form, $form_state);
298
    $section = $form_state->get('section');
299
    switch ($section) {
300
      case 'graphql_query_name':
301
        $this->setOption($section, $form_state->getValue($section));
302
        break;
303
      case 'entity_type':
304
        $new_entity = $form_state->getValue('entity_type');
305
        $old_entity = $this->getOption('entity_type');
306
        $this->setOption('entity_type', $new_entity);
307
308
        if ($new_entity != $old_entity) {
309
          // Each entity has its own list of bundles and view modes. If there's
310
          // only one on the new type, we can select it automatically. Otherwise
311
          // we need to wipe the options and start over.
312
          $new_entity_info = \Drupal::entityManager()->getDefinition($new_entity);
0 ignored issues
show
Unused Code introduced by
$new_entity_info is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
313
          $new_bundles_keys = \Drupal::entityManager()->getBundleInfo($new_entity);
314
          $new_bundles = array();
315
          if (count($new_bundles_keys) == 1) {
316
            $new_bundles[] = $new_bundles_keys[0];
317
          }
318
          $this->setOption('bundles', $new_bundles);
319
        }
320
        break;
321
      case 'bundles':
322
        $this->setOption('bundles', array_values(array_filter($form_state->getValue('bundles'))));
323
        break;
324
    }
325
  }
326
327
  /**
328
   * {@inheritdoc}
329
   */
330
  public function execute() {
331
    return $this->view->execute();
332
  }
333
334
  /**
335
   * {@inheritdoc}
336
   */
337
  public function render() {
338
    $rows = (!empty($this->view->result) || $this->view->style_plugin->evenEmpty()) ? $this->view->style_plugin->render($this->view->result) : [];
339
340
    // Apply the cache metadata from the display plugin. This comes back as a
341
    // cache render array so we have to transform it back afterwards.
342
    $this->applyDisplayCacheabilityMetadata($this->view->element);
343
344
    return [
345
      'view' => $this->view,
346
      'rows' => $rows,
347
      'cache' => CacheableMetadata::createFromRenderArray($this->view->element),
348
    ];
349
  }
350
}
351