Completed
Push — 8.x-1.x ( b69bb3...47909d )
by Janez
03:09
created

IFrame::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 7
Ratio 100 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
dl 7
loc 7
rs 9.4285
c 3
b 0
f 1
cc 1
eloc 6
nc 1
nop 8

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
/**
4
 * Contains \Drupal\entity_browser\Plugin\EntityBrowser\Display\IFrame.
5
 */
6
7
namespace Drupal\entity_browser\Plugin\EntityBrowser\Display;
8
9
use Drupal\Component\Uuid\UuidInterface;
10
use Drupal\Core\Entity\EntityInterface;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\Core\Routing\RouteMatchInterface;
13
use Drupal\Core\Url;
14
use Drupal\entity_browser\DisplayBase;
15
use Drupal\entity_browser\DisplayRouterInterface;
16
use Drupal\entity_browser\Events\Events;
17
use Drupal\entity_browser\Events\RegisterJSCallbacks;
18
use Drupal\entity_browser\Events\AlterEntityBrowserDisplayData;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
use Drupal\Core\Path\CurrentPathStack;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
24
use Symfony\Component\HttpKernel\KernelEvents;
25
use Symfony\Component\HttpFoundation\Request;
26
27
/**
28
 * Presents entity browser in an iFrame.
29
 *
30
 * @EntityBrowserDisplay(
31
 *   id = "iframe",
32
 *   label = @Translation("iFrame"),
33
 *   description = @Translation("Displays entity browser in an iFrame."),
34
 *   uses_route = TRUE
35
 * )
36
 */
37
class IFrame extends DisplayBase implements DisplayRouterInterface {
38
39
  /**
40
   * Current route match service.
41
   *
42
   * @var \Drupal\Core\Routing\RouteMatchInterface
43
   */
44
  protected $currentRouteMatch;
45
46
  /**
47
   * UUID generator interface.
48
   *
49
   * @var \Drupal\Component\Uuid\UuidInterface
50
   */
51
  protected $uuidGenerator;
52
53
  /**
54
   * UIID string.
55
   *
56
   * @var string
57
   */
58
  protected $uuid = NULL;
59
60
  /**
61
   * Current path.
62
   *
63
   * @var \Drupal\Core\Path\CurrentPathStack
64
   */
65
  protected $currentPath;
66
67
  /**
68
   * Current request.
69
   *
70
   * @var \Symfony\Component\HttpFoundation\Request
71
   */
72
  protected $request;
73
74
  /**
75
   * Constructs display plugin.
76
   *
77
   * @param array $configuration
78
   *   A configuration array containing information about the plugin instance.
79
   * @param string $plugin_id
80
   *   The plugin_id for the plugin instance.
81
   * @param mixed $plugin_definition
82
   *   The plugin implementation definition.
83
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
84
   *   Event dispatcher service.
85
   * @param \Drupal\Core\Routing\RouteMatchInterface
86
   *   The currently active route match object.
87
   * @param \Drupal\Component\Uuid\UuidInterface
88
   *   UUID generator interface.
89
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
90
   *   The current path.
91
   */
92 View Code Duplication
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, RouteMatchInterface $current_route_match, UuidInterface $uuid, Request $request, CurrentPathStack $current_path) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher);
94
    $this->currentRouteMatch = $current_route_match;
95
    $this->uuidGenerator = $uuid;
96
    $this->request = $request;
97
    $this->currentPath = $current_path;
98
  }
99
100
  /**
101
   * {@inheritdoc}
102
   */
103 View Code Duplication
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
    return new static(
105
      $configuration,
106
      $plugin_id,
107
      $plugin_definition,
108
      $container->get('event_dispatcher'),
109
      $container->get('current_route_match'),
110
      $container->get('uuid'),
111
      $container->get('request_stack')->getCurrentRequest(),
112
      $container->get('path.current')
113
    );
114
  }
115
116
  /**
117
   * {@inheritdoc}
118
   */
119 View Code Duplication
  public function defaultConfiguration() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
    return array(
121
      'width' => '650',
122
      'height' => '500',
123
      'link_text' => t('Select entities'),
124
      'auto_open' => FALSE,
125
    ) + parent::defaultConfiguration();
126
  }
127
128
  /**
129
   * {@inheritdoc}
130
   */
131
  public function displayEntityBrowser(FormStateInterface $form_state) {
132
    $uuid = $this->getUuid();
133
    /** @var \Drupal\entity_browser\Events\RegisterJSCallbacks $event */
134
    // TODO - $uuid is unused in this event but we need to pass it as
135
    // constructor expects it. See https://www.drupal.org/node/2600706 for more
136
    // info.
137
    $js_event_object = new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid);
138
    $js_event_object->registerCallback('Drupal.entityBrowser.selectionCompleted');
139
    $callback_event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, $js_event_object);
140
    $original_path = $this->currentPath->getPath();
141
    $data = [
142
      'query_parameters' => [
143
        'query' => [
144
          'uuid' => $uuid,
145
          'original_path' => $original_path,
146
        ],
147
      ],
148
      'attributes' => [
149
        'href' => '#browser',
150
        'class' => ['entity-browser-handle', 'entity-browser-iframe'],
151
        'data-uuid' => $uuid,
152
        'data-original-path' => $original_path,
153
      ],
154
    ];
155
    $event_object = new AlterEntityBrowserDisplayData($this->configuration['entity_browser_id'], $uuid, $this->getPluginDefinition(), $form_state, $data);
156
    $event = $this->eventDispatcher->dispatch(Events::ALTER_BROWSER_DISPLAY_DATA, $event_object);
157
    $data = $event->getData();
158
    return [
159
      '#theme_wrappers' => ['container'],
160
      'link' => [
161
        '#type' => 'html_tag',
162
        '#tag' => 'a',
163
        '#value' => $this->configuration['link_text'],
164
        '#attributes' => $data['attributes'],
165
        '#attached' => [
166
          'library' => ['entity_browser/iframe'],
167
          'drupalSettings' => [
168
            'entity_browser' => [
169
              'iframe' => [
170
                $uuid => [
171
                  'src' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], $data['query_parameters'])
172
                    ->toString(),
173
                  'width' => $this->configuration['width'],
174
                  'height' => $this->configuration['height'],
175
                  'js_callbacks' => $callback_event->getCallbacks(),
176
                  'entity_browser_id' => $this->configuration['entity_browser_id'],
177
                  'auto_open' => $this->configuration['auto_open'],
178
                ],
179
              ],
180
            ],
181
          ]
182
        ],
183
      ],
184
    ];
185
  }
186
187
  /**
188
   * {@inheritdoc}
189
   */
190
  public function selectionCompleted(array $entities) {
191
    $this->entities = $entities;
192
    $this->eventDispatcher->addListener(KernelEvents::RESPONSE, [$this, 'propagateSelection']);
193
  }
194
195
  /**
196
   * KernelEvents::RESPONSE listener. Intercepts default response and injects
197
   * response that will trigger JS to propagate selected entities upstream.
198
   *
199
   * @param FilterResponseEvent $event
200
   *   Response event.
201
   */
202 View Code Duplication
  public function propagateSelection(FilterResponseEvent $event) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
    $render = [
204
      'labels' => [
205
        '#markup' => 'Labels: ' . implode(', ', array_map(function (EntityInterface $item) {return $item->label();}, $this->entities)),
206
        '#attached' => [
207
          'library' => ['entity_browser/iframe_selection'],
208
          'drupalSettings' => [
209
            'entity_browser' => [
210
              'iframe' => [
211
                'entities' => array_map(function (EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $this->entities),
212
                'uuid' => $this->request->query->get('uuid'),
213
              ],
214
            ],
215
          ],
216
        ],
217
      ],
218
    ];
219
220
    $event->setResponse(new Response(\Drupal::service('bare_html_page_renderer')->renderBarePage($render, 'Entity browser', 'page')));
221
  }
222
223
  /**
224
   * {@inheritdoc}
225
   */
226
  public function getUuid() {
227
    if (empty($this->uuid)) {
228
      $this->uuid = $this->uuidGenerator->generate();
229
    }
230
    return $this->uuid;
231
  }
232
233
  /**
234
    * {@inheritdoc}
235
    */
236
  public function setUuid($uuid) {
237
    $this->uuid = $uuid;
238
  }
239
240
  /**
241
   * {@inheritdoc}
242
   */
243
  public function path() {
244
    return '/entity-browser/iframe/' . $this->configuration['entity_browser_id'];
245
  }
246
247
  /**
248
   * {@inheritdoc}
249
   */
250
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
251
    $configuration = $this->getConfiguration();
252
    $form['width'] = [
253
      '#type' => 'number',
254
      '#title' => $this->t('Width of the iFrame'),
255
      '#min' => 1,
256
      '#default_value' => $configuration['width'],
257
    ];
258
259
    $form['height'] = [
260
      '#type' => 'number',
261
      '#title' => $this->t('Height of the iFrame'),
262
      '#min' => 1,
263
      '#default_value' => $configuration['height'],
264
    ];
265
266
    $form['link_text'] = [
267
      '#type' => 'textfield',
268
      '#title' => $this->t('Link text'),
269
      '#default_value' => $configuration['link_text'],
270
    ];
271
272
    $form['auto_open'] = [
273
      '#type' => 'checkbox',
274
      '#title' => $this->t('Auto open entity browser'),
275
      '#default_value' => $configuration['auto_open'],
276
    ];
277
278
    return $form;
279
  }
280
281
  /**
282
   * {@inheritdoc}
283
   */
284
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
285
    if ($form_state->getValue('width') <= 0) {
286
      $form_state->setError($form['width'], $this->t('Width must be greather than 0.'));
287
    }
288
    if ($form_state->getValue('height') <= 0) {
289
      $form_state->setError($form['height'], $this->t('Height must be greather than 0.'));
290
    }
291
  }
292
293
}
294