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

IFrame::defaultConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 8
Ratio 100 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 7
c 3
b 0
f 0
nc 1
nop 0
dl 8
loc 8
rs 9.4285
1
<?php
2
3
namespace Drupal\entity_browser\Plugin\EntityBrowser\Display;
4
5
use Drupal\Component\Uuid\UuidInterface;
6
use Drupal\Core\Entity\EntityInterface;
7
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\Core\Routing\RouteMatchInterface;
9
use Drupal\Core\Url;
10
use Drupal\entity_browser\DisplayBase;
11
use Drupal\entity_browser\DisplayRouterInterface;
12
use Drupal\entity_browser\Events\Events;
13
use Drupal\entity_browser\Events\RegisterJSCallbacks;
14
use Drupal\entity_browser\Events\AlterEntityBrowserDisplayData;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17
use Drupal\Core\Path\CurrentPathStack;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
20
use Symfony\Component\HttpKernel\KernelEvents;
21
use Symfony\Component\HttpFoundation\Request;
22
23
/**
24
 * Presents entity browser in an iFrame.
25
 *
26
 * @EntityBrowserDisplay(
27
 *   id = "iframe",
28
 *   label = @Translation("iFrame"),
29
 *   description = @Translation("Displays entity browser in an iFrame."),
30
 *   uses_route = TRUE
31
 * )
32
 */
33
class IFrame extends DisplayBase implements DisplayRouterInterface {
34
35
  /**
36
   * Current route match service.
37
   *
38
   * @var \Drupal\Core\Routing\RouteMatchInterface
39
   */
40
  protected $currentRouteMatch;
41
42
  /**
43
   * Current path.
44
   *
45
   * @var \Drupal\Core\Path\CurrentPathStack
46
   */
47
  protected $currentPath;
48
49
  /**
50
   * Current request.
51
   *
52
   * @var \Symfony\Component\HttpFoundation\Request
53
   */
54
  protected $request;
55
56
  /**
57
   * Constructs display plugin.
58
   *
59
   * @param array $configuration
60
   *   A configuration array containing information about the plugin instance.
61
   * @param string $plugin_id
62
   *   The plugin_id for the plugin instance.
63
   * @param mixed $plugin_definition
64
   *   The plugin implementation definition.
65
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
66
   *   Event dispatcher service.
67
   * @param \Drupal\Component\Uuid\UuidInterface
68
   *   UUID generator interface.
69
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
70
   *   The currently active route match object.
71
   * @param \Symfony\Component\HttpFoundation\Request $request
72
   *   Current request.
73
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
74
   *   The current path.
75
   */
76 View Code Duplication
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, UuidInterface $uuid, RouteMatchInterface $current_route_match, 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...
77
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $uuid);
78
    $this->currentRouteMatch = $current_route_match;
79
    $this->request = $request;
80
    $this->currentPath = $current_path;
81
  }
82
83
  /**
84
   * {@inheritdoc}
85
   */
86 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...
87
    return new static(
88
      $configuration,
89
      $plugin_id,
90
      $plugin_definition,
91
      $container->get('event_dispatcher'),
92
      $container->get('uuid'),
93
      $container->get('current_route_match'),
94
      $container->get('request_stack')->getCurrentRequest(),
95
      $container->get('path.current')
96
    );
97
  }
98
99
  /**
100
   * {@inheritdoc}
101
   */
102 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...
103
    return [
104
      'width' => '650',
105
      'height' => '500',
106
      'link_text' => t('Select entities'),
107
      'auto_open' => FALSE,
108
    ] + parent::defaultConfiguration();
109
  }
110
111
  /**
112
   * {@inheritdoc}
113
   */
114
  public function displayEntityBrowser(FormStateInterface $form_state) {
115
    $uuid = $this->getUuid();
116
    /** @var \Drupal\entity_browser\Events\RegisterJSCallbacks $event */
117
    $js_event_object = new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid);
118
    $js_event_object->registerCallback('Drupal.entityBrowser.selectionCompleted');
119
    $callback_event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, $js_event_object);
120
    $original_path = $this->currentPath->getPath();
121
    $data = [
122
      'query_parameters' => [
123
        'query' => [
124
          'uuid' => $uuid,
125
          'original_path' => $original_path,
126
        ],
127
      ],
128
      'attributes' => [
129
        'href' => '#browser',
130
        'class' => ['entity-browser-handle', 'entity-browser-iframe'],
131
        'data-uuid' => $uuid,
132
        'data-original-path' => $original_path,
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
      'link' => [
141
        '#type' => 'html_tag',
142
        '#tag' => 'a',
143
        '#value' => $this->configuration['link_text'],
144
        '#attributes' => $data['attributes'],
145
        '#attached' => [
146
          'library' => ['entity_browser/iframe'],
147
          'drupalSettings' => [
148
            'entity_browser' => [
149
              'iframe' => [
150
                $uuid => [
151
                  'src' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], $data['query_parameters'])
152
                    ->toString(),
153
                  'width' => $this->configuration['width'],
154
                  'height' => $this->configuration['height'],
155
                  'js_callbacks' => $callback_event->getCallbacks(),
156
                  'entity_browser_id' => $this->configuration['entity_browser_id'],
157
                  'auto_open' => $this->configuration['auto_open'],
158
                ],
159
              ],
160
            ],
161
          ]
162
        ],
163
      ],
164
    ];
165
  }
166
167
  /**
168
   * {@inheritdoc}
169
   */
170
  public function selectionCompleted(array $entities) {
171
    $this->entities = $entities;
172
    $this->eventDispatcher->addListener(KernelEvents::RESPONSE, [$this, 'propagateSelection']);
173
  }
174
175
  /**
176
   * KernelEvents::RESPONSE listener. Intercepts default response and injects
177
   * response that will trigger JS to propagate selected entities upstream.
178
   *
179
   * @param FilterResponseEvent $event
180
   *   Response event.
181
   */
182 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...
183
    $render = [
184
      'labels' => [
185
        '#markup' => 'Labels: ' . implode(', ', array_map(function (EntityInterface $item) {return $item->label();}, $this->entities)),
186
        '#attached' => [
187
          'library' => ['entity_browser/iframe_selection'],
188
          'drupalSettings' => [
189
            'entity_browser' => [
190
              'iframe' => [
191
                'entities' => array_map(function (EntityInterface $item) {return [$item->id(), $item->uuid(), $item->getEntityTypeId()];}, $this->entities),
192
                'uuid' => $this->request->query->get('uuid'),
193
              ],
194
            ],
195
          ],
196
        ],
197
      ],
198
    ];
199
200
    $event->setResponse(new Response(\Drupal::service('bare_html_page_renderer')->renderBarePage($render, 'Entity browser', 'page')));
201
  }
202
203
  /**
204
   * {@inheritdoc}
205
   */
206
  public function path() {
207
    return '/entity-browser/iframe/' . $this->configuration['entity_browser_id'];
208
  }
209
210
  /**
211
   * {@inheritdoc}
212
   */
213
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
214
    $configuration = $this->getConfiguration();
215
    $form['width'] = [
216
      '#type' => 'number',
217
      '#title' => $this->t('Width of the iFrame'),
218
      '#min' => 1,
219
      '#default_value' => $configuration['width'],
220
    ];
221
222
    $form['height'] = [
223
      '#type' => 'number',
224
      '#title' => $this->t('Height of the iFrame'),
225
      '#min' => 1,
226
      '#default_value' => $configuration['height'],
227
    ];
228
229
    $form['link_text'] = [
230
      '#type' => 'textfield',
231
      '#title' => $this->t('Link text'),
232
      '#default_value' => $configuration['link_text'],
233
    ];
234
235
    $form['auto_open'] = [
236
      '#type' => 'checkbox',
237
      '#title' => $this->t('Auto open entity browser'),
238
      '#default_value' => $configuration['auto_open'],
239
    ];
240
241
    return $form;
242
  }
243
244
  /**
245
   * {@inheritdoc}
246
   */
247
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
248
    if ($form_state->getValue('width') <= 0) {
249
      $form_state->setError($form['width'], $this->t('Width must be greather than 0.'));
250
    }
251
    if ($form_state->getValue('height') <= 0) {
252
      $form_state->setError($form['height'], $this->t('Height must be greather than 0.'));
253
    }
254
  }
255
256
}
257