OEmbedResourceConstraintValidator.php in Drupal 8
File
core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraintValidator.php
View source
<?php
namespace Drupal\media\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\media\OEmbed\ProviderException;
use Drupal\media\OEmbed\ResourceException;
use Drupal\media\OEmbed\ResourceFetcherInterface;
use Drupal\media\OEmbed\UrlResolverInterface;
use Drupal\media\Plugin\media\Source\OEmbedInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class OEmbedResourceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $urlResolver;
protected $resourceFetcher;
protected $logger;
public function __construct(UrlResolverInterface $url_resolver, ResourceFetcherInterface $resource_fetcher, LoggerChannelFactoryInterface $logger_factory) {
$this->urlResolver = $url_resolver;
$this->resourceFetcher = $resource_fetcher;
$this->logger = $logger_factory
->get('media');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('media.oembed.url_resolver'), $container
->get('media.oembed.resource_fetcher'), $container
->get('logger.factory'));
}
public function validate($value, Constraint $constraint) {
$media = $value
->getEntity();
$source = $media
->getSource();
if (!$source instanceof OEmbedInterface) {
throw new \LogicException('Media source must implement ' . OEmbedInterface::class);
}
$url = $source
->getSourceFieldValue($media);
if (empty($url)) {
$this->context
->addViolation($constraint->invalidResourceMessage);
return;
}
try {
$provider = $this->urlResolver
->getProviderByUrl($url);
} catch (ResourceException $e) {
$this
->handleException($e, $constraint->unknownProviderMessage);
return;
} catch (ProviderException $e) {
$this
->handleException($e, $constraint->providerErrorMessage);
return;
}
if (!in_array($provider
->getName(), $source
->getProviders(), TRUE)) {
$this->context
->addViolation($constraint->disallowedProviderMessage, [
'@name' => $provider
->getName(),
]);
return;
}
try {
$resource_url = $this->urlResolver
->getResourceUrl($url);
$this->resourceFetcher
->fetchResource($resource_url);
} catch (ResourceException $e) {
$this
->handleException($e, $constraint->invalidResourceMessage);
}
}
protected function handleException(\Exception $e, $error_message = NULL) {
if ($error_message) {
$this->context
->addViolation($error_message);
}
do {
$this->logger
->error($e
->getMessage());
$e = $e
->getPrevious();
} while ($e);
}
}