Completed
Pull Request — 8.x-1.x (#126)
by Janez
02:06
created

IFrame::buildConfigurationForm()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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