class CKEditor5MediaController

Same name in other branches
  1. 9 core/modules/ckeditor5/src/Controller/CKEditor5MediaController.php \Drupal\ckeditor5\Controller\CKEditor5MediaController
  2. 11.x core/modules/ckeditor5/src/Controller/CKEditor5MediaController.php \Drupal\ckeditor5\Controller\CKEditor5MediaController

Provides an API for checking if a media entity has image field.

@internal Controller classes are internal.

Hierarchy

Expanded class hierarchy of CKEditor5MediaController

File

core/modules/ckeditor5/src/Controller/CKEditor5MediaController.php, line 28

Namespace

Drupal\ckeditor5\Controller
View source
class CKEditor5MediaController extends ControllerBase {
    
    /**
     * The currently authenticated user.
     *
     * @var \Drupal\Core\Session\AccountInterface
     */
    protected $currentUser;
    
    /**
     * The entity repository.
     *
     * @var \Drupal\Core\Entity\EntityRepositoryInterface
     */
    protected $entityRepository;
    
    /**
     * The request stack.
     *
     * @var \Symfony\Component\HttpFoundation\RequestStack
     */
    protected $requestStack;
    
    /**
     * Constructs a new CKEditor5MediaController.
     *
     * @param \Drupal\Core\Session\AccountInterface $current_user
     *   The currently authenticated user.
     * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
     *   The entity repository.
     * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
     *   The request stack.
     */
    public function __construct(AccountInterface $current_user, EntityRepositoryInterface $entity_repository, RequestStack $request_stack) {
        $this->currentUser = $current_user;
        $this->entityRepository = $entity_repository;
        $this->requestStack = $request_stack;
    }
    
    /**
     * Returns JSON response containing metadata about media entity.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The current request object.
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *   A JSON object including the response.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
     *   Thrown when no media UUID is provided.
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     *   Thrown when no media with the provided UUID exists.
     */
    public function mediaEntityMetadata(Request $request) {
        $uuid = $request->query
            ->get('uuid');
        if (!$uuid || !Uuid::isValid($uuid)) {
            throw new BadRequestHttpException();
        }
        // Access is enforced on route level.
        // @see \Drupal\ckeditor5\Controller\CKEditor5MediaController::access().
        if (!($media = $this->entityRepository
            ->loadEntityByUuid('media', $uuid))) {
            throw new NotFoundHttpException();
        }
        $image_field = $this->getMediaImageSourceFieldName($media);
        $response = [];
        $response['type'] = $media->bundle();
        // If this uses the image media source and the "alt" field is enabled,
        // expose additional metadata.
        // @see \Drupal\media\Plugin\media\Source\Image
        // @see core/modules/ckeditor5/js/ckeditor5_plugins/drupalMedia/src/mediaimagetextalternative/mediaimagetextalternativeui.js
        if ($image_field) {
            $settings = $media->{$image_field}
                ->getItemDefinition()
                ->getSettings();
            if (!empty($settings['alt_field'])) {
                $response['imageSourceMetadata'] = [
                    'alt' => $this->entityRepository
                        ->getTranslationFromContext($media)->{$image_field}->alt,
                ];
            }
        }
        // Note that we intentionally do not use:
        // - \Drupal\Core\Cache\CacheableResponse because caching it on the server
        //   side is wasteful, hence there is no need for cacheability metadata.
        // - \Drupal\Core\Render\HtmlResponse because there is no need for
        //   attachments nor cacheability metadata.
        return (new JsonResponse($response, 200))->setPrivate()
            ->setMaxAge(300);
    }
    
    /**
     * Additional access check for ::isMediaImage().
     *
     * This grants access if media embed filter is enabled on the filter format
     * and user has access to view the media entity.
     *
     * Note that access to the filter format is not checked here because the route
     * is configured to check entity access to the filter format.
     *
     * @param \Drupal\editor\Entity\Editor $editor
     *   The text editor.
     *
     * @return \Drupal\Core\Access\AccessResultInterface
     *   The access result.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
     *   Thrown when no media UUID is provided.
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     *   Thrown when no media with the provided UUID exists.
     */
    public function access(Editor $editor) : AccessResultInterface {
        if ($editor->getEditor() !== 'ckeditor5') {
            return AccessResult::forbidden();
        }
        // @todo add current request as an argument after
        // https://www.drupal.org/project/drupal/issues/2786941 has been resolved.
        $request = $this->requestStack
            ->getCurrentRequest();
        $uuid = $request->query
            ->get('uuid');
        if (!$uuid || !Uuid::isValid($uuid)) {
            throw new BadRequestHttpException();
        }
        $media = $this->entityRepository
            ->loadEntityByUuid('media', $uuid);
        if (!$media) {
            throw new NotFoundHttpException();
        }
        $filters = $editor->getFilterFormat()
            ->filters();
        return AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status)
            ->andIf($media->access('view', $this->currentUser, TRUE))
            ->addCacheableDependency($editor->getFilterFormat());
    }
    
    /**
     * Gets the name of an image media item's source field.
     *
     * @param \Drupal\media\MediaInterface $media
     *   The media item being embedded.
     *
     * @return string|null
     *   The name of the image source field configured for the media item, or
     *   NULL if the source field is not an image field.
     */
    protected function getMediaImageSourceFieldName(MediaInterface $media) {
        $field_definition = $media->getSource()
            ->getSourceFieldDefinition($media->bundle->entity);
        $item_class = $field_definition->getItemDefinition()
            ->getClass();
        if (is_a($item_class, ImageItem::class, TRUE)) {
            return $field_definition->getName();
        }
        return NULL;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AutowireTrait::create public static function Instantiates a new instance of the implementing class using autowiring. 33
CKEditor5MediaController::$currentUser protected property The currently authenticated user. Overrides ControllerBase::$currentUser
CKEditor5MediaController::$entityRepository protected property The entity repository.
CKEditor5MediaController::$requestStack protected property The request stack.
CKEditor5MediaController::access public function Additional access check for ::isMediaImage().
CKEditor5MediaController::getMediaImageSourceFieldName protected function Gets the name of an image media item's source field.
CKEditor5MediaController::mediaEntityMetadata public function Returns JSON response containing metadata about media entity.
CKEditor5MediaController::__construct public function Constructs a new CKEditor5MediaController.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 1
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 1
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 2
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 1
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 1
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

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