Completed
Push — 8.x-1.x ( d0852f...55caf8 )
by Janez
02:42
created

Modal::setUuid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * Contains \Drupal\entity_browser\Plugin\EntityBrowser\Display\Modal.
5
 */
6
7
namespace Drupal\entity_browser\Plugin\EntityBrowser\Display;
8
9
use Drupal\Component\Utility\Html;
10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Component\Uuid\UuidInterface;
12
use Drupal\Core\Ajax\OpenModalDialogCommand;
13
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Routing\RouteMatchInterface;
15
use Drupal\Core\Url;
16
use Drupal\entity_browser\DisplayAjaxInterface;
17
use Drupal\entity_browser\DisplayBase;
18
use Drupal\entity_browser\DisplayRouterInterface;
19
use Drupal\entity_browser\Events\Events;
20
use Drupal\entity_browser\Events\RegisterJSCallbacks;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
use Drupal\Core\Path\CurrentPathStack;
24
use Drupal\Core\Ajax\AjaxResponse;
25
use Drupal\Core\Ajax\CloseDialogCommand;
26
use Drupal\entity_browser\Ajax\SelectEntitiesCommand;
27
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
28
use Symfony\Component\HttpKernel\KernelEvents;
29
use Drupal\Core\Form\FormStateInterface;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpFoundation\Response;
32
33
/**
34
 * Presents entity browser in an Modal.
35
 *
36
 * @EntityBrowserDisplay(
37
 *   id = "modal",
38
 *   label = @Translation("Modal"),
39
 *   description = @Translation("Displays entity browser in a Modal."),
40
 *   uses_route = TRUE
41
 * )
42
 */
43
class Modal extends DisplayBase implements DisplayRouterInterface {
44
45
  /**
46
   * Current route match service.
47
   *
48
   * @var \Drupal\Core\Routing\RouteMatchInterface
49
   */
50
  protected $currentRouteMatch;
51
52
  /**
53
   * UUID generator interface.
54
   *
55
   * @var \Drupal\Component\Uuid\UuidInterface
56
   */
57
  protected $uuidGenerator;
58
59
  /**
60
   * Current path.
61
   *
62
   * @var \Drupal\Core\Path\CurrentPathStack
63
   */
64
  protected $currentPath;
65
66
  /**
67
   * UIID string.
68
   *
69
   * @var string
70
   */
71
  protected $uuid = NULL;
72
73
 /**
74
   * Current request.
75
   *
76
   * @var \Symfony\Component\HttpFoundation\Request
77
   */
78
  protected $request;
79
80
  /**
81
   * Constructs display plugin.
82
   *
83
   * @param array $configuration
84
   *   A configuration array containing information about the plugin instance.
85
   * @param string $plugin_id
86
   *   The plugin_id for the plugin instance.
87
   * @param mixed $plugin_definition
88
   *   The plugin implementation definition.
89
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
90
   *   Event dispatcher service.
91
   * @param \Drupal\Core\Routing\RouteMatchInterface
92
   *   The currently active route match object.
93
   * @param \Drupal\Component\Uuid\UuidInterface
94
   *   UUID generator interface.
95
   */
96
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, RouteMatchInterface $current_route_match, UuidInterface $uuid, CurrentPathStack $current_path, Request $request) {
97
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher);
98
    $this->currentRouteMatch = $current_route_match;
99
    $this->uuidGenerator = $uuid;
100
    $this->currentPath = $current_path;
101
    $this->request = $request;
102
  }
103
104
  /**
105
   * {@inheritdoc}
106
   */
107 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...
108
    return new static(
109
      $configuration,
110
      $plugin_id,
111
      $plugin_definition,
112
      $container->get('event_dispatcher'),
113
      $container->get('current_route_match'),
114
      $container->get('uuid'),
115
      $container->get('path.current'),
116
      $container->get('request_stack')->getCurrentRequest()
117
    );
118
  }
119
120
  /**
121
   * {@inheritdoc}
122
   */
123 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...
124
    return array(
125
      'width' => '650',
126
      'height' => '500',
127
      'link_text' => t('Select entities'),
128
    ) + parent::defaultConfiguration();
129
  }
130
131
  /**
132
   * {@inheritdoc}
133
   */
134
  public function displayEntityBrowser() {
135
    $uuid = $this->getUuid();
136
    /** @var \Drupal\entity_browser\Events\RegisterJSCallbacks $event */
137
    // TODO - $uuid is unused in this event but we need to pass it as
138
    // constructor expects it. See https://www.drupal.org/node/2600706 for more
139
    // info.
140
    $event_object = new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid);
141
    $event_object->registerCallback('Drupal.entityBrowser.selectionCompleted');
142
    $event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, $event_object );
143
    $original_path = $this->currentPath->getPath();
144
    return [
145
      '#theme_wrappers' => ['container'],
146
      'path' => [
147
        '#type' => 'hidden',
148
        '#value' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], [
149
          'query' => [
150
            'uuid' => $uuid,
151
            'original_path' => $original_path,
152
          ],
153
        ])->toString(),
154
      ],
155
      'open_modal' => [
156
        '#type' => 'submit',
157
        '#value' => $this->configuration['link_text'],
158
        '#limit_validation_errors' => [],
159
        '#submit' => [],
160
        '#name' => Html::getId('op_' . $this->configuration['entity_browser_id'] . '_' . $uuid),
161
        '#ajax' => [
162
          'callback' => [$this, 'openModal'],
163
          'event' => 'click',
164
        ],
165
        '#attributes' => [
166
          'data-uuid' => $uuid,
167
        ],
168
        '#attached' => [
169
          'library' => ['core/drupal.dialog.ajax',  'entity_browser/modal'],
170
          'drupalSettings' => [
171
            'entity_browser' => [
172
              'modal' => [
173
                $uuid => [
174
                  'uuid' => $uuid,
175
                  'js_callbacks' => $event->getCallbacks(),
176
                  'original_path' => $original_path,
177
                ],
178
              ],
179
            ],
180
          ],
181
        ],
182
      ],
183
    ];
184
  }
185
186
  /**
187
   * Generates the content and opens the modal.
188
   *
189
   * @param array $form
190
   *   The form array.
191
   * @param \Drupal\Core\Form\FormStateInterface $form_state
192
   *   The form state object.
193
   *
194
   * @return \Drupal\Core\Ajax\AjaxResponse
195
   *   An ajax response.
196
   */
197
  public function openModal(array &$form, FormStateInterface $form_state) {
198
    $triggering_element = $form_state->getTriggeringElement();
199
    $parents = $triggering_element['#parents'];
200
    array_pop($parents);
201
    $parents = array_merge($parents, ['path']);
202
    $input = $form_state->getUserInput();
203
    $src = NestedArray::getValue($input, $parents);
204
205
    $content = [
206
      '#type' => 'html_tag',
207
      '#tag' => 'iframe',
208
      '#attributes' => [
209
        'src' => $src,
210
        'width' => '100%',
211
        'height' => $this->configuration['height'] - 90,
212
        'frameborder' => 0,
213
        'style' => 'padding:',
214
        'name' => Html::cleanCssIdentifier('entity-browser-iframe-' . $this->configuration['entity_browser_id'])
215
      ],
216
    ];
217
    $html = drupal_render($content);
218
219
    $response = new AjaxResponse();
220
    $response->addCommand(new OpenModalDialogCommand($this->configuration['link_text'], $html, [
221
      'width' => $this->configuration['width'],
222
      'height' => $this->configuration['height'],
223
    ]));
224
    return $response;
225
  }
226
227
  /**
228
   * {@inheritdoc}
229
   */
230
  public function selectionCompleted(array $entities) {
231
    $this->entities = $entities;
232
    $this->eventDispatcher->addListener(KernelEvents::RESPONSE, [$this, 'propagateSelection']);
233
  }
234
235
  /**
236
   * {@inheritdoc}
237
   */
238
  public function addAjax(array &$form) {
239
    // Set a wrapper container to replace the form on ajax callback.
240
    $form['#prefix'] = '<div id="entity-browser-form">';
241
    $form['#suffix'] = '</div>';
242
243
    // Add the browser id to use in the FormAjaxController.
244
    $form['browser_id'] = array(
245
      '#type' => 'hidden',
246
      '#value' => $this->configuration['entity_browser_id'],
247
    );
248
249
    $form['actions']['submit']['#ajax'] = array(
250
      'callback' => array($this, 'widgetAjaxCallback'),
251
      'wrapper' => 'entity-browser-form',
252
    );
253
  }
254
255
  /**
256
   * Ajax callback for entity browser form.
257
   *
258
   * Allows the entity browser form to submit the form via ajax.
259
   *
260
   * @param array $form
261
   *   The form array.
262
   * @param FormStateInterface $form_state
263
   *   The form state object.
264
   *
265
   * @return \Drupal\Core\Ajax\AjaxResponse
266
   *   Response.
267
   */
268
  public function widgetAjaxCallback(array &$form, FormStateInterface $form_state) {
269
    // If we've got any validation error, print out the form again.
270
    if ($form_state->hasAnyErrors()) {
271
      return $form;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $form; (array) is incompatible with the return type documented by Drupal\entity_browser\Pl...dal::widgetAjaxCallback of type Drupal\Core\Ajax\AjaxResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
272
    }
273
274
    $commands = $this->getAjaxCommands($form_state);
275
    $response = new AjaxResponse();
276
    foreach ($commands as $command) {
277
      $response->addCommand($command);
278
    }
279
280
    return $response;
281
  }
282
283
  /**
284
   * Helper function to return commands to return in AjaxResponse.
285
   *
286
   * @return array
287
   *   An array of ajax commands.
288
   */
289
  public function getAjaxCommands(FormStateInterface $form_state) {
290
    $entities = array_map(function(EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $form_state->get(['entity_browser', 'selected_entities']));
291
292
    $commands = array();
293
    $commands[] = new SelectEntitiesCommand($this->uuid, $entities);
294
295
    return $commands;
296
  }
297
298
  /**
299
   * KernelEvents::RESPONSE listener.
300
   *
301
   * Intercepts default response and injects
302
   * response that will trigger JS to propagate selected entities upstream.
303
   *
304
   * @param FilterResponseEvent $event
305
   *   Response event.
306
   */
307 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...
308
    $render = [
309
      'labels' => [
310
        '#markup' => 'Labels: ' . implode(', ', array_map(function (EntityInterface $item) {return $item->label();}, $this->entities)),
311
        '#attached' => [
312
          'library' => ['entity_browser/modal_selection'],
313
          'drupalSettings' => [
314
            'entity_browser' => [
315
              'modal' => [
316
                'entities' => array_map(function (EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $this->entities),
317
                'uuid' => $this->request->query->get('uuid'),
318
              ],
319
            ],
320
          ],
321
        ],
322
      ],
323
    ];
324
325
    $event->setResponse(new Response(\Drupal::service('bare_html_page_renderer')->renderBarePage($render, 'Entity browser', 'entity_browser_propagation')));
326
  }
327
328
  /**
329
   * {@inheritdoc}
330
   */
331
  public function path() {
332
    return '/entity-browser/modal/' . $this->configuration['entity_browser_id'];
333
  }
334
335
  /**
336
   * {@inheritdoc}
337
   */
338
  public function getUuid() {
339
    if (empty($this->uuid)) {
340
      $this->uuid = $this->uuidGenerator->generate();
341
    }
342
    return $this->uuid;
343
  }
344
345
  /**
346
    * {@inheritdoc}
347
    */
348
  public function setUuid($uuid) {
349
    $this->uuid = $uuid;
350
  }
351
352
  /**
353
   * @inheritDoc
354
   */
355
  public function __sleep() {
356
    return array('configuration');
357
  }
358
359
}
360