<?php
declare(strict_types=1);
namespace App\Component\ColorPicker\EventSubscriber;
use App\Component\ColorPicker\Attribute\ColorPickerColor;
use App\Component\ColorPicker\Event\PostUpdateEvent;
use App\Component\ColorPicker\Model\UpdateColorEntry;
use App\Repository\ColorPickerSwatchRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UpdateSwatchColorSubscriber implements EventSubscriberInterface
{
private const UPDATE_SWATCH_LISTENER_FIELD = 'value';
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly ColorPickerSwatchRepository $repository,
) {
}
public function onPostUpdateEvent(PostUpdateEvent $event): void
{
$changeSet = $event->getChangeSet();
if (!$changeSet->hasChangedField(self::UPDATE_SWATCH_LISTENER_FIELD)) {
return;
}
$entries = [];
$metaDataCollection = $this->entityManager->getMetadataFactory()->getAllMetadata();
foreach ($metaDataCollection as $metaData) {
foreach ($metaData->getReflectionProperties() as $property) {
if (null !== $property && \count($property->getAttributes(ColorPickerColor::class)) > 0) {
$entries[] = new UpdateColorEntry(
$metaData->getTableName(),
$metaData->getColumnName($property->getName())
);
}
}
}
$this->repository->updateColors(
$entries,
$changeSet->getOldValue(self::UPDATE_SWATCH_LISTENER_FIELD),
$changeSet->getNewValue(self::UPDATE_SWATCH_LISTENER_FIELD)
);
}
public static function getSubscribedEvents(): array
{
return [
PostUpdateEvent::class => 'onPostUpdateEvent',
];
}
}