<?php
declare(strict_types=1);
namespace NetInventors\NetiNextEasyCoupon\Subscriber;
use Doctrine\DBAL\Connection;
use Monolog\Logger;
use NetInventors\NetiNextEasyCoupon\Core\Content\EasyCoupon\EasyCouponDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\NumberRange\ValueGenerator\NumberRangeValueGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EntitySubscriber implements EventSubscriberInterface
{
private NumberRangeValueGenerator $numberRangeValueGenerator;
private Connection $connection;
private Logger $logger;
public function __construct(
NumberRangeValueGenerator $numberRangeValueGenerator,
Connection $connection,
Logger $logger
) {
$this->numberRangeValueGenerator = $numberRangeValueGenerator;
$this->connection = $connection;
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
EasyCouponDefinition::ENTITY_NAME . '.written' => 'onEasyCouponWritten',
];
}
public function onEasyCouponWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $writeResult) {
if (
$writeResult->getEntityName() !== EasyCouponDefinition::ENTITY_NAME
|| $writeResult->getOperation() !== 'insert'
) {
continue;
}
/**
* @var string $id This is okay because the entity has only one primary key
*/
$id = $writeResult->getPrimaryKey();
try {
$number = $this->numberRangeValueGenerator->getValue(
EasyCouponDefinition::ENTITY_NAME,
$event->getContext(),
null
);
$sql = '
UPDATE neti_easy_coupon
SET number = ?
WHERE id = ?
';
$this->connection->executeStatement($sql, [
$number,
Uuid::fromHexToBytes($id),
]);
} catch (\Exception $ex) {
$this->logger->warning(
'Could not generate number for EasyCoupon',
[
'error' => $ex->getMessage(),
'easyCouponId' => $id,
]
);
}
}
}
}