Completed
Push — 8.x-1.x ( 3d8643...b71662 )
by Janez
03:27
created

Modal::selectionCompleted()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\entity_browser\Plugin\EntityBrowser\Display;
4
5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\NestedArray;
7
use Drupal\Component\Uuid\UuidInterface;
8
use Drupal\Core\Ajax\OpenModalDialogCommand;
9
use Drupal\Core\Entity\EntityInterface;
10
use Drupal\Core\Routing\RouteMatchInterface;
11
use Drupal\Core\Url;
12
use Drupal\entity_browser\DisplayBase;
13
use Drupal\entity_browser\DisplayRouterInterface;
14
use Drupal\entity_browser\Events\Events;
15
use Drupal\entity_browser\Events\RegisterJSCallbacks;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18
use Drupal\Core\Path\CurrentPathStack;
19
use Drupal\Core\Ajax\AjaxResponse;
20
use Drupal\entity_browser\Ajax\SelectEntitiesCommand;
21
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
22
use Symfony\Component\HttpKernel\KernelEvents;
23
use Drupal\Core\Form\FormStateInterface;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\HttpFoundation\Response;
26
use Drupal\entity_browser\Events\AlterEntityBrowserDisplayData;
27
28
/**
29
 * Presents entity browser in an Modal.
30
 *
31
 * @EntityBrowserDisplay(
32
 *   id = "modal",
33
 *   label = @Translation("Modal"),
34
 *   description = @Translation("Displays entity browser in a Modal."),
35
 *   uses_route = TRUE
36
 * )
37
 */
38
class Modal extends DisplayBase implements DisplayRouterInterface {
39
40
  /**
41
   * Current route match service.
42
   *
43
   * @var \Drupal\Core\Routing\RouteMatchInterface
44
   */
45
  protected $currentRouteMatch;
46
47
  /**
48
   * Current path.
49
   *
50
   * @var \Drupal\Core\Path\CurrentPathStack
51
   */
52
  protected $currentPath;
53
54
  /**
55
   * Current request.
56
   *
57
   * @var \Symfony\Component\HttpFoundation\Request
58
   */
59
  protected $request;
60
61
  /**
62
   * Constructs display plugin.
63
   *
64
   * @param array $configuration
65
   *   A configuration array containing information about the plugin instance.
66
   * @param string $plugin_id
67
   *   The plugin_id for the plugin instance.
68
   * @param mixed $plugin_definition
69
   *   The plugin implementation definition.
70
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
71
   *   Event dispatcher service.
72
   * @param \Drupal\Component\Uuid\UuidInterface
73
   *   UUID generator interface.
74
   * @param \Drupal\Core\Routing\RouteMatchInterface
75
   *   The currently active route match object.
76
   * @param \Symfony\Component\HttpFoundation\Request $request
77
   *   Current request.
78
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
79
   *   The current path.
80
   */
81 View Code Duplication
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, UuidInterface $uuid, RouteMatchInterface $current_route_match, CurrentPathStack $current_path, Request $request) {
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...
82
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $uuid);
83
    $this->currentRouteMatch = $current_route_match;
84
    $this->currentPath = $current_path;
85
    $this->request = $request;
86
  }
87
88
  /**
89
   * {@inheritdoc}
90
   */
91 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...
92
    return new static(
93
      $configuration,
94
      $plugin_id,
95
      $plugin_definition,
96
      $container->get('event_dispatcher'),
97
      $container->get('uuid'),
98
      $container->get('current_route_match'),
99
      $container->get('path.current'),
100
      $container->get('request_stack')->getCurrentRequest()
101
    );
102
  }
103
104
  /**
105
   * {@inheritdoc}
106
   */
107 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...
108
    return [
109
      'width' => '650',
110
      'height' => '500',
111
      'link_text' => t('Select entities'),
112
    ] + parent::defaultConfiguration();
113
  }
114
115
  /**
116
   * {@inheritdoc}
117
   */
118
  public function displayEntityBrowser(FormStateInterface $form_state) {
119
    $uuid = $this->getUuid();
120
    $js_event_object = new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid);
121
    $js_event_object->registerCallback('Drupal.entityBrowser.selectionCompleted');
122
    $js_event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, $js_event_object );
123
    $original_path = $this->currentPath->getPath();
124
    $data = [
125
      'query_parameters' => [
126
        'query' => [
127
          'uuid' => $uuid,
128
          'original_path' => $original_path,
129
        ],
130
      ],
131
      'attributes' => [
132
        'data-uuid' => $uuid,
133
      ],
134
    ];
135
    $event_object = new AlterEntityBrowserDisplayData($this->configuration['entity_browser_id'], $uuid, $this->getPluginDefinition(), $form_state, $data);
136
    $event = $this->eventDispatcher->dispatch(Events::ALTER_BROWSER_DISPLAY_DATA, $event_object);
137
    $data = $event->getData();
138
    return [
139
      '#theme_wrappers' => ['container'],
140
      'path' => [
141
        '#type' => 'hidden',
142
        '#value' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], $data['query_parameters'])->toString(),
143
      ],
144
      'open_modal' => [
145
        '#type' => 'submit',
146
        '#value' => $this->configuration['link_text'],
147
        '#limit_validation_errors' => [],
148
        '#submit' => [],
149
        '#name' => Html::getId('op_' . $this->configuration['entity_browser_id'] . '_' . $uuid),
150
        '#ajax' => [
151
          'callback' => [$this, 'openModal'],
152
          'event' => 'click',
153
        ],
154
        '#attributes' => $data['attributes'],
155
        '#attached' => [
156
          'library' => ['core/drupal.dialog.ajax',  'entity_browser/modal'],
157
          'drupalSettings' => [
158
            'entity_browser' => [
159
              'modal' => [
160
                $uuid => [
161
                  'uuid' => $uuid,
162
                  'js_callbacks' => $js_event->getCallbacks(),
163
                  'original_path' => $original_path,
164
                ],
165
              ],
166
            ],
167
          ],
168
        ],
169
      ],
170
    ];
171
  }
172
173
  /**
174
   * Generates the content and opens the modal.
175
   *
176
   * @param array $form
177
   *   The form array.
178
   * @param \Drupal\Core\Form\FormStateInterface $form_state
179
   *   The form state object.
180
   *
181
   * @return \Drupal\Core\Ajax\AjaxResponse
182
   *   An ajax response.
183
   */
184
  public function openModal(array &$form, FormStateInterface $form_state) {
185
    $triggering_element = $form_state->getTriggeringElement();
186
    $parents = $triggering_element['#parents'];
187
    array_pop($parents);
188
    $parents = array_merge($parents, ['path']);
189
    $input = $form_state->getUserInput();
190
    $src = NestedArray::getValue($input, $parents);
191
192
    $content = [
193
      '#type' => 'html_tag',
194
      '#tag' => 'iframe',
195
      '#attributes' => [
196
        'src' => $src,
197
        'width' => '100%',
198
        'height' => $this->configuration['height'] - 90,
199
        'frameborder' => 0,
200
        'style' => 'padding:0',
201
        'name' => Html::cleanCssIdentifier('entity-browser-iframe-' . $this->configuration['entity_browser_id'])
202
      ],
203
    ];
204
    $html = drupal_render($content);
205
206
    $response = new AjaxResponse();
207
    $response->addCommand(new OpenModalDialogCommand($this->configuration['link_text'], $html, [
208
      'width' => 'auto',
209
      'height' => 'auto',
210
      'maxWidth' => $this->configuration['width'],
211
      'maxHeight' => $this->configuration['height'],
212
      'fluid' => 1,
213
      'autoResize' => 0,
214
      'resizable' => 0,
215
    ]));
216
    return $response;
217
  }
218
219
  /**
220
   * {@inheritdoc}
221
   */
222
  public function selectionCompleted(array $entities) {
223
    $this->entities = $entities;
224
    $this->eventDispatcher->addListener(KernelEvents::RESPONSE, [$this, 'propagateSelection']);
225
  }
226
227
  /**
228
   * {@inheritdoc}
229
   */
230
  public function addAjax(array &$form) {
231
    // Set a wrapper container to replace the form on ajax callback.
232
    $form['#prefix'] = '<div id="entity-browser-form">';
233
    $form['#suffix'] = '</div>';
234
235
    // Add the browser id to use in the FormAjaxController.
236
    $form['browser_id'] = [
237
      '#type' => 'hidden',
238
      '#value' => $this->configuration['entity_browser_id'],
239
    ];
240
241
    $form['actions']['submit']['#ajax'] = [
242
      'callback' => [$this, 'widgetAjaxCallback'],
243
      'wrapper' => 'entity-browser-form',
244
    ];
245
  }
246
247
  /**
248
   * Ajax callback for entity browser form.
249
   *
250
   * Allows the entity browser form to submit the form via ajax.
251
   *
252
   * @param array $form
253
   *   The form array.
254
   * @param FormStateInterface $form_state
255
   *   The form state object.
256
   *
257
   * @return \Drupal\Core\Ajax\AjaxResponse
258
   *   Response.
259
   */
260
  public function widgetAjaxCallback(array &$form, FormStateInterface $form_state) {
261
    // If we've got any validation error, print out the form again.
262
    if ($form_state->hasAnyErrors()) {
263
      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...
264
    }
265
266
    $commands = $this->getAjaxCommands($form_state);
267
    $response = new AjaxResponse();
268
    foreach ($commands as $command) {
269
      $response->addCommand($command);
270
    }
271
272
    return $response;
273
  }
274
275
  /**
276
   * Helper function to return commands to return in AjaxResponse.
277
   *
278
   * @return array
279
   *   An array of ajax commands.
280
   */
281
  public function getAjaxCommands(FormStateInterface $form_state) {
282
    $entities = array_map(function(EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $form_state->get(['entity_browser', 'selected_entities']));
283
284
    $commands = [];
285
    $commands[] = new SelectEntitiesCommand($this->uuid, $entities);
286
287
    return $commands;
288
  }
289
290
  /**
291
   * KernelEvents::RESPONSE listener.
292
   *
293
   * Intercepts default response and injects
294
   * response that will trigger JS to propagate selected entities upstream.
295
   *
296
   * @param FilterResponseEvent $event
297
   *   Response event.
298
   */
299 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...
300
    $render = [
301
      'labels' => [
302
        '#markup' => 'Labels: ' . implode(', ', array_map(function (EntityInterface $item) {return $item->label();}, $this->entities)),
303
        '#attached' => [
304
          'library' => ['entity_browser/modal_selection'],
305
          'drupalSettings' => [
306
            'entity_browser' => [
307
              'modal' => [
308
                'entities' => array_map(function (EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $this->entities),
309
                'uuid' => $this->request->query->get('uuid'),
310
              ],
311
            ],
312
          ],
313
        ],
314
      ],
315
    ];
316
317
    $event->setResponse(new Response(\Drupal::service('bare_html_page_renderer')->renderBarePage($render, 'Entity browser', 'page')));
318
  }
319
320
  /**
321
   * {@inheritdoc}
322
   */
323
  public function path() {
324
    return '/entity-browser/modal/' . $this->configuration['entity_browser_id'];
325
  }
326
327
  /**
328
   * @inheritDoc
329
   */
330
  public function __sleep() {
331
    return ['configuration'];
332
  }
333
334
  /**
335
   * {@inheritdoc}
336
   */
337
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
338
    $configuration = $this->getConfiguration();
339
    $form['width'] = [
340
      '#type' => 'number',
341
      '#title' => $this->t('Width of the modal'),
342
      '#default_value' => $configuration['width'],
343
      '#description' => t('Empty value for responsive width.'),
344
    ];
345
    $form['height'] = [
346
      '#type' => 'number',
347
      '#title' => $this->t('Height of the modal'),
348
      '#default_value' => $configuration['height'],
349
      '#description' => t('Empty value for responsive height.'),
350
    ];
351
    $form['link_text'] = [
352
      '#type' => 'textfield',
353
      '#title' => $this->t('Link text'),
354
      '#default_value' => $configuration['link_text'],
355
    ];
356
    return $form;
357
  }
358
359
}
360