<?php
// api/src/EventSubscriber/BookMailSubscriber.php
namespace Roothirsch\ShopBundle\EventSubscriber\Api;
use ApiPlatform\Core\EventListener\EventPriorities;
use Roothirsch\ShopBundle\Entity\Estimate;
use Roothirsch\ShopBundle\Entity\EstimateAddress;
use Roothirsch\ShopBundle\Repository\AddressRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
final class EstimateAddressSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var AddressRepository
*/
private $estimateAddressRepository;
public function __construct(EntityManagerInterface $entityManager, AddressRepository $estimateAddressRepository)
{
$this->entityManager = $entityManager;
$this->estimateAddressRepository = $estimateAddressRepository;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['validate', EventPriorities::PRE_VALIDATE],
];
}
public function validate(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
{
if (!$event->getControllerResult() instanceof Estimate) {
return;
}
/** @var \Roothirsch\ShopBundle\Entity\Estimate $estimate */
$estimate = $event->getControllerResult();
$this->updateCustomerAddress($estimate);
$this->updateCarpenterAddresses($estimate);
$this->entityManager->flush();
}
/**
* @param \Roothirsch\ShopBundle\Entity\Estimate $estimate
*/
protected function updateCustomerAddress(Estimate $estimate)
{
$sourceName = 'estimate_customer';
$address = $this->estimateAddressRepository->findOneBy(
[
'estimate' => $estimate,
'source' => $sourceName,
]
);
if (!$address) {
$address = new EstimateAddress();
$address
->setEstimate($estimate)
->setSource($sourceName);
$this->entityManager->persist($address);
}
$address
->setOwner($estimate->getOwner())
->setCustomer($estimate->getCustomer())
->setAddress($estimate->getAddress())
->setContactPerson($estimate->getContactPerson())
->setIsHidden($estimate->getHideAddressInSelector());
}
/**
* @param \Roothirsch\ShopBundle\Entity\Estimate $estimate
*/
protected function updateCarpenterAddresses(Estimate $estimate)
{
$sourceName = 'estimate_item_carpenter';
foreach ($estimate->getItems() as $item) {
if (!isset($item['carpenterCompany']) || empty($item['carpenterCompany'])) {
continue;
}
$address = $this->estimateAddressRepository->findOneBy(['itemShortcode' => $item['shortcode']]);
if (!$address) {
$address = new EstimateAddress();
$address
->setEstimate($estimate)
->setSource($sourceName)
->setItemShortcode($item['shortcode']);
$this->entityManager->persist($address);
}
$address
->setOwner($estimate->getOwner())
->setCustomer($item['carpenterCompany'])
->setAddress($item['carpenterAddress'])
->setContactPerson($estimate->getContactPerson())
->setIsHidden($estimate->getHideAddressInSelector());
}
}
}