DatabaseEntriesRepository.php 1.97 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php


namespace Source\Gateways\Entries;

use Carbon\Carbon;
use Source\Entities\Entry;
use Source\Sanitize\CastsTo;

class DatabaseEntriesRepository implements EntriesRepository
{
    use CastsTo;

    /**
     * @param \App\Entry $entry
     * @return \Source\Entities\Entry
     */
    protected static function toEntry(\App\Entry $entry): Entry
    {
        return new Entry(
21
22
            $entry->getAttribute('id'),
            $entry->getAttribute('user_id'),
23
            $entry->getAttribute('door_id'),
24
            $entry->getAttribute('success'),
Jacob Priddy's avatar
Jacob Priddy committed
25
            $entry->getAttribute('reason'),
26
27
            $entry->getAttribute('created_at'),
            $entry->getAttribute('updated_at')
28
29
30
31
32
33
        );
    }

    /**
     * @inheritDoc
     */
34
    public function add(Entry $entry): ?Entry
35
36
    {
        $e = new \App\Entry();
37
        $e->setAttribute('user_id', $entry->getUserId());
38
        $e->setAttribute('door_id', $entry->getDoorId());
Jacob Priddy's avatar
Jacob Priddy committed
39
        $e->setAttribute('reason', $entry->getReason());
40
        $e->setAttribute('success', $entry->wasSuccessful());
41
42
43
44
45
46
47
48
49
50
51

        if (!$e->save()) {
            return null;
        }

        return self::toEntry($e);
    }

    /**
     * @inheritDoc
     */
52
    public function get(?Carbon $begin = null, ?Carbon $end = null, ?string $userId = null, ?string $doorId = null): array
53
    {
Jacob Priddy's avatar
Jacob Priddy committed
54
55
56
        $query = \App\Entry::query()->orderByDesc('created_at');

        if ($userId) {
57
            $query->where('user_id', self::castToInt($userId));
Jacob Priddy's avatar
Jacob Priddy committed
58
59
        }

60
61
        if ($doorId) {
            $query->where('door_id', self::castToInt($doorId));
Jacob Priddy's avatar
Jacob Priddy committed
62
63
64
65
        }

        if ($begin && $end) {
            $query->whereBetween('created_at', [$begin, $end]);
Jacob Priddy's avatar
Jacob Priddy committed
66
        } elseif ($begin) {
Jacob Priddy's avatar
Jacob Priddy committed
67
            $query->where('created_at', '>', $begin);
Jacob Priddy's avatar
Jacob Priddy committed
68
        } elseif ($end) {
Jacob Priddy's avatar
Jacob Priddy committed
69
70
            $query->where('created_at', '<', $end);
        }
71
72
73

        return array_map(static function (\App\Entry $entry) {
            return self::toEntry($entry);
Jacob Priddy's avatar
Jacob Priddy committed
74
        }, $query->get()->values()->all());
75
76
    }
}