Completed
Push — 8.x-1.x ( 228956...9813da )
by Janez
03:15
created

Modal::addAjax()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 3
b 0
f 0
nc 1
nop 1
dl 0
loc 16
rs 9.4285
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\OpenDialogCommand;
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
    $field_name = $triggering_element['#parents'][0];
193
    $element_name = $this->configuration['entity_browser_id'];
194
    $content = [
195
      '#type' => 'html_tag',
196
      '#tag' => 'iframe',
197
      '#attributes' => [
198
        'src' => $src,
199
        'class' => 'entity-browser-modal-iframe',
200
        'width' => '100%',
201
        'height' => $this->configuration['height'] - 90,
202
        'frameborder' => 0,
203
        'style' => 'padding:0',
204
        'name' => 'entity_browser_iframe_' . Html::cleanCssIdentifier($element_name),
205
      ],
206
    ];
207
    $html = drupal_render($content);
208
209
    $response = new AjaxResponse();
210
    $response->addCommand(new OpenDialogCommand('#' . Html::getUniqueId($field_name . '-' . $element_name . '-dialog'), $this->configuration['link_text'], $html, [
211
      'width' => 'auto',
212
      'height' => 'auto',
213
      'modal' => TRUE,
214
      'maxWidth' => $this->configuration['width'],
215
      'maxHeight' => $this->configuration['height'],
216
      'fluid' => 1,
217
      'autoResize' => 0,
218
      'resizable' => 0,
219
    ]));
220
    return $response;
221
  }
222
223
  /**
224
   * {@inheritdoc}
225
   */
226
  public function selectionCompleted(array $entities) {
227
    $this->entities = $entities;
228
    $this->eventDispatcher->addListener(KernelEvents::RESPONSE, [$this, 'propagateSelection']);
229
  }
230
231
  /**
232
   * {@inheritdoc}
233
   */
234
  public function addAjax(array &$form) {
235
    // Set a wrapper container to replace the form on ajax callback.
236
    $form['#prefix'] = '<div id="entity-browser-form">';
237
    $form['#suffix'] = '</div>';
238
239
    // Add the browser id to use in the FormAjaxController.
240
    $form['browser_id'] = [
241
      '#type' => 'hidden',
242
      '#value' => $this->configuration['entity_browser_id'],
243
    ];
244
245
    $form['actions']['submit']['#ajax'] = [
246
      'callback' => [$this, 'widgetAjaxCallback'],
247
      'wrapper' => 'entity-browser-form',
248
    ];
249
  }
250
251
  /**
252
   * Ajax callback for entity browser form.
253
   *
254
   * Allows the entity browser form to submit the form via ajax.
255
   *
256
   * @param array $form
257
   *   The form array.
258
   * @param FormStateInterface $form_state
259
   *   The form state object.
260
   *
261
   * @return \Drupal\Core\Ajax\AjaxResponse
262
   *   Response.
263
   */
264
  public function widgetAjaxCallback(array &$form, FormStateInterface $form_state) {
265
    // If we've got any validation error, print out the form again.
266
    if ($form_state->hasAnyErrors()) {
267
      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...
268
    }
269
270
    $commands = $this->getAjaxCommands($form_state);
271
    $response = new AjaxResponse();
272
    foreach ($commands as $command) {
273
      $response->addCommand($command);
274
    }
275
276
    return $response;
277
  }
278
279
  /**
280
   * Helper function to return commands to return in AjaxResponse.
281
   *
282
   * @return array
283
   *   An array of ajax commands.
284
   */
285
  public function getAjaxCommands(FormStateInterface $form_state) {
286
    $entities = array_map(function(EntityInterface $item) {
287
      return [$item->id(), $item->uuid(), $item->getEntityTypeId()];
288
    }, $form_state->get(['entity_browser', 'selected_entities']));
289
290
    $commands = [];
291
    $commands[] = new SelectEntitiesCommand($this->uuid, $entities);
292
293
    return $commands;
294
  }
295
296
  /**
297
   * KernelEvents::RESPONSE listener.
298
   *
299
   * Intercepts default response and injects
300
   * response that will trigger JS to propagate selected entities upstream.
301
   *
302
   * @param FilterResponseEvent $event
303
   *   Response event.
304
   */
305 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...
306
    $render = [
307
      'labels' => [
308
        '#markup' => 'Labels: ' . implode(', ', array_map(function (EntityInterface $item) {
309
          return $item->label();
310
        }, $this->entities)),
311
        '#attached' => [
312
          'library' => ['entity_browser/modal_selection'],
313
          'drupalSettings' => [
314
            'entity_browser' => [
315
              'modal' => [
316
                'entities' => array_map(function (EntityInterface $item) {
317
                  return [$item->id(), $item->uuid(), $item->getEntityTypeId()];
318
                }, $this->entities),
319
                'uuid' => $this->request->query->get('uuid'),
320
              ],
321
            ],
322
          ],
323
        ],
324
      ],
325
    ];
326
327
    $event->setResponse(new Response(\Drupal::service('bare_html_page_renderer')->renderBarePage($render, 'Entity browser', 'page')));
328
  }
329
330
  /**
331
   * {@inheritdoc}
332
   */
333
  public function path() {
334
    return '/entity-browser/modal/' . $this->configuration['entity_browser_id'];
335
  }
336
337
  /**
338
   * @inheritDoc
339
   */
340
  public function __sleep() {
341
    return ['configuration'];
342
  }
343
344
  /**
345
   * {@inheritdoc}
346
   */
347
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
348
    $configuration = $this->getConfiguration();
349
    $form['width'] = [
350
      '#type' => 'number',
351
      '#title' => $this->t('Width of the modal'),
352
      '#default_value' => $configuration['width'],
353
      '#description' => t('Empty value for responsive width.'),
354
    ];
355
    $form['height'] = [
356
      '#type' => 'number',
357
      '#title' => $this->t('Height of the modal'),
358
      '#default_value' => $configuration['height'],
359
      '#description' => t('Empty value for responsive height.'),
360
    ];
361
    $form['link_text'] = [
362
      '#type' => 'textfield',
363
      '#title' => $this->t('Link text'),
364
      '#default_value' => $configuration['link_text'],
365
    ];
366
    return $form;
367
  }
368
369
}
370