summaryrefslogtreecommitdiff
path: root/app/Models/StatsDAOSQLite.php
blob: 50b12d2c7535270c20af5a07eba00fd05bfac0a2 (plain)
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
declare(strict_types=1);

class FreshRSS_StatsDAOSQLite extends FreshRSS_StatsDAO {

	#[\Override]
	protected function sqlDateToIsoGranularity(string $field, int $precision, string $granularity): string {
		$offset = $this->getTimezoneOffset();
		return match ($granularity) {
			'day' => "strftime('%Y-%m-%d', ($field / $precision) + $offset, 'unixepoch')",
			'month' => "strftime('%Y-%m', ($field / $precision) + $offset, 'unixepoch')",
			'year' => "strftime('%Y', ($field / $precision) + $offset, 'unixepoch')",
			default => throw new InvalidArgumentException('Invalid date granularity'),
		};
	}

	#[\Override]
	protected function sqlFloor(string $s): string {
		return "CAST(($s) AS INT)";
	}

	/**
	 * @return array<int,int>
	 */
	#[\Override]
	protected function calculateEntryRepartitionPerFeedPerPeriod(string $period, ?int $feed = null): array {
		if ($feed) {
			$restrict = "WHERE e.id_feed = {$feed}";
		} else {
			$restrict = '';
		}
		$offset = $this->getTimezoneOffset();
		$sql = <<<SQL
SELECT strftime('{$period}', e.date + {$offset}, 'unixepoch') AS period
, COUNT(1) AS count
FROM `_entry` AS e
{$restrict}
GROUP BY period
ORDER BY period ASC
SQL;

		$res = $this->fetchAssoc($sql);
		if ($res == null) {
			return [];
		}

		$periodMax = match ($period) {
			'%H' => 24,
			'%w' => 7,
			'%m' => 12,
			default => 30,
		};

		$repartition = array_fill(0, $periodMax, 0);
		foreach ($res as $value) {
			$repartition[(int)$value['period']] = (int)$value['count'];
		}

		return $repartition;
	}
}