3 namespace Drupal\media\Entity;
5 use Drupal\Core\Entity\EditorialContentEntityBase;
6 use Drupal\Core\Entity\EntityStorageInterface;
7 use Drupal\Core\Entity\EntityTypeInterface;
8 use Drupal\Core\Field\BaseFieldDefinition;
9 use Drupal\Core\StringTranslation\StringTranslationTrait;
10 use Drupal\media\MediaInterface;
11 use Drupal\media\MediaSourceEntityConstraintsInterface;
12 use Drupal\media\MediaSourceFieldConstraintsInterface;
13 use Drupal\user\UserInterface;
16 * Defines the media entity class.
18 * @todo Remove default/fallback entity form operation when #2006348 is done.
19 * @see https://www.drupal.org/node/2006348.
23 * label = @Translation("Media"),
24 * label_singular = @Translation("media item"),
25 * label_plural = @Translation("media items"),
26 * label_count = @PluralTranslation(
27 * singular = "@count media item",
28 * plural = "@count media items"
30 * bundle_label = @Translation("Media type"),
32 * "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
33 * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
34 * "list_builder" = "Drupal\Core\Entity\EntityListBuilder",
35 * "access" = "Drupal\media\MediaAccessControlHandler",
37 * "default" = "Drupal\media\MediaForm",
38 * "add" = "Drupal\media\MediaForm",
39 * "edit" = "Drupal\media\MediaForm",
40 * "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
42 * "translation" = "Drupal\content_translation\ContentTranslationHandler",
43 * "views_data" = "Drupal\media\MediaViewsData",
44 * "route_provider" = {
45 * "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
48 * base_table = "media",
49 * data_table = "media_field_data",
50 * revision_table = "media_revision",
51 * revision_data_table = "media_field_revision",
52 * translatable = TRUE,
53 * show_revision_ui = TRUE,
57 * "bundle" = "bundle",
59 * "langcode" = "langcode",
61 * "published" = "status",
63 * revision_metadata_keys = {
64 * "revision_user" = "revision_user",
65 * "revision_created" = "revision_created",
66 * "revision_log_message" = "revision_log_message",
68 * bundle_entity_type = "media_type",
69 * permission_granularity = "entity_type",
70 * admin_permission = "administer media",
71 * field_ui_base_route = "entity.media_type.edit_form",
72 * common_reference_target = TRUE,
74 * "add-page" = "/media/add",
75 * "add-form" = "/media/add/{media_type}",
76 * "canonical" = "/media/{media}",
77 * "delete-form" = "/media/{media}/delete",
78 * "edit-form" = "/media/{media}/edit",
79 * "revision" = "/media/{media}/revisions/{media_revision}/view",
83 class Media extends EditorialContentEntityBase implements MediaInterface {
85 use StringTranslationTrait;
90 public function getName() {
91 $name = $this->get('name');
93 if ($name->isEmpty()) {
94 $media_source = $this->getSource();
95 return $media_source->getMetadata($this, $media_source->getPluginDefinition()['default_name_metadata_attribute']);
105 public function label() {
106 return $this->getName();
112 public function setName($name) {
113 return $this->set('name', $name);
119 public function getCreatedTime() {
120 return $this->get('created')->value;
126 public function setCreatedTime($timestamp) {
127 return $this->set('created', $timestamp);
133 public function getOwner() {
134 return $this->get('uid')->entity;
140 public function setOwner(UserInterface $account) {
141 return $this->set('uid', $account->id());
147 public function getOwnerId() {
148 return $this->get('uid')->target_id;
154 public function setOwnerId($uid) {
155 return $this->set('uid', $uid);
161 public function getSource() {
162 return $this->bundle->entity->getSource();
166 * Update the thumbnail for the media item.
168 * @param bool $from_queue
169 * Specifies whether the thumbnail update is triggered from the queue.
171 * @return \Drupal\media\MediaInterface
172 * The updated media item.
176 * @todo There has been some disagreement about how to handle updates to
177 * thumbnails. We need to decide on what the API will be for this.
178 * https://www.drupal.org/node/2878119
180 protected function updateThumbnail($from_queue = FALSE) {
181 $file_storage = \Drupal::service('entity_type.manager')->getStorage('file');
182 $thumbnail_uri = $this->getThumbnailUri($from_queue);
183 $existing = $file_storage->getQuery()
184 ->condition('uri', $thumbnail_uri)
188 $this->thumbnail->target_id = reset($existing);
191 /** @var \Drupal\file\FileInterface $file */
192 $file = $file_storage->create(['uri' => $thumbnail_uri]);
193 if ($owner = $this->getOwner()) {
194 $file->setOwner($owner);
196 $file->setPermanent();
198 $this->thumbnail->target_id = $file->id();
201 // Set the thumbnail alt.
202 $media_source = $this->getSource();
203 $plugin_definition = $media_source->getPluginDefinition();
204 if (!empty($plugin_definition['thumbnail_alt_metadata_attribute'])) {
205 $this->thumbnail->alt = $media_source->getMetadata($this, $plugin_definition['thumbnail_alt_metadata_attribute']);
208 $this->thumbnail->alt = $this->t('Thumbnail', [], ['langcode' => $this->langcode->value]);
211 // Set the thumbnail title.
212 if (!empty($plugin_definition['thumbnail_title_metadata_attribute'])) {
213 $this->thumbnail->title = $media_source->getMetadata($this, $plugin_definition['thumbnail_title_metadata_attribute']);
216 $this->thumbnail->title = $this->label();
223 * Updates the queued thumbnail for the media item.
225 * @return \Drupal\media\MediaInterface
226 * The updated media item.
230 * @todo If the need arises in contrib, consider making this a public API,
231 * by adding an interface that extends MediaInterface.
233 public function updateQueuedThumbnail() {
234 $this->updateThumbnail(TRUE);
239 * Gets the URI for the thumbnail of a media item.
241 * If thumbnail fetching is queued, new media items will use the default
242 * thumbnail, and existing media items will use the current thumbnail, until
243 * the queue is processed and the updated thumbnail has been fetched.
244 * Otherwise, the new thumbnail will be fetched immediately.
246 * @param bool $from_queue
247 * Specifies whether the thumbnail is being fetched from the queue.
250 * The file URI for the thumbnail of the media item.
254 protected function getThumbnailUri($from_queue) {
255 $thumbnails_queued = $this->bundle->entity->thumbnailDownloadsAreQueued();
256 if ($thumbnails_queued && $this->isNew()) {
257 $default_thumbnail_filename = $this->getSource()->getPluginDefinition()['default_thumbnail_filename'];
258 $thumbnail_uri = \Drupal::service('config.factory')->get('media.settings')->get('icon_base_uri') . '/' . $default_thumbnail_filename;
260 elseif ($thumbnails_queued && !$from_queue) {
261 $thumbnail_uri = $this->get('thumbnail')->entity->getFileUri();
264 $thumbnail_uri = $this->getSource()->getMetadata($this, $this->getSource()->getPluginDefinition()['thumbnail_uri_metadata_attribute']);
267 return $thumbnail_uri;
271 * Determines if the source field value has changed.
274 * TRUE if the source field value changed, FALSE otherwise.
278 protected function hasSourceFieldChanged() {
279 $source_field_name = $this->getSource()->getConfiguration()['source_field'];
280 $current_items = $this->get($source_field_name);
281 return isset($this->original) && !$current_items->equals($this->original->get($source_field_name));
285 * Determines if the thumbnail should be updated for a media item.
287 * @param bool $is_new
288 * Specifies whether the media item is new.
291 * TRUE if the thumbnail should be updated, FALSE otherwise.
293 protected function shouldUpdateThumbnail($is_new = FALSE) {
294 // Update thumbnail if we don't have a thumbnail yet or when the source
295 // field value changes.
296 return !$this->get('thumbnail')->entity || $is_new || $this->hasSourceFieldChanged();
302 public function preSave(EntityStorageInterface $storage) {
303 parent::preSave($storage);
305 $media_source = $this->getSource();
306 foreach ($this->translations as $langcode => $data) {
307 if ($this->hasTranslation($langcode)) {
308 $translation = $this->getTranslation($langcode);
309 // Try to set fields provided by the media source and mapped in
310 // media type config.
311 foreach ($translation->bundle->entity->getFieldMap() as $metadata_attribute_name => $entity_field_name) {
312 // Only save value in entity field if empty. Do not overwrite existing
314 if ($translation->hasField($entity_field_name) && ($translation->get($entity_field_name)->isEmpty() || $translation->hasSourceFieldChanged())) {
315 $translation->set($entity_field_name, $media_source->getMetadata($translation, $metadata_attribute_name));
319 // Try to set a default name for this media item if no name is provided.
320 if ($translation->get('name')->isEmpty()) {
321 $translation->setName($translation->getName());
325 if ($translation->shouldUpdateThumbnail()) {
326 $translation->updateThumbnail();
335 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
336 parent::postSave($storage, $update);
338 foreach ($this->translations as $langcode => $data) {
339 if ($this->hasTranslation($langcode)) {
340 $translation = $this->getTranslation($langcode);
341 if ($translation->bundle->entity->thumbnailDownloadsAreQueued() && $translation->shouldUpdateThumbnail($is_new)) {
342 \Drupal::queue('media_entity_thumbnail')->createItem(['id' => $translation->id()]);
351 public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
352 parent::preSaveRevision($storage, $record);
354 $is_new_revision = $this->isNewRevision();
355 if (!$is_new_revision && isset($this->original) && empty($record->revision_log_message)) {
356 // If we are updating an existing media item without adding a
357 // new revision, we need to make sure $entity->revision_log_message is
358 // reset whenever it is empty.
359 // Therefore, this code allows us to avoid clobbering an existing log
360 // entry with an empty one.
361 $record->revision_log_message = $this->original->revision_log_message->value;
364 if ($is_new_revision) {
365 $record->revision_created = self::getRequestTime();
372 public function validate() {
373 $media_source = $this->getSource();
375 if ($media_source instanceof MediaSourceEntityConstraintsInterface) {
376 $entity_constraints = $media_source->getEntityConstraints();
377 $this->getTypedData()->getDataDefinition()->setConstraints($entity_constraints);
380 if ($media_source instanceof MediaSourceFieldConstraintsInterface) {
381 $source_field_name = $media_source->getConfiguration()['source_field'];
382 $source_field_constraints = $media_source->getSourceFieldConstraints();
383 $this->get($source_field_name)->getDataDefinition()->setConstraints($source_field_constraints);
386 return parent::validate();
392 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
393 $fields = parent::baseFieldDefinitions($entity_type);
395 $fields['name'] = BaseFieldDefinition::create('string')
396 ->setLabel(t('Name'))
398 ->setTranslatable(TRUE)
399 ->setRevisionable(TRUE)
400 ->setDefaultValue('')
401 ->setSetting('max_length', 255)
402 ->setDisplayOptions('form', [
403 'type' => 'string_textfield',
406 ->setDisplayConfigurable('form', TRUE)
407 ->setDisplayConfigurable('view', TRUE)
408 ->setDisplayOptions('view', [
414 $fields['thumbnail'] = BaseFieldDefinition::create('image')
415 ->setLabel(t('Thumbnail'))
416 ->setDescription(t('The thumbnail of the media item.'))
417 ->setRevisionable(TRUE)
418 ->setTranslatable(TRUE)
419 ->setDisplayOptions('view', [
424 'image_style' => 'thumbnail',
427 ->setDisplayConfigurable('view', TRUE)
430 $fields['uid'] = BaseFieldDefinition::create('entity_reference')
431 ->setLabel(t('Authored by'))
432 ->setDescription(t('The user ID of the author.'))
433 ->setRevisionable(TRUE)
434 ->setDefaultValueCallback(static::class . '::getCurrentUserId')
435 ->setSetting('target_type', 'user')
436 ->setTranslatable(TRUE)
437 ->setDisplayOptions('form', [
438 'type' => 'entity_reference_autocomplete',
441 'match_operator' => 'CONTAINS',
443 'autocomplete_type' => 'tags',
447 ->setDisplayConfigurable('form', TRUE)
448 ->setDisplayOptions('view', [
453 ->setDisplayConfigurable('view', TRUE);
456 ->setDisplayOptions('form', [
457 'type' => 'boolean_checkbox',
459 'display_label' => TRUE,
463 ->setDisplayConfigurable('form', TRUE);
465 $fields['created'] = BaseFieldDefinition::create('created')
466 ->setLabel(t('Authored on'))
467 ->setDescription(t('The time the media item was created.'))
468 ->setTranslatable(TRUE)
469 ->setRevisionable(TRUE)
470 ->setDefaultValueCallback(static::class . '::getRequestTime')
471 ->setDisplayOptions('form', [
472 'type' => 'datetime_timestamp',
475 ->setDisplayConfigurable('form', TRUE)
476 ->setDisplayOptions('view', [
478 'type' => 'timestamp',
481 ->setDisplayConfigurable('view', TRUE);
483 $fields['changed'] = BaseFieldDefinition::create('changed')
484 ->setLabel(t('Changed'))
485 ->setDescription(t('The time the media item was last edited.'))
486 ->setTranslatable(TRUE)
487 ->setRevisionable(TRUE);
493 * Default value callback for 'uid' base field definition.
495 * @see ::baseFieldDefinitions()
498 * An array of default values.
500 public static function getCurrentUserId() {
501 return [\Drupal::currentUser()->id()];
507 public static function getRequestTime() {
508 return \Drupal::time()->getRequestTime();