<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\Channel\Channel;
use App\Repository\Channel\ChannelRepository;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
final class ChannelListener
{
public function __construct(private ChannelRepository $channelRepository)
{
}
public function preCreate(ResourceControllerEvent $event): void
{
/** @var Channel $channel */
$channel = $event->getSubject();
if ($channel->isDefaultChannel()) {
$channels = $this->channelRepository->findAll();
/** @var Channel $otherChannel */
foreach ($channels as $otherChannel) {
if ($otherChannel->getCode() !== $channel->getCode() && $otherChannel->isDefaultChannel()) {
$otherChannel->setIsDefaultChannel(false);
}
}
}
}
public function preUpdate(ResourceControllerEvent $event): void
{
/** @var Channel $channel */
$channel = $event->getSubject();
if ($channel->isDefaultChannel()) {
$channels = $this->channelRepository->findAll();
/** @var Channel $otherChannel */
foreach ($channels as $otherChannel) {
if ($otherChannel->getCode() !== $channel->getCode() && $otherChannel->isDefaultChannel()) {
$otherChannel->setIsDefaultChannel(false);
}
}
}
}
}