class MediaLinkTarget

Provides a Media link target handler.

Media entities are atypical because by default they do not have their own stand-alone URL, which means only a subset of Media entities is actually linkable.

On the other hand, media entities that use the "file" media source plugin can be linked regardless of that setting because the referenced files are still linkable. Every media source plugin is free to implement the base implementation of :getMetadata() because a source plugin is guaranteed to know how the media is stored and linked.

Hierarchy

Expanded class hierarchy of MediaLinkTarget

See also

media_entity_type_alter()

\Drupal\media\Routing\MediaRouteProvider::getCanonicalRoute()

https://www.drupal.org/i/3017935

\Drupal\media\MediaSourceInterface::METADATA_ATTRIBUTE_LINK_TARGET

\Drupal\media\MediaSourceBase::getMetadata()

\Drupal\media\Plugin\media\Source\File::getMetadata()

\Drupal\media\Plugin\media\Source\OEmbed::getMetadata()

\Drupal\file\Entity\FileLinkTarget

\Drupal\media\Plugin\EntityReferenceSelection\MediaWithLinkTargetSelection

File

core/modules/media/src/Entity/MediaLinkTarget.php, line 39

Namespace

Drupal\media\Entity
View source
class MediaLinkTarget implements EntityLinkTargetInterface {
  
  /**
   * {@inheritdoc}
   */
  public function getLinkTarget(EntityInterface $entity) : GeneratedUrl {
    // Below is an example of how to get the generated URL object for a media
    // linked entity which is used in Entity links filter.
    // @see \Drupal\filter\Plugin\Filter\EntityLinks::getUrl().
    // At this point, media entity type is not enabled for entity suggestions in
    // CKEditor.
    // @see \Drupal\ckeditor5\Hook\Ckeditor5Hooks::entityBundleInfoAlter().
    // Technically, media link target handler should not be in the core until
    // core supports media entity by default, consider this is an example on how
    // to build a media link target handler.
    assert($entity instanceof MediaInterface);
    if ($link_target = $entity->getSource()
      ->getMetadata($entity, MediaSourceInterface::METADATA_ATTRIBUTE_LINK_TARGET)) {
      return $link_target;
    }
    // Entities are returned unless standalone URLs are enabled, to avoid
    // meaningless links like this one
    return (new GeneratedUrl())->setGeneratedUrl('')
      ->setCacheMaxAge(Cache::PERMANENT);
  }

}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.