DatabaseAttemptsRepository.php 1.57 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\Attempts;

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

class DatabaseAttemptsRepository implements AttemptsRepository
{
    use CastsTo;

    /**
     * @param \App\Attempt $attempt
     * @return \Source\Entities\Attempt
     */
    protected static function toAttempt(\App\Attempt $attempt): Attempt
    {
        return new Attempt(
21
            $attempt->getAttribute('id'),
22
            $attempt->getAttribute('door_id'),
23
24
            $attempt->getAttribute('created_at'),
            $attempt->getAttribute('updated_at')
25
26
27
28
29
30
        );
    }

    /**
     * @inheritDoc
     */
31
    public function getBetween(?Carbon $begin = null, ?Carbon $end = null, ?string $doorId = null): array
32
    {
Jacob Priddy's avatar
Jacob Priddy committed
33
        $query = \App\Attempt::query()->orderByDesc('created_at');
34

35
36
        if ($doorId) {
            $query->where('door_id', self::castToInt($doorId));
Jacob Priddy's avatar
Jacob Priddy committed
37
        }
38

Jacob Priddy's avatar
Jacob Priddy committed
39
40
41
42
43
44
45
        if ($begin && $end) {
            $query->whereBetween('created_at', [$begin, $end]);
        } elseif ($begin) {
            $query->where('created_at', '>', $begin);
        } elseif ($end) {
            $query->where('created_at', '<', $end);
        }
46
47
48

        return array_map(static function (\App\Attempt $attempt) {
            return self::toAttempt($attempt);
Jacob Priddy's avatar
Jacob Priddy committed
49
        }, $query->get()->values()->all());
50
51
52
53
54
    }

    /**
     * @inheritDoc
     */
Jacob Priddy's avatar
Jacob Priddy committed
55
    public function add(Attempt $attempt): ?Attempt
56
57
    {
        $a = new \App\Attempt();
58
        $a->setAttribute('door_id', $attempt->getDoorId());
Jacob Priddy's avatar
fix bug    
Jacob Priddy committed
59

Jacob Priddy's avatar
Jacob Priddy committed
60
61
62
        $a->save();

        return self::toAttempt($a);
63
64
    }
}