src/EventSubsriber/AddBookingStatsSubscriber.php line 26
<?php
namespace App\EventSubsriber;
use App\BookingsEntity\Booking;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
use Symfony\UX\Chartjs\Model\Chart;
class AddBookingStatsSubscriber implements EventSubscriberInterface
{
public function __construct(
protected ChartBuilderInterface $chartBuilder
) {
}
public static function getSubscribedEvents(): array
{
return [
AfterCrudActionEvent::class => 'afterCrudActionEvent',
];
}
public function afterCrudActionEvent(AfterCrudActionEvent $event)
{
$context = $event->getAdminContext();
$crud = $context->getCrud();
if ($crud->getEntityFqcn() === Booking::class && $crud->getCurrentAction() === Action::INDEX) {
$parameters = $event->getResponseParameters();
$paginator = $event->getResponseParameters()->get('paginator');
$stats = [];
if ($paginator) {
$results = $paginator->getResults();
$statsDonut = $this->generateStatsDonut($results);
$parameters->set('statsDonut', $statsDonut);
}
$event->addResponseParameters($parameters->all());
}
}
private function generateStatsDonut($results): Chart
{
$chart = $this->chartBuilder->createChart(Chart::TYPE_DOUGHNUT);
$stats = [];
/** @var Booking $result */
foreach ($results as $result) {
if (!isset($stats[$result->getState()])) {
$stats[$result->getState()] = 0;
}
$stats[$result->getState()]++;
}
$chart->setData([
'labels' => array_keys($stats),
'datasets' => [
[
'label' => 'Stati',
'backgroundColor' => [
'rgb(146, 197, 110)',
'rgb(0, 98, 125)',
'rgb(236, 95, 101)',
],
'borderColor' => 'rgb(255, 255, 255)',
'data' => array_values($stats),
],
],
]);
return $chart;
}
}