DatabaseEntriesRepository.php 1.91 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_location'),
24
25
26
            $entry->getAttribute('success'),
            $entry->getAttribute('created_at'),
            $entry->getAttribute('updated_at')
27
28
29
30
31
32
        );
    }

    /**
     * @inheritDoc
     */
33
    public function add(Entry $entry): ?Entry
34
35
    {
        $e = new \App\Entry();
36
        $e->setAttribute('user_id', $entry->getUserId());
37
        $e->setAttribute('door_location', $entry->getDoorLocation());
38
        $e->setAttribute('success', $entry->wasSuccessful());
39
40
41
42
43
44
45
46
47
48
49

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

        return self::toEntry($e);
    }

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

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

58
59
        if ($doorLocation) {
            $query->where('door_location', 'ILIKE', "%$doorLocation%");
Jacob Priddy's avatar
Jacob Priddy committed
60
61
62
63
        }

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

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