acquia_dam-1.0.0-rc1/src/MediaTypeResolver.php
src/MediaTypeResolver.php
<?php declare(strict_types=1); namespace Drupal\acquia_dam; use Drupal\acquia_dam\Plugin\media\Source\Asset; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\media\MediaTypeInterface; /** * Media type resolver for assets. */ final class MediaTypeResolver { /** * The entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ private $entityTypeManager; /** * Constructs a new MediaTypeResolver object. * * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager. */ public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->entityTypeManager = $entity_type_manager; } /** * Resolves the media type for an asset. * * @param array $asset * The asset data. * * @return \Drupal\media\MediaTypeInterface|null * The media type, or NULL if one cannot be resolved. * * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException */ public function resolve(array $asset): ?MediaTypeInterface { if (!isset($asset['file_properties'])) { return NULL; } $mapping = [ 'ft' => 'format_type', 'ff' => 'format', ]; foreach ($this->getMediaTypes() as $media_type) { $source = $media_type->getSource(); $definition = $source->getPluginDefinition(); if (!isset($mapping[$definition['asset_search_key']])) { continue; } $property_name = $mapping[$definition['asset_search_key']]; $property_value = $asset['file_properties'][$property_name] ?? ''; if ($definition['asset_search_value'] === $property_value) { return $media_type; } } return NULL; } /** * Gets media types with Asset source plugin. * * @return \Drupal\media\MediaTypeInterface[] * The media types. * * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException * * @phpstan-return array<string, \Drupal\media\MediaTypeInterface> */ private function getMediaTypes(): array { static $media_types = []; if ($media_types === []) { $media_type_storage = $this->entityTypeManager->getStorage('media_type'); $media_types = array_filter($media_type_storage->loadMultiple(), static function (MediaTypeInterface $media_type) { return $media_type->getSource() instanceof Asset; }); } return $media_types; } }