src/Component/ColorPicker/EventSubscriber/UpdateSwatchColorSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Component\ColorPicker\EventSubscriber;
  4. use App\Component\ColorPicker\Attribute\ColorPickerColor;
  5. use App\Component\ColorPicker\Event\PostUpdateEvent;
  6. use App\Component\ColorPicker\Model\UpdateColorEntry;
  7. use App\Repository\ColorPickerSwatchRepository;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class UpdateSwatchColorSubscriber implements EventSubscriberInterface
  11. {
  12.     private const UPDATE_SWATCH_LISTENER_FIELD 'value';
  13.     public function __construct(
  14.         private readonly EntityManagerInterface $entityManager,
  15.         private readonly ColorPickerSwatchRepository $repository,
  16.     ) {
  17.     }
  18.     public function onPostUpdateEvent(PostUpdateEvent $event): void
  19.     {
  20.         $changeSet $event->getChangeSet();
  21.         if (!$changeSet->hasChangedField(self::UPDATE_SWATCH_LISTENER_FIELD)) {
  22.             return;
  23.         }
  24.         $entries = [];
  25.         $metaDataCollection $this->entityManager->getMetadataFactory()->getAllMetadata();
  26.         foreach ($metaDataCollection as $metaData) {
  27.             foreach ($metaData->getReflectionProperties() as $property) {
  28.                 if (null !== $property && \count($property->getAttributes(ColorPickerColor::class)) > 0) {
  29.                     $entries[] = new UpdateColorEntry(
  30.                         $metaData->getTableName(),
  31.                         $metaData->getColumnName($property->getName())
  32.                     );
  33.                 }
  34.             }
  35.         }
  36.         $this->repository->updateColors(
  37.             $entries,
  38.             $changeSet->getOldValue(self::UPDATE_SWATCH_LISTENER_FIELD),
  39.             $changeSet->getNewValue(self::UPDATE_SWATCH_LISTENER_FIELD)
  40.         );
  41.     }
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             PostUpdateEvent::class => 'onPostUpdateEvent',
  46.         ];
  47.     }
  48. }