MediaSourceBase.php 11 KB

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