summaryrefslogtreecommitdiff
path: root/src/Controllers/EntriesController.php
blob: 13aa8e022a1d0dea2dd030e6e5a75b86f0fa417b (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php

namespace FlatFileForms\Controllers;

use Yosymfony\Toml\Toml;

class EntriesController
{
  public function getEntries()
  {
    /**@var Utilities $utilities*/
    global $utilities;

    $entries = [];

    $dateFrom = new \DateTime($_GET['dateFrom']);
    $dateTo = new \DateTime($_GET['dateTo'] ?? 'now');

    $dateRangeYears = range($dateFrom->format('Y'), $dateTo->format('Y'));
    $dateRangeYearsCount = count($dateRangeYears);
    foreach ($dateRangeYears as $dateRangeYearIdx => $dateRangeYear) {
      $yearPath = "$formPath/entries/$dateRangeYear";
      if (! is_dir($yearPath)) {
        continue;
      }

      if ($dateRangeYearsCount === 1) {
        $dateRangeMonths = range($dateFrom->format('m'), $dateTo->format('m'));
      }
      else if ($dateRangeYearIdx === 0) {
        $dateRangeMonths = range($dateFrom->format('m'), 12);
      }
      else if ($dateRangeYearIdx === $dateRangeYearsCount - 1) {
        $dateRangeMonths = range(1, $dateTo->format('m'));
      }
      else {
        $dateRangeMonths = range(1, 12);
      }

      $dateRangeMonthsCount = count($dateRangeMonths);
      foreach ($dateRangeMonths as $dateRangeMonthIdx => $dateRangeMonth) {
        $monthPath = "$yearPath/" . sprintf('%02d', $dateRangeMonth);
        if (! is_dir($monthPath)) {
          continue;
        }

        if ($dateRangeMonthsCount === 1) {
          $dateRangeDays = range($dateFrom->format('d'), $dateTo->format('d'));
        }
        else if ($dateRangeYearIdx === 0 && $dateRangeMonthIdx === 0) {
          $dateRangeDays = range($dateFrom->format('d'), 31);
        }
        else if ($dateRangeYearIdx === $dateRangeYearsCount - 1 && $dateRangeMonthIdx === $dateRangeMonthsCount - 1) {
          $dateRangeDays = range(1, $dateTo->format('d'));
        }
        else {
          $dateRangeDays = range(1, 31);
        }

        foreach ($dateRangeDays as $dateRangeDay) {
          $dayPath = "$monthPath/" . sprintf('%02d', $dateRangeDay);
          if (! is_dir($dayPath)) {
            continue;
          }

          $entriesForDay = $utilities->scandir($dayPath);
          foreach ($entriesForDay as $entryForDay) {
            $entry = Toml::parseFile("$dayPath/$entryForDay");
            if (isset($_GET['flat'])) {
              $entries[] = $entry;
            } else {
              $entries[$dateRangeYear][$dateRangeMonth][$dateRangeDay][] = $entry;
            }
          }
        }

      }
    }

    $content['data'] = $entries;

    return $content;
  }
}