Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
namespace App\Service;
use App\Dto\BarChart\BarChartInput;
use App\Dto\BarChart\BarChartOutput;
use Doctrine\ORM\EntityManagerInterface;
class BarChartService
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function getBarChartData(BarChartInput $input): array
{
$startDate = new \DateTimeImmutable($input->start);
$endDate = new \DateTimeImmutable($input->end);
echo "=================================================================";
$queryBuilder = $this->entityManager->createQueryBuilder();
// Sélectionnez la date avec le format approprié en fonction de la granularité
switch ($input->granularity) {
case 'day':
$selectExpression = 'DATE_FORMAT(s.date, \'%Y-%m-%d\')';
$groupByExpression = 's.date';
break;
case 'month':
$selectExpression = 'DATE_FORMAT(s.date, \'%Y-%m\')';
$groupByExpression = 'DATE_FORMAT(s.date, \'%Y-%m\')';
break;
case 'year':
$selectExpression = 'DATE_FORMAT(s.date, \'%Y\')';
$groupByExpression = 'DATE_FORMAT(s.date, \'%Y\')';
break;
default:
throw new \InvalidArgumentException('Invalid granularity');
}
$result = $queryBuilder
->select($selectExpression . ' as date', 'COUNT(s.id) as occurrences')
->from(Sale::class, 's')
->where('s.date BETWEEN :start AND :end')
->setParameter('start', $startDate)
->setParameter('end', $endDate)
->groupBy($groupByExpression)
->orderBy('date')
->getQuery()
->getResult();
$output = [];
foreach ($result as $row) {
$output[] = new BarChartOutput($row['date'], (int)$row['occurrences']);
}
return $output;
}
}