src/Twig/AppExtension.php line 200

Open in your IDE?
  1. <?php
  2. namespace App\Twig;
  3. use DateTime;
  4. use Twig\TwigTest;
  5. use App\Entity\Club;
  6. use App\Entity\User;
  7. use Twig\TwigFilter;
  8. use App\Entity\Coach;
  9. use App\Entity\Course;
  10. use Twig\TwigFunction;
  11. use App\Entity\Category;
  12. use App\Entity\ClubInfo;
  13. use App\Entity\Operator;
  14. use App\Entity\CoachInfo;
  15. use App\Entity\Partnership;
  16. use App\Service\CourseService;
  17. use App\Entity\CourseAvailability;
  18. use App\Repository\NoteRepository;
  19. use App\Repository\CourseRepository;
  20. use App\Service\InternationalService;
  21. use Symfony\Component\Intl\Countries;
  22. use Twig\Extension\AbstractExtension;
  23. use App\Repository\CategoryRepository;
  24. use App\Repository\PartnershipRepository;
  25. use App\Repository\ConversationRepository;
  26. use App\Repository\WebsiteLanguageRepository;
  27. use App\Repository\CourseAvailabilityRepository;
  28. use App\Repository\NoteRequestRepository;
  29. use App\Repository\TraineeRepository;
  30. use Symfony\Component\HttpFoundation\RequestStack;
  31. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  32. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  33. class AppExtension extends AbstractExtension
  34. {
  35.     private $googleApiKeyBack;
  36.     public function __construct(
  37.         private ConversationRepository $conversationRepository,
  38.         private InternationalService $internationalService,
  39.         private CourseRepository $courseRepository,
  40.         private CourseAvailabilityRepository $courseAvailabilityRepository,
  41.         private RequestStack $requestStack,
  42.         private ParameterBagInterface $params,
  43.         private CategoryRepository $categoryRepository,
  44.         private WebsiteLanguageRepository $websiteLanguageRepository,
  45.         private UrlGeneratorInterface $router,
  46.         private CourseService $courseService,
  47.         private PartnershipRepository $partnershipRepository,
  48.         private NoteRepository $noteRepository,
  49.         private NoteRequestRepository $noteRequestRepository,
  50.         private TraineeRepository $traineeRepository
  51.     ) {
  52.         $this->googleApiKeyBack $this->params->get('api_key_google_back');
  53.     }
  54.     public function getTests()
  55.     {
  56.         return [
  57.             new TwigTest('instanceof', [$this'isInstanceof']),
  58.             new TwigTest('hasseveralavailabilities', [$this'hasSeveralAvailabilities']),
  59.             new TwigTest('fileexists', [$this'fileExists']),
  60.         ];
  61.     }
  62.     public function getFunctions()
  63.     {
  64.         return [
  65.             new TwigFunction('conversationBetween', [$this'conversationBetween']),
  66.             new TwigFunction('countunreadmessages', [$this'countUnreadMessages']),
  67.             new TwigFunction('haveCommonIntership', [$this'haveCommonIntership']),
  68.             new TwigFunction('articleCategoryInfos', [$this'articleCategoryInfos']),
  69.             new TwigFunction('getOtherPartner', [$this'getOtherPartner']),
  70.             new TwigFunction('getNotes', [$this'getNotes']),
  71.             new TwigFunction('getAverageNotes', [$this'getAverageNotes']),
  72.         ];
  73.     }
  74.     public function getFilters()
  75.     {
  76.         return [
  77.             new TwigFilter('nextdate', [$this'getNextDate']),
  78.             new TwigFilter('cheapestavailability', [$this'getCheapestAvailability']),
  79.             new TwigFilter('countryName', [$this'getCountryName']),
  80.             new TwigFilter('nextcalendarweek', [$this'getNextWeek']),
  81.             new TwigFilter('lastcalendarweek', [$this'getLastWeek']),
  82.             new TwigFilter('nextcalendarmonth', [$this'getNextMonth']),
  83.             new TwigFilter('lastcalendarmonth', [$this'getLastMonth']),
  84.             new TwigFilter('stringToDate', [$this'stringToDate']),
  85.             new TwigFilter('placeName', [$this'getPlaceName']),
  86.             new TwigFilter('getDifferenceDate', [$this'getDifferenceDate']),
  87.             new TwigFilter('courseTitleFromToken', [$this'courseTitleFromToken']),
  88.             new TwigFilter('proActiveCourses', [$this'proActiveCourses']),
  89.             new TwigFilter('countryPhoneCode', [$this'countryPhoneCode']),
  90.             new TwigFilter('userType', [$this'userType']),
  91.             new TwigFilter('statusReuqested', [$this'statusReuqested']),
  92.         ];
  93.     }
  94.     public function statusReuqested($email)
  95.     {
  96.         $user $this->traineeRepository->findOneBy(['email' => $email]);
  97.         if ($user) {
  98.             return 'registered';
  99.         }
  100.         return 'not-registered';
  101.     }
  102.     public function getNotes($pro)
  103.     {
  104.         $notes $this->noteRepository->getProNotes($pro);
  105.         return $notes;
  106.     }
  107.     public function getAverageNotes($pro)
  108.     {
  109.         $total 0;
  110.         $education 0;
  111.         $organization 0;
  112.         $count 0;
  113.         $notes $this->getNotes($pro);
  114.         foreach ($notes as $note) {
  115.             $organization += $note->getOrganization();
  116.             $education += $note->getEducation();
  117.             $count++;
  118.         }
  119.         $educationAverage $count != number_format((float)($education $count), 1'.''') : 0;
  120.         $organizationAverage $count != number_format((float)($organization $count), 1'.''') : 0;
  121.         
  122.         $totalAverage $count != number_format((float)(($education $organization) / ($count 2)), 1'.''') : 0;
  123.         $average = [
  124.             'education' => $count != $educationAverage 0,
  125.             'organization' => $count != $organizationAverage 0,
  126.             'total' => $count != $totalAverage 0,
  127.             'count' => $count
  128.         ];
  129.         return $average;
  130.         
  131.     }
  132.     public function getOtherPartner(Partnership $partnership$pro)
  133.     {
  134.         // Vérifie si le pro est un Coach et trouve l'autre professionnel
  135.         if ($partnership->getCoach() === $pro) {
  136.             return $partnership->getClub() ?? $partnership->getOperator();
  137.         }
  138.         // Vérifie si le pro est un Club et trouve l'autre professionnel
  139.         if ($partnership->getClub() === $pro) {
  140.             return $partnership->getCoach() ?? $partnership->getOperator();
  141.         }
  142.         // Vérifie si le pro est un Opérateur et trouve l'autre professionnel
  143.         if ($partnership->getOperator() === $pro) {
  144.             return $partnership->getCoach() ?? $partnership->getClub();
  145.         }
  146.         // Si le pro est le demandeur du partenariat, retourne l'autre professionnel
  147.         if ($partnership->getRequestedBy() !== $pro) {
  148.             if ($partnership->getCoach() !== $pro) {
  149.                 return $partnership->getCoach();
  150.             } elseif ($partnership->getClub() !== $pro) {
  151.                 return $partnership->getClub();
  152.             } elseif ($partnership->getOperator() !== $pro) {
  153.                 return $partnership->getOperator();
  154.             }
  155.         }
  156.         return null// Si le pro n'est pas impliqué ou aucune condition ne correspond
  157.     }
  158.     function countryPhoneCode($countryCode)
  159.     {
  160.         return $this->internationalService->countryPhoneCode($countryCode);
  161.     }
  162.     public function articleCategoryInfos(Category $category$locale)
  163.     {
  164.         $language $this->websiteLanguageRepository->findOneBy(['slug' => $locale]);
  165.         $categoryTranslated $this->categoryRepository->findOneBy(['unit' => $category->getUnit(), 'websiteLanguage' => $language]);
  166.         return [
  167.             'title' => $categoryTranslated->getTitle(),
  168.             'link' => $this->router->generate('article_category', ['slug' => $categoryTranslated->getSlug()])
  169.         ];
  170.     }
  171.     public function haveCommonIntership(User $owner$partner)
  172.     {
  173.         return $this->courseRepository->areProTogetherOnActiveCourse($owner$partner);
  174.         if ($partner instanceof Club) {
  175.             $clubInfo $partner->getClubInfo();
  176.             $courses $this->courseRepository->count(['owner' => $owner'club' => $clubInfo'status' => 'active']);
  177.         } else if ($partner instanceof Coach) {
  178.             $coachInfo $partner->getCoachInfo();
  179.             $courses $this->courseRepository->countActiveCourseBetween($owner$coachInfo);
  180.         } else if ($partner instanceof Operator) {
  181.             $operatorInfo $partner->getOperatorInfo();
  182.             $courses $this->courseRepository->countActiveCourseBetween($partner$operatorInfo);
  183.         }
  184.         if ($courses == 0) {
  185.             return false;
  186.         }
  187.         return true;
  188.     }
  189.     public function isInstanceof($var$instance)
  190.     {
  191.         $reflexionClass = new \ReflectionClass($instance);
  192.         return $reflexionClass->isInstance($var);
  193.     }
  194.     function userType(User $user)
  195.     {
  196.         if ($user instanceof Coach) {
  197.             $type 'coach';
  198.         } elseif ($user instanceof Club) {
  199.             $type 'club';
  200.         } elseif ($user instanceof Operator) {
  201.             $type 'operator';
  202.         }
  203.         return $type;
  204.     }
  205.     public function getNextDate(Course $course$startingDate null)
  206.     {
  207.         $nextAvailability $this->courseService->getAvailabilities($course'single'$startingDate);
  208.         return $nextAvailability;
  209.         /*
  210.         if ($startingDate == null) {
  211.             $fromDate = new DateTime();
  212.             $fromDate->setTimestamp(strtotime('today midnight'));
  213.         } 
  214.         
  215.         else {
  216.             $fromDate = date_create_from_format('d/m/Y', $startingDate);
  217.         }
  218.         $date = null;
  219.         
  220.         $nextAvailability = new CourseAvailability();
  221.         $frequency = $course->getFrequency();
  222.         
  223.         if ($frequency == 'punctual') {
  224.             foreach ($course->getAvailabilities() as $availability) {
  225.                 $begin = date_create_from_format('d/m/Y', $availability->getBegin());
  226.                 if ($begin > $fromDate && ($date == null || $date > $begin)) {
  227.                     $date = $begin;
  228.                     $nextAvailability->setDuration($availability->getDuration())
  229.                         ->setPrice($availability->getPrice())
  230.                         ->setBegin($begin->format('d.m.y'))
  231.                         ->setEnd(date_create_from_format('d/m/Y', $availability->getEnd())->format('d.m.y'));
  232.                 }
  233.             }
  234.         } 
  235.         
  236.         else {
  237.             foreach ($course->getAvailabilities() as $availability) {
  238.                 $begin = date_create_from_format('d/m/Y', $availability->getBegin());
  239.                 $endDate = null;
  240.                 if ($availability->getEnd() != null) {
  241.                     $endDate = date_create_from_format('d/m/Y', $availability->getEnd());
  242.                 }
  243.                 if ($endDate == null || $endDate > $fromDate) {
  244.                     $startDay = $availability->getStartDate();
  245.                     $recurrence = $availability->getRecurrence();
  246.                     $currentDate = $begin;
  247.     
  248.                     switch ($startDay) {
  249.                         case 'mon':
  250.                             $startDay = 'monday';
  251.                             break;
  252.                         case 'tue':
  253.                             $startDay = 'tuesday';
  254.                             break;
  255.                         case 'wed':
  256.                             $startDay = 'wednesday';
  257.                             break;
  258.                         case 'thu':
  259.                             $startDay = 'thursday';
  260.                             break;
  261.                         case 'fri':
  262.                             $startDay = 'friday';
  263.                             break;
  264.                         case 'sat':
  265.                             $startDay = 'saturday';
  266.                             break;
  267.                         case 'sun':
  268.                             $startDay = 'sunday';
  269.                             break;
  270.                     }
  271.                     
  272.                     if($startDay) {
  273.                         if (strtolower($begin->format('l')) != $startDay) {
  274.                             $currentDate->modify("next {$startDay}");
  275.                         }
  276.                     }
  277.     
  278.                     switch ($recurrence) {
  279.                         case 'weekly':
  280.                             $nextRecurrence = "next {$startDay}";
  281.                             break;
  282.                         case 'monthly':
  283.                             $dayPosition = $availability->getDayPosition();
  284.                             if ($dayPosition == '1') {
  285.                                 $nextRecurrence = "first {$startDay} of next month";
  286.                             } else if ($dayPosition == '2') {
  287.                                 $nextRecurrence = "second {$startDay} of next month";
  288.                             } else if ($dayPosition == '3') {
  289.                                 $nextRecurrence = "third {$startDay} of next month";
  290.                             } else if ($dayPosition == '4') {
  291.                                 $nextRecurrence = "fourth {$startDay} of next month";
  292.                             }
  293.                             else if ($dayPosition == 'last') {
  294.                                 $nextRecurrence = "last {$startDay} of next month";
  295.                             }
  296.                             break;
  297.                     }
  298.                     while ($currentDate < $fromDate) {
  299.                         $currentDate->modify($nextRecurrence);
  300.                     }
  301.                     if ($date == null || $date > ($currentDate && ($endDate == null || $endDate > $date))) {
  302.                         $end = clone ($currentDate);
  303.                         $end->modify("+{$availability->getDuration()} days");
  304.                         $date = $currentDate;
  305.                         $nextAvailability->setDuration($availability->getDuration())
  306.                             ->setPrice($availability->getPrice())
  307.                             ->setBegin($begin->format('d.m.y'))
  308.                             ->setEnd($end->format('d.m.y'));
  309.                     }
  310.                 }
  311.             }
  312.         }
  313.         return $nextAvailability;
  314.         */
  315.     }
  316.     public function getCheapestAvailability(Course $course)
  317.     {
  318.         $cheapestAvailability null;
  319.         foreach ($course->getAvailabilities() as $availability) {
  320.             if ($cheapestAvailability == null || $cheapestAvailability->getPrice() > $availability->getPrice()) {
  321.                 $cheapestAvailability $availability;
  322.             }
  323.         }
  324.         return $cheapestAvailability;
  325.     }
  326.     public function getNextWeek($date)
  327.     {
  328.         $dateTime = new \DateTime($date);
  329.         $dateTime->modify('+1 week');
  330.         return $dateTime->format('Y-m-d');
  331.     }
  332.     public function getLastWeek($date)
  333.     {
  334.         $dateTime = new \DateTime($date);
  335.         $dateTime->modify('-1 week');
  336.         return $dateTime->format('Y-m-d');
  337.     }
  338.     public function getNextMonth($date)
  339.     {
  340.         $dateTime = new \DateTime($date);
  341.         $dateTime->modify('+1 month');
  342.         $dateTime->modify('first monday of this month');
  343.         return $dateTime->format('Y-m-d');
  344.     }
  345.     public function getLastMonth($date)
  346.     {
  347.         $dateTime = new \DateTime($date);
  348.         $dateTime->modify('-1 month');
  349.         $dateTime->modify('first monday of this month');
  350.         return $dateTime->format('Y-m-d');
  351.     }
  352.     public function stringToDate($string)
  353.     {
  354.         $date date_create_from_format('d.m.y'$string);
  355.         return ($date);
  356.     }
  357.     
  358.     public function getPlaceName($place$locale)
  359.     {
  360.         $response file_get_contents("https://maps.googleapis.com/maps/api/place/details/json?place_id={$place}&key={$this->googleApiKeyBack}&language={$locale}");
  361.  
  362.         $resultJson json_decode($response);
  363.         return $resultJson->result->formatted_address;
  364.     }
  365.     
  366.     public function getCountryName($countryCode$locale)
  367.     {
  368.         return Countries::getName($countryCode$locale);
  369.     }
  370.     public function getDifferenceDate($created)
  371.     {
  372.         $now date("Y-m-d");
  373.         $diff $now $created;
  374.         return $diff;
  375.     }
  376.     public function conversationBetween($pro$trainee)
  377.     {
  378.         $conversation $this->conversationRepository->findOneBy(['pro' => $pro'trainee' => $trainee]);
  379.         return $conversation $conversation->getToken() : null;
  380.     }
  381.     public function courseTitleFromToken($token)
  382.     {
  383.         $course $this->courseRepository->findOneBy(['token' => $token]);
  384.         $request $this->requestStack->getCurrentRequest();
  385.         try {
  386.             $courseName $course->getTranslatedContent($request->getLocale())->getName();
  387.         } catch (\Throwable $th) {
  388.             $courseName '';
  389.         }
  390.         return $courseName;
  391.     }
  392.     public function hasSeveralAvailabilities(Course $course$startingDate null)
  393.     {
  394.         if ($startingDate == null) {
  395.             $fromDate = new DateTime();
  396.             $fromDate->setTimestamp(strtotime('today midnight'));
  397.         } else {
  398.             $fromDate date_create_from_format('d/m/Y'$startingDate);
  399.         }
  400.         $nextAvailabilities = [];
  401.         $allAvailabilities $this->courseAvailabilityRepository->findAvailabilities($course);
  402.         $frequency $course->getFrequency();
  403.         if ($frequency == 'punctual') {
  404.             foreach ($allAvailabilities as $availability) {
  405.                 $begin date_create_from_format('d/m/Y'$availability->getBegin());
  406.                 if ($begin $fromDate) {
  407.                     $currentAvailability = new CourseAvailability();
  408.                     $currentAvailability->setDuration($availability->getDuration())
  409.                         ->setPrice($availability->getPrice())
  410.                         ->setBegin($begin->format('d.m.y'))
  411.                         ->setEnd(date_create_from_format('d/m/Y'$availability->getEnd())->format('d.m.y'));
  412.                     $nextAvailabilities[] = $currentAvailability;
  413.                 }
  414.             }
  415.         } else {
  416.             foreach ($allAvailabilities as $availability) {
  417.                 $begin date_create_from_format('d/m/Y'$availability->getBegin());
  418.                 $endDate null;
  419.                 if ($availability->getEnd() != null) {
  420.                     $endDate date_create_from_format('d/m/Y'$availability->getEnd());
  421.                 }
  422.                 if ($endDate == null || $endDate $fromDate) {
  423.                     $startDay $availability->getStartDate();
  424.                     $recurrence $availability->getRecurrence();
  425.                     $duration $availability->getDuration();
  426.                     $currentDate = clone ($begin);
  427.                     /*
  428.                     switch ($startDay) {
  429.                         case 'mon':
  430.                             $startDay = 'monday';
  431.                             break;
  432.                         case 'tue':
  433.                             $startDay = 'tuesday';
  434.                             break;
  435.                         case 'wed':
  436.                             $startDay = 'wednesday';
  437.                             break;
  438.                         case 'thu':
  439.                             $startDay = 'thursday';
  440.                             break;
  441.                         case 'fri':
  442.                             $startDay = 'friday';
  443.                             break;
  444.                         case 'sat':
  445.                             $startDay = 'saturday';
  446.                             break;
  447.                         case 'sun':
  448.                             $startDay = 'sunday';
  449.                             break;
  450.                     }
  451.                     */
  452.                     $currentDate->modify("next {$startDay}");
  453.                     switch ($recurrence) {
  454.                         case 'weekly':
  455.                             $nextRecurrence "next {$startDay}";
  456.                             break;
  457.                         case 'monthly':
  458.                             $dayPosition $availability->getDayPosition();
  459.                             if ($dayPosition == '1') {
  460.                                 $nextRecurrence "first {$startDay} of next month";
  461.                             } else if ($dayPosition == '2') {
  462.                                 $nextRecurrence "second {$startDay} of next month";
  463.                             } else if ($dayPosition == '3') {
  464.                                 $nextRecurrence "third {$startDay} of next month";
  465.                             } else if ($dayPosition == '4') {
  466.                                 $nextRecurrence "fourth {$startDay} of next month";
  467.                             } else if ($dayPosition == 'last') {
  468.                                 $nextRecurrence "last {$startDay} of next month";
  469.                             }
  470.                             break;
  471.                     }
  472.                     while ($currentDate $fromDate) {
  473.                         $currentDate->modify($nextRecurrence);
  474.                     }
  475.                     for ($i 0$i 10$i++) {
  476.                         $end = clone ($currentDate);
  477.                         $end->modify("+{$duration} days");
  478.                         $currentAvailability = new CourseAvailability();
  479.                         $currentAvailability->setDuration($duration)
  480.                             ->setPrice($availability->getPrice())
  481.                             ->setBegin($currentDate->format('d.m.y'))
  482.                             ->setEnd($end->format('d.m.y'));
  483.                         if ($endDate == null || $endDate $currentDate) {
  484.                             array_push($nextAvailabilities$currentAvailability);
  485.                         }
  486.                         $currentDate->modify($nextRecurrence);
  487.                     }
  488.                 }
  489.             }
  490.         }
  491.         if (count($nextAvailabilities) > 1) {
  492.             return true;
  493.         }
  494.         return false;
  495.     }
  496.     public function fileExists($file$directory)
  497.     {
  498.         if (file_exists($this->params->get($directory) . '/' $file)) {
  499.             return true;
  500.         }
  501.         return false;
  502.     }
  503.     public function countUnreadMessages($user)
  504.     {
  505.         $number 0;
  506.         $conversations $this->conversationRepository->getMessages($user);
  507.         foreach ($conversations as $conversation) {
  508.             $lastMessage $conversation->getLastMessage();
  509.             if ($lastMessage->getSender() != $user && $lastMessage->getIsReaded() == false) {
  510.                 $number++;
  511.             }
  512.         }
  513.         return $number;
  514.     }
  515.     public function proActiveCourses(User $pro)
  516.     {
  517.         return $this->courseRepository->countProActiveCourses($pro);
  518.     }
  519. }