<?php
declare(strict_types=1);
namespace Wbfk\ITScope\Subscriber;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\UpdateCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
use Shopware\Core\Framework\Validation\WriteConstraintViolationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Wbfk\ITScope\Core\Content\Product\WbfkItScopeProductExtensionDefinition;
class WbfkProductExtensionValidator implements EventSubscriberInterface
{
public function __construct(protected Connection $connection)
{
}
public static function getSubscribedEvents(): array
{
return [
PreWriteValidationEvent::class => 'onPreValidate',
];
}
public function onPreValidate(PreWriteValidationEvent $event): void
{
$violationList = new ConstraintViolationList();
foreach ($event->getCommands() as $command) {
if (!($command instanceof InsertCommand || $command instanceof UpdateCommand)) {
continue;
}
if ($command->getDefinition()->getClass() !== WbfkItScopeProductExtensionDefinition::class) {
continue;
}
$violationList->addAll($this->validateWbfkProductExtension($command));
}
if ($violationList->count() > 0) {
$event->getExceptions()->add(new WriteConstraintViolationException($violationList));
}
}
protected function validateWbfkProductExtension(InsertCommand|UpdateCommand $command): ConstraintViolationList
{
$violationList = new ConstraintViolationList();
$payload = $command->getPayload();
if (empty($payload['it_scope_id'])) {
return $violationList;
}
$itScopeId = json_decode($payload['it_scope_id'], true);
$stmt = $this->connection->prepare('SELECT LOWER(HEX(product_id)) AS product_id FROM wbfk_it_scope_product_extension WHERE it_scope_id = ?');
$stmt->executeStatement([$itScopeId]);
if ($stmt->rowCount() > 0) {
$result = $stmt->fetchOne();
$violationList->add(
new ConstraintViolation(
sprintf('Die ITScopeId wird bereits von Artikel %s genutzt', $result),
'Die ITScopeId wird bereits genutzt',
[],
'',
$command->getPath().'/itScopeId',
$itScopeId
)
);
}
return $violationList;
}
}