2cfbb5554ea6d0098be2d44124d62486dbb2257f
[yaffs-website] / web / modules / contrib / dropzonejs / modules / eb_widget / src / Plugin / EntityBrowser / Widget / MediaEntityDropzoneJsEbWidget.php
1 <?php
2
3 namespace Drupal\dropzonejs_eb_widget\Plugin\EntityBrowser\Widget;
4
5 use Drupal\Core\Entity\EntityTypeManagerInterface;
6 use Drupal\Core\Extension\ModuleHandlerInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Link;
9 use Drupal\Core\Session\AccountProxyInterface;
10 use Drupal\Core\Utility\Token;
11 use Drupal\dropzonejs\DropzoneJsUploadSaveInterface;
12 use Drupal\dropzonejs\Events\DropzoneMediaEntityCreateEvent;
13 use Drupal\dropzonejs\Events\Events;
14 use Drupal\entity_browser\WidgetValidationManager;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
16 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17
18 /**
19  * Provides an Entity Browser widget that uploads uploads media entities.
20  *
21  * Widget will upload files and attach them to the media entity of bundle that
22  * is defined in the configuration.
23  *
24  * @EntityBrowserWidget(
25  *   id = "dropzonejs_media_entity",
26  *   label = @Translation("Media Entity DropzoneJS"),
27  *   description = @Translation("Adds DropzoneJS upload integration that saves Media entities."),
28  *   auto_select = TRUE
29  * )
30  */
31 class MediaEntityDropzoneJsEbWidget extends DropzoneJsEbWidget {
32
33   /**
34    * Module handler service.
35    *
36    * @var \Drupal\Core\Extension\ModuleHandlerInterface
37    */
38   protected $moduleHandler;
39
40   /**
41    * Constructs widget plugin.
42    *
43    * @param array $configuration
44    *   A configuration array containing information about the plugin instance.
45    * @param string $plugin_id
46    *   The plugin_id for the plugin instance.
47    * @param mixed $plugin_definition
48    *   The plugin implementation definition.
49    * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
50    *   Event dispatcher service.
51    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
52    *   The entity type manager service.
53    * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
54    *   The Widget Validation Manager service.
55    * @param \Drupal\dropzonejs\DropzoneJsUploadSaveInterface $dropzonejs_upload_save
56    *   The upload saving dropzonejs service.
57    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
58    *   The current user service.
59    * @param Token $token
60    *   The token service.
61    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
62    *   The module handler service.
63    */
64   public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, DropzoneJsUploadSaveInterface $dropzonejs_upload_save, AccountProxyInterface $current_user, Token $token, ModuleHandlerInterface $module_handler) {
65     parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager, $dropzonejs_upload_save, $current_user, $token);
66     $this->moduleHandler = $module_handler;
67   }
68
69   /**
70    * {@inheritdoc}
71    */
72   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
73     return new static(
74       $configuration,
75       $plugin_id,
76       $plugin_definition,
77       $container->get('event_dispatcher'),
78       $container->get('entity_type.manager'),
79       $container->get('plugin.manager.entity_browser.widget_validation'),
80       $container->get('dropzonejs.upload_save'),
81       $container->get('current_user'),
82       $container->get('token'),
83       $container->get('module_handler')
84     );
85   }
86
87   /**
88    * {@inheritdoc}
89    */
90   public function defaultConfiguration() {
91     return [
92       'media_entity_bundle' => '',
93     ] + parent::defaultConfiguration();
94   }
95
96   /**
97    * Returns the media bundle that this widget creates.
98    *
99    * @return \Drupal\media_entity\MediaBundleInterface
100    *   Media bundle.
101    */
102   protected function getBundle() {
103     return $this->entityTypeManager
104       ->getStorage('media_bundle')
105       ->load($this->configuration['media_entity_bundle']);
106   }
107
108   /**
109    * {@inheritdoc}
110    */
111   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
112     $form = parent::buildConfigurationForm($form, $form_state);
113
114     $form['media_entity_bundle'] = [
115       '#type' => 'select',
116       '#title' => $this->t('Media type'),
117       '#required' => TRUE,
118       '#description' => $this->t('The type of media entity to create from the uploaded file(s).'),
119     ];
120
121     $bundle = $this->getBundle();
122     if ($bundle) {
123       $form['media_entity_bundle']['#default_value'] = $bundle->id();
124     }
125
126     $bundles = $this->entityTypeManager->getStorage('media_bundle')->loadMultiple();
127
128     if (!empty($bundles)) {
129       foreach ($bundles as $bundle) {
130         $form['media_entity_bundle']['#options'][$bundle->id()] = $bundle->label();
131       }
132     }
133     else {
134       $form['media_entity_bundle']['#disabled'] = TRUE;
135       $form['media_entity_bundle']['#description'] = $this->t('You must @create_bundle before using this widget.', [
136         '@create_bundle' => Link::createFromRoute($this->t('create a media bundle'), 'media.bundle_add')->toString(),
137       ]);
138     }
139
140     return $form;
141   }
142
143   /**
144    * {@inheritdoc}
145    */
146   public function calculateDependencies() {
147     $dependencies = parent::calculateDependencies();
148
149     // Depend on the media bundle this widget creates.
150     $bundle = $this->getBundle();
151     $dependencies[$bundle->getConfigDependencyKey()][] = $bundle->getConfigDependencyName();
152     $dependencies['module'][] = 'media_entity';
153
154     return $dependencies;
155   }
156
157   /**
158    * {@inheritdoc}
159    */
160   public function prepareEntities(array $form, FormStateInterface $form_state) {
161     $entities = [];
162     $bundle = $this->getBundle();
163
164     foreach (parent::prepareEntities($form, $form_state) as $file) {
165       $entity_values = [
166         'bundle' => $bundle->id(),
167         $bundle->getTypeConfiguration()['source_field'] => $file,
168         'uid' => $this->currentUser->id(),
169         'status' => TRUE,
170         'type' => $bundle->getType()->getPluginId(),
171       ];
172       $this->moduleHandler->alter('dropzonejs_eb_media_entity_prepare', $entity_values, $file);
173       $entities[] = $this->entityTypeManager->getStorage('media')->create($entity_values);
174     }
175
176     return $entities;
177   }
178
179   /**
180    * {@inheritdoc}
181    */
182   public function submit(array &$element, array &$form, FormStateInterface $form_state) {
183     /** @var \Drupal\media_entity\MediaInterface[] $media_entities */
184     $media_entities = $this->prepareEntities($form, $form_state);
185     $source_field = $this->getBundle()->getTypeConfiguration()['source_field'];
186
187     foreach ($media_entities as &$media_entity) {
188       $file = $media_entity->$source_field->entity;
189       /** @var \Drupal\dropzonejs\Events\DropzoneMediaEntityCreateEvent $event */
190       $event = $this->eventDispatcher->dispatch(Events::MEDIA_ENTITY_CREATE, new DropzoneMediaEntityCreateEvent($media_entity, $file, $form, $form_state, $element));
191       $media_entity = $event->getMediaEntity();
192       // If we don't save file at this point Media entity creates another file
193       // entity with same uri for the thumbnail. That should probably be fixed
194       // in Media entity, but this workaround should work for now.
195       $media_entity->$source_field->entity->save();
196       $media_entity->save();
197     }
198
199     $this->selectEntities($media_entities, $form_state);
200     $this->clearFormValues($element, $form_state);
201   }
202
203 }