MediaSourceBase.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. namespace Drupal\media;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Entity\EntityFieldManagerInterface;
  5. use Drupal\Core\Entity\EntityTypeManagerInterface;
  6. use Drupal\Core\Field\FieldTypePluginManagerInterface;
  7. use Drupal\Core\Form\FormStateInterface;
  8. use Drupal\Core\Config\ConfigFactoryInterface;
  9. use Drupal\Core\Plugin\PluginBase;
  10. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. /**
  13. * Base implementation of media source plugin.
  14. */
  15. abstract class MediaSourceBase extends PluginBase implements MediaSourceInterface, ContainerFactoryPluginInterface {
  16. /**
  17. * Plugin label.
  18. *
  19. * @var string
  20. */
  21. protected $label;
  22. /**
  23. * The entity type manager service.
  24. *
  25. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  26. */
  27. protected $entityTypeManager;
  28. /**
  29. * The entity field manager service.
  30. *
  31. * @var \Drupal\Core\Entity\EntityFieldManagerInterface
  32. */
  33. protected $entityFieldManager;
  34. /**
  35. * The field type plugin manager service.
  36. *
  37. * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
  38. */
  39. protected $fieldTypeManager;
  40. /**
  41. * The config factory service.
  42. *
  43. * @var \Drupal\Core\Config\ConfigFactoryInterface
  44. */
  45. protected $configFactory;
  46. /**
  47. * Constructs a new class instance.
  48. *
  49. * @param array $configuration
  50. * A configuration array containing information about the plugin instance.
  51. * @param string $plugin_id
  52. * The plugin_id for the plugin instance.
  53. * @param mixed $plugin_definition
  54. * The plugin implementation definition.
  55. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  56. * Entity type manager service.
  57. * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
  58. * Entity field manager service.
  59. * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
  60. * The field type plugin manager service.
  61. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  62. * The config factory service.
  63. */
  64. public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, ConfigFactoryInterface $config_factory) {
  65. parent::__construct($configuration, $plugin_id, $plugin_definition);
  66. $this->entityTypeManager = $entity_type_manager;
  67. $this->entityFieldManager = $entity_field_manager;
  68. $this->fieldTypeManager = $field_type_manager;
  69. $this->configFactory = $config_factory;
  70. // Add the default configuration of the media source to the plugin.
  71. $this->setConfiguration($configuration);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  77. return new static(
  78. $configuration,
  79. $plugin_id,
  80. $plugin_definition,
  81. $container->get('entity_type.manager'),
  82. $container->get('entity_field.manager'),
  83. $container->get('plugin.manager.field.field_type'),
  84. $container->get('config.factory')
  85. );
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function setConfiguration(array $configuration) {
  91. $this->configuration = NestedArray::mergeDeep(
  92. $this->defaultConfiguration(),
  93. $configuration
  94. );
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. public function getConfiguration() {
  100. return $this->configuration;
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function defaultConfiguration() {
  106. return [
  107. 'source_field' => '',
  108. ];
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function getMetadata(MediaInterface $media, $attribute_name) {
  114. switch ($attribute_name) {
  115. case 'default_name':
  116. return 'media:' . $media->bundle() . ':' . $media->uuid();
  117. case 'thumbnail_uri':
  118. $default_thumbnail_filename = $this->pluginDefinition['default_thumbnail_filename'];
  119. return $this->configFactory->get('media.settings')->get('icon_base_uri') . '/' . $default_thumbnail_filename;
  120. }
  121. return NULL;
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function calculateDependencies() {
  127. return [];
  128. }
  129. /**
  130. * Get the source field options for the media type form.
  131. *
  132. * This returns all fields related to media entities, filtered by the allowed
  133. * field types in the media source annotation.
  134. *
  135. * @return string[]
  136. * A list of source field options for the media type form.
  137. */
  138. protected function getSourceFieldOptions() {
  139. // If there are existing fields to choose from, allow the user to reuse one.
  140. $options = [];
  141. foreach ($this->entityFieldManager->getFieldStorageDefinitions('media') as $field_name => $field) {
  142. $allowed_type = in_array($field->getType(), $this->pluginDefinition['allowed_field_types'], TRUE);
  143. if ($allowed_type && !$field->isBaseField()) {
  144. $options[$field_name] = $field->getLabel();
  145. }
  146. }
  147. return $options;
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  153. $options = $this->getSourceFieldOptions();
  154. $form['source_field'] = [
  155. '#type' => 'select',
  156. '#title' => $this->t('Field with source information'),
  157. '#default_value' => $this->configuration['source_field'],
  158. '#empty_option' => $this->t('- Create -'),
  159. '#options' => $options,
  160. '#description' => $this->t('Select the field that will store essential information about the media item. If "Create" is selected a new field will be automatically created.'),
  161. ];
  162. if (!$options && $form_state->get('operation') === 'add') {
  163. $form['source_field']['#access'] = FALSE;
  164. $field_definition = $this->fieldTypeManager->getDefinition(reset($this->pluginDefinition['allowed_field_types']));
  165. $form['source_field_message'] = [
  166. '#markup' => $this->t('%field_type field will be automatically created on this type to store the essential information about the media item.', [
  167. '%field_type' => $field_definition['label'],
  168. ]),
  169. ];
  170. }
  171. elseif ($form_state->get('operation') === 'edit') {
  172. $form['source_field']['#access'] = FALSE;
  173. $fields = $this->entityFieldManager->getFieldDefinitions('media', $form_state->get('type')->id());
  174. $form['source_field_message'] = [
  175. '#markup' => $this->t('%field_name field is used to store the essential information about the media item.', [
  176. '%field_name' => $fields[$this->configuration['source_field']]->getLabel(),
  177. ]),
  178. ];
  179. }
  180. return $form;
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  191. foreach (array_intersect_key($form_state->getValues(), $this->configuration) as $config_key => $config_value) {
  192. $this->configuration[$config_key] = $config_value;
  193. }
  194. // If no source field is explicitly set, create it now.
  195. if (empty($this->configuration['source_field'])) {
  196. $field_storage = $this->createSourceFieldStorage();
  197. $field_storage->save();
  198. $this->configuration['source_field'] = $field_storage->getName();
  199. }
  200. }
  201. /**
  202. * Creates the source field storage definition.
  203. *
  204. * By default, the first field type listed in the plugin definition's
  205. * allowed_field_types array will be the generated field's type.
  206. *
  207. * @return \Drupal\field\FieldStorageConfigInterface
  208. * The unsaved field storage definition.
  209. */
  210. protected function createSourceFieldStorage() {
  211. return $this->entityTypeManager
  212. ->getStorage('field_storage_config')
  213. ->create([
  214. 'entity_type' => 'media',
  215. 'field_name' => $this->getSourceFieldName(),
  216. 'type' => reset($this->pluginDefinition['allowed_field_types']),
  217. ]);
  218. }
  219. /**
  220. * Returns the source field storage definition.
  221. *
  222. * @return \Drupal\Core\Field\FieldStorageDefinitionInterface|null
  223. * The field storage definition or NULL if it doesn't exists.
  224. */
  225. protected function getSourceFieldStorage() {
  226. // Nothing to do if no source field is configured yet.
  227. $field = $this->configuration['source_field'];
  228. if ($field) {
  229. // Even if we do know the name of the source field, there's no
  230. // guarantee that it exists.
  231. $fields = $this->entityFieldManager->getFieldStorageDefinitions('media');
  232. return isset($fields[$field]) ? $fields[$field] : NULL;
  233. }
  234. return NULL;
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. public function getSourceFieldDefinition(MediaTypeInterface $type) {
  240. // Nothing to do if no source field is configured yet.
  241. $field = $this->configuration['source_field'];
  242. if ($field) {
  243. // Even if we do know the name of the source field, there is no
  244. // guarantee that it already exists.
  245. $fields = $this->entityFieldManager->getFieldDefinitions('media', $type->id());
  246. return isset($fields[$field]) ? $fields[$field] : NULL;
  247. }
  248. return NULL;
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. public function createSourceField(MediaTypeInterface $type) {
  254. $storage = $this->getSourceFieldStorage() ?: $this->createSourceFieldStorage();
  255. return $this->entityTypeManager
  256. ->getStorage('field_config')
  257. ->create([
  258. 'field_storage' => $storage,
  259. 'bundle' => $type->id(),
  260. 'label' => $this->pluginDefinition['label'],
  261. 'required' => TRUE,
  262. ]);
  263. }
  264. /**
  265. * Determine the name of the source field.
  266. *
  267. * @return string
  268. * The source field name. If one is already stored in configuration, it is
  269. * returned. Otherwise, a new, unused one is generated.
  270. */
  271. protected function getSourceFieldName() {
  272. $base_id = 'field_media_' . $this->getPluginId();
  273. $tries = 0;
  274. $storage = $this->entityTypeManager->getStorage('field_storage_config');
  275. // Iterate at least once, until no field with the generated ID is found.
  276. do {
  277. $id = $base_id;
  278. // If we've tried before, increment and append the suffix.
  279. if ($tries) {
  280. $id .= '_' . $tries;
  281. }
  282. $field = $storage->load('media.' . $id);
  283. $tries++;
  284. } while ($field);
  285. return $id;
  286. }
  287. }