src/EventListener/VacationListener.php line 63

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. namespace App\EventListener;
  4. use App\Event\Vacation\VacationAddedEvent;
  5. use App\Event\Vacation\VacationDeletedEvent;
  6. use App\Repository\AvailableDayRepository;
  7. use DateInterval;
  8. use DatePeriod;
  9. use DateTime;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpClient\HttpClient;
  13. class VacationListener
  14. {
  15.     private $availableDayRepository;
  16.     private $entityManager;
  17.     public function __construct(AvailableDayRepository $availableDayRepositoryEntityManagerInterface $entityManager)
  18.     {
  19.         $this->availableDayRepository $availableDayRepository;
  20.         $this->entityManager $entityManager;
  21.     }
  22.     public function onVacationAdded(VacationAddedEvent $event)
  23.     {
  24.         $vacation $event->getVacation();
  25.         $user $vacation->getUser();
  26.         $url "https://calendar.kuzyak.in/api/calendar/{$vacation->getDateFrom()->format('Y')}/holidays";
  27.         $response HttpClient::create()->request('GET'$url);
  28.         $daysOff json_decode($response->getContent(), true512\JSON_BIGINT_AS_STRING \JSON_THROW_ON_ERROR);
  29.         $holidaysDate array_map(function ($holiday) {
  30.             $date = new DateTime($holiday['date']);
  31.             return $date->format('Y-m-d');
  32.         }, $daysOff['holidays']);
  33.         $datePeriod = new DatePeriod($vacation->getDateFrom(), new DateInterval('P1D'), (clone $vacation->getDateTo())->modify('+1 day'));
  34.         $requestedDays 0;
  35.         foreach ($datePeriod as $date) {
  36.             // Исключаем праздники
  37.             if (in_array($date->format('Y-m-d'), $holidaysDate)) {
  38.                 continue;
  39.             }
  40.             // Исключаем выходные
  41.             if ($date->format('N') >= 6) {
  42.                 continue;
  43.             }
  44.             $requestedDays++;
  45.         }
  46.         $availableDays $this->availableDayRepository->findOneBy(['user' => $user]);
  47.         $availableDays->setDays($availableDays->getDays() - $requestedDays);
  48.         $this->entityManager->persist($availableDays);
  49.         $this->entityManager->flush();
  50.     }
  51.     public function onVacationDeleted(VacationDeletedEvent $event)
  52.     {
  53.         $vacation $event->getVacation();
  54.         $user $vacation->getUser();
  55.         $daysToAdd $vacation->getDateFrom()->diff($vacation->getDateTo())->days 1;
  56.         $availableDays $this->availableDayRepository->findOneBy(['user' => $user]);
  57.         $availableDays->setDays($availableDays->getDays() + $daysToAdd);
  58.         $this->entityManager->persist($availableDays);
  59.         $this->entityManager->flush();
  60.     }
  61. }