<?php declare(strict_types=1);
namespace StudioSolid\ProductVideos\Core\Content\Product\Subscriber;
use Exception;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
use Shopware\Core\Framework\Validation\WriteConstraintViolationException;
use StudioSolid\ProductVideos\Core\Content\Product\Aggregate\ProductEmbeddedVideoMedia\ProductEmbeddedVideoMediaDefinition;
use StudioSolid\ProductVideos\Core\Content\Product\Service\ProductEmbeddedVideoMediaService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
class ProductEmbeddedVideoMediaValidator implements EventSubscriberInterface
{
/**
* @var ProductEmbeddedVideoMediaService
*/
private $productEmbeddedVideoMediaService;
public function __construct(ProductEmbeddedVideoMediaService $productEmbeddedVideoMediaService)
{
$this->productEmbeddedVideoMediaService = $productEmbeddedVideoMediaService;
}
public static function getSubscribedEvents()
{
return [
PreWriteValidationEvent::class => 'validate',
];
}
public function validate(PreWriteValidationEvent $event): void
{
$violations = new ConstraintViolationList();
foreach ($event->getCommands() as $command) {
if (!($command instanceof InsertCommand)) {
continue;
}
if ($command->getDefinition()->getClass() !== ProductEmbeddedVideoMediaDefinition::class) {
continue;
}
$payload = $command->getPayload();
$source = $payload['source'];
$videoId = $payload['video_id'];
try {
$this->productEmbeddedVideoMediaService->validate($source, $videoId);
} catch (Exception $exception) {
$violations->add(new ConstraintViolation(
$exception->getMessage(),
null,
[],
null,
'/',
null
));
}
try {
if (!$this->productEmbeddedVideoMediaService->fetchThumbnailPlatformUrl($source, $videoId)) {
throw new \InvalidArgumentException('Parameter videoId is not available at the requested source ' . $source);
}
} catch (Exception $exception) {
$violations->add(new ConstraintViolation(
$exception->getMessage(),
null,
[],
null,
'/',
null
));
}
}
if ($violations->count() < 1) {
return;
}
$event->getExceptions()->add(new WriteConstraintViolationException($violations));
}
}