InMemoryOverridesRepository.php 1.94 KB
Newer Older
1
2
3
4
5
<?php


namespace Source\Gateways\Overrides;

Jacob Priddy's avatar
Jacob Priddy committed
6
7
8
use Carbon\Carbon;
use Source\Entities\Override;

9
10
class InMemoryOverridesRepository implements OverridesRepository
{
11
12
13
    /**
     * @var \Source\Entities\Override[]
     */
Jacob Priddy's avatar
Jacob Priddy committed
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
    protected array $overrides = [];

    /**
     * @inheritDoc
     */
    public function overrideHistoryForDoor(string $doorId): array
    {
        return array_filter($this->overrides, static function (Override $override) use ($doorId) {
            return $override->hasDoorIdOf($doorId);
        });
    }

    /**
     * @inheritDoc
     */
    public function overrideHistoryBetween(Carbon $begin, Carbon $end): array
    {
        return array_filter($this->overrides, static function (Override $override) use ($begin, $end) {
            return $override->isActiveForDate($begin) || $override->isActiveForDate($end);
        });
    }

    /**
     * @inheritDoc
     */
39
    public function activeOverrideForDoorBetween(string $doorId, Carbon $begin, Carbon $end): ?Override
Jacob Priddy's avatar
Jacob Priddy committed
40
    {
41
        $overrides = array_filter($this->overrides, static function (Override $override) use ($doorId, $begin, $end) {
Jacob Priddy's avatar
Jacob Priddy committed
42
43
44
            return $override->hasDoorIdOf($doorId) &&
                ($override->isActiveForDate($begin) || $override->isActiveForDate($end) ||
                    ($begin->isBefore($override->getStart()) && $end->isAfter($override->getEnd())));
Jacob Priddy's avatar
Jacob Priddy committed
45
        });
Jacob Priddy's avatar
Jacob Priddy committed
46

47
48
        return array_shift($overrides);
    }
Jacob Priddy's avatar
Jacob Priddy committed
49

50
51
52
53
54
55
    /**
     * @inheritDoc
     */
    public function addOverride(Override $override): ?Override
    {
        $this->overrides[] = $override;
Jacob Priddy's avatar
Jacob Priddy committed
56

57
        return $override;
Jacob Priddy's avatar
Jacob Priddy committed
58
59
60
61
62
    }

    /**
     * @inheritDoc
     */
63
    public function updateOverride(string $overrideId, Override $override): ?Override
Jacob Priddy's avatar
Jacob Priddy committed
64
    {
65
66
67
68
        $this->overrides = array_filter($this->overrides, static function (Override $o) use ($overrideId) {
            return !$o->hasIdOf($overrideId);
        });

Jacob Priddy's avatar
Jacob Priddy committed
69
70
71
72
        $this->overrides[] = $override;

        return $override;
    }
73
}