StatsDAOSQLite.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_StatsDAOSQLite extends FreshRSS_StatsDAO {
  4. #[\Override]
  5. protected function sqlDateToIsoGranularity(string $field, int $precision, string $granularity): string {
  6. if (!preg_match('/^[a-zA-Z0-9_.]+$/', $field)) {
  7. throw new InvalidArgumentException('Invalid date field!');
  8. }
  9. $offset = $this->getTimezoneOffset();
  10. return match ($granularity) {
  11. 'day' => "strftime('%Y-%m-%d', ($field / $precision) + $offset, 'unixepoch')",
  12. 'month' => "strftime('%Y-%m', ($field / $precision) + $offset, 'unixepoch')",
  13. 'year' => "strftime('%Y', ($field / $precision) + $offset, 'unixepoch')",
  14. default => throw new InvalidArgumentException('Invalid date granularity'),
  15. };
  16. }
  17. #[\Override]
  18. protected function sqlFloor(string $s): string {
  19. return "CAST(($s) AS INT)";
  20. }
  21. /**
  22. * @return array<int,int>
  23. */
  24. #[\Override]
  25. protected function calculateEntryRepartitionPerFeedPerPeriod(string $period, ?int $feed = null): array {
  26. if ($feed) {
  27. $restrict = "WHERE e.id_feed = {$feed}";
  28. } else {
  29. $restrict = '';
  30. }
  31. $offset = $this->getTimezoneOffset();
  32. $sql = <<<SQL
  33. SELECT strftime('{$period}', e.date + {$offset}, 'unixepoch') AS period, COUNT(1) AS count
  34. FROM `_entry` AS e
  35. {$restrict}
  36. GROUP BY period
  37. ORDER BY period ASC
  38. SQL;
  39. $res = $this->fetchAssoc($sql);
  40. if ($res == null) {
  41. return [];
  42. }
  43. $periodMax = match ($period) {
  44. '%H' => 24,
  45. '%w' => 7,
  46. '%m' => 12,
  47. default => 30,
  48. };
  49. $repartition = array_fill(0, $periodMax, 0);
  50. foreach ($res as $value) {
  51. $repartition[(int)$value['period']] = (int)$value['count'];
  52. }
  53. return $repartition;
  54. }
  55. }