101 lines
3.6 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\PersonBundle\AccompanyingPeriod\Events;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Notification;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Event\Person\PersonAddressMoveEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class PersonMoveEventSubscriber implements EventSubscriberInterface
{
private EngineInterface $engine;
private EntityManagerInterface $entityManager;
private Security $security;
private TranslatorInterface $translator;
public function __construct(
EngineInterface $engine,
EntityManagerInterface $entityManager,
Security $security,
TranslatorInterface $translator
) {
$this->engine = $engine;
$this->entityManager = $entityManager;
$this->security = $security;
$this->translator = $translator;
}
public static function getSubscribedEvents(): array
{
return [
PersonAddressMoveEvent::class => 'resetPeriodLocation',
];
}
public function resetPeriodLocation(PersonAddressMoveEvent $event)
{
if ($event->getPreviousAddress() !== $event->getNextAddress()
&& null !== $event->getPreviousAddress()
) {
$person = $event->getPerson();
foreach ($person->getCurrentAccompanyingPeriods() as $period) {
if ($period->getStep() === AccompanyingPeriod::STEP_DRAFT) {
continue;
}
$now = new \DateTimeImmutable('now');
if (
$period->getPersonLocation() === $person
&&
(
$event->getMoveDate() >= $period->getLastLocationHistory()->getStartDate()
|| (
$event->getNextAddress()->getValidFrom() < $now
&& (null === $event->getNextAddress()->getValidTo() || $event->getNextAddress()->getValidTo() > $now)
)
)
&& null !== $period->getUser()
&& $period->getUser() !== $this->security->getUser()
) {
// reset the location, back to an address
$period->setPersonLocation(null);
$period->setAddressLocation(Address::createFromAddress($event->getPreviousAddress()));
$notification = new Notification();
$notification
->addAddressee($period->getUser())
->setTitle($this->translator->trans('period_notification.Person locating period has moved'))
->setRelatedEntityClass(AccompanyingPeriod::class)
->setRelatedEntityId($period->getId())
->setMessage($this->engine->render('@ChillPerson/AccompanyingPeriod/notification_location_user_on_period_has_moved.fr.txt.twig', [
'oldPersonLocation' => $person,
'period' => $period,
]));
$this->entityManager->persist($notification);
}
}
}
}
}