InMemoryRequestsRepository.php 2.51 KB
Newer Older
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php


namespace Source\Gateways\Requests;

use Source\Entities\Request;
use Source\Exceptions\EntityNotFoundException;

class InMemoryRequestsRepository implements RequestsRepository
{
    /**
     * @var \Source\Entities\Request[]
     */
    protected array $requests = [];

    /**
     * @inheritDoc
     */
    public function create(Request $request): Request
    {
        $this->requests[] = $request;
        return $request;
    }

    /**
     * @inheritDoc
     */
    public function search(?string $query = null): array
    {
        if (!$query) {
            return $this->requests;
        }

        return array_filter($this->requests, static function (Request $request) use ($query): bool {
            return stripos($request->getTitle(), $query) !== false
                || stripos($request->getRequest(), $query) !== false
                || stripos($request->getReply(), $query) !== false;
        });
    }

    /**
     * @inheritDoc
     */
    public function pending(): array
    {
        return array_filter($this->requests, fn (Request $request) => $request->getAccepted() === null);
    }

    /**
     * @inheritDoc
     */
    public function get(string $requestId): ?Request
    {
        foreach ($this->requests as $request) {
            if ($request->hasIdOf($requestId)) {
                return $request;
            }
        }

        return null;
    }

    /**
     * @inheritDoc
     */
    public function filter(?string $userId = null, ?bool $accepted = null, ?bool $replied = null): array
    {
        $requests = $this->requests;

        if ($userId !== null) {
            $requests = array_filter($requests, fn (Request $request) => $request->hasUserIdOf($userId));
        }

        if ($accepted !== null) {
            $requests = array_filter($requests, fn (Request $request) => $request->getAccepted() === $accepted);
        }

        if ($replied !== null) {
            $requests = array_filter($requests, fn (Request $request) => $request->getAccepted() !== null || $request->getReply() !== null);
        }

        return $requests;
    }

    /**
     * @inheritDoc
     */
    public function update(string $requestId, Request $request): Request
    {
        foreach ($this->requests as &$requestBase) {
            if ($requestBase->hasIdOf($requestId)) {
                $request->setId($requestBase->getId());

                $requestBase = $request;

                return $requestBase;
            }
        }

        throw new EntityNotFoundException('Request not found.');
    }
}