StatsDAOSQLite.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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
  34. , COUNT(1) AS count
  35. FROM `_entry` AS e
  36. {$restrict}
  37. GROUP BY period
  38. ORDER BY period ASC
  39. SQL;
  40. $res = $this->fetchAssoc($sql);
  41. if ($res == null) {
  42. return [];
  43. }
  44. $periodMax = match ($period) {
  45. '%H' => 24,
  46. '%w' => 7,
  47. '%m' => 12,
  48. default => 30,
  49. };
  50. $repartition = array_fill(0, $periodMax, 0);
  51. foreach ($res as $value) {
  52. $repartition[(int)$value['period']] = (int)$value['count'];
  53. }
  54. return $repartition;
  55. }
  56. }