src/EventSubsriber/AddBookingStatsSubscriber.php line 26

  1. <?php
  2. namespace App\EventSubsriber;
  3. use App\BookingsEntity\Booking;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
  8. use Symfony\UX\Chartjs\Model\Chart;
  9. class AddBookingStatsSubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         protected ChartBuilderInterface $chartBuilder
  13.     ) {
  14.     }
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             AfterCrudActionEvent::class => 'afterCrudActionEvent',
  19.         ];
  20.     }
  21.     public function afterCrudActionEvent(AfterCrudActionEvent $event)
  22.     {
  23.         $context $event->getAdminContext();
  24.         $crud $context->getCrud();
  25.         if ($crud->getEntityFqcn() === Booking::class && $crud->getCurrentAction() === Action::INDEX) {
  26.             $parameters $event->getResponseParameters();
  27.             $paginator $event->getResponseParameters()->get('paginator');
  28.             $stats = [];
  29.             if ($paginator) {
  30.                 $results $paginator->getResults();
  31.                 $statsDonut $this->generateStatsDonut($results);
  32.                 $parameters->set('statsDonut'$statsDonut);
  33.             }
  34.             $event->addResponseParameters($parameters->all());
  35.         }
  36.     }
  37.     private function generateStatsDonut($results): Chart
  38.     {
  39.         $chart $this->chartBuilder->createChart(Chart::TYPE_DOUGHNUT);
  40.         $stats = [];
  41.         /** @var Booking $result */
  42.         foreach ($results as $result) {
  43.             if (!isset($stats[$result->getState()])) {
  44.                 $stats[$result->getState()] = 0;
  45.             }
  46.             $stats[$result->getState()]++;
  47.         }
  48.         $chart->setData([
  49.             'labels' => array_keys($stats),
  50.             'datasets' => [
  51.                 [
  52.                     'label' => 'Stati',
  53.                     'backgroundColor' => [
  54.                         'rgb(146, 197, 110)',
  55.                         'rgb(0, 98, 125)',
  56.                         'rgb(236, 95, 101)',
  57.                     ],
  58.                     'borderColor' => 'rgb(255, 255, 255)',
  59.                     'data' => array_values($stats),
  60.                 ],
  61.             ],
  62.         ]);
  63.         return $chart;
  64.     }
  65. }