ApiAbstract   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 18
eloc 77
c 0
b 0
f 0
dl 0
loc 189
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 11 2
A create() 0 22 3
A isEntityNotFound() 0 7 2
A __construct() 0 10 1
A delete() 0 16 3
A list() 0 18 2
A getUserIdentifier() 0 3 1
A update() 0 27 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Admin\Http\Controllers;
6
7
use AbterPhp\Framework\Databases\Queries\FoundRows;
8
use AbterPhp\Framework\Http\Service\Execute\IRepoService;
9
use Opulence\Http\Responses\Response;
10
use Opulence\Orm\OrmException;
11
use Opulence\Routing\Controller;
12
use Psr\Log\LoggerInterface;
13
14
abstract class ApiAbstract extends Controller
15
{
16
    use ApiResponseTrait;
17
    use ApiIssueTrait;
18
    use ApiDataTrait;
19
20
    public const LOG_MSG_CREATE_FAILURE = 'Creating %1$s failed.';
21
    public const LOG_MSG_UPDATE_FAILURE = 'Updating %1$s with id "%2$s" failed.';
22
    public const LOG_MSG_DELETE_FAILURE = 'Deleting %1$s with id "%2$s" failed.';
23
    public const LOG_MSG_GET_FAILURE    = 'Retrieving %1$s with id "%2$s" failed.';
24
    public const LOG_MSG_LIST_FAILURE   = 'Retrieving %1$s failed.';
25
26
    public const LOG_CONTEXT_EXCEPTION  = 'Exception';
27
    public const LOG_PREVIOUS_EXCEPTION = 'Previous exception #%d';
28
29
    public const ENTITY_SINGULAR = '';
30
    public const ENTITY_PLURAL   = '';
31
32
    protected LoggerInterface $logger;
33
34
    protected IRepoService $repoService;
35
36
    protected FoundRows $foundRows;
37
38
    /**
39
     * ApiAbstract constructor.
40
     *
41
     * @param LoggerInterface $logger
42
     * @param IRepoService    $repoService
43
     * @param FoundRows       $foundRows
44
     * @param string          $problemBaseUrl
45
     */
46
    public function __construct(
47
        LoggerInterface $logger,
48
        IRepoService $repoService,
49
        FoundRows $foundRows,
50
        string $problemBaseUrl
51
    ) {
52
        $this->logger         = $logger;
53
        $this->repoService    = $repoService;
54
        $this->foundRows      = $foundRows;
55
        $this->problemBaseUrl = $problemBaseUrl;
56
    }
57
58
    /**
59
     * @param string $entityId
60
     *
61
     * @return Response
62
     */
63
    public function get(string $entityId): Response
64
    {
65
        try {
66
            $entity = $this->repoService->retrieveEntity($entityId);
67
        } catch (\Exception $e) {
68
            $msg = sprintf(static::LOG_MSG_GET_FAILURE, static::ENTITY_SINGULAR, $entityId);
69
70
            return $this->handleException($msg, $e);
71
        }
72
73
        return $this->handleGetSuccess($entity);
74
    }
75
76
    /**
77
     * @return Response
78
     */
79
    public function list(): Response
80
    {
81
        $query = $this->request->getQuery();
82
83
        $offset = (int)$query->get('offset', 0);
84
        $limit  = (int)$query->get('limit', 100);
85
86
        try {
87
            $entities = $this->repoService->retrieveList($offset, $limit, [], [], []);
88
        } catch (\Exception $e) {
89
            $msg = sprintf(static::LOG_MSG_LIST_FAILURE, static::ENTITY_PLURAL);
90
91
            return $this->handleException($msg, $e);
92
        }
93
94
        $maxCount = $this->foundRows->get();
95
96
        return $this->handleListSuccess($entities, $maxCount);
97
    }
98
99
    /**
100
     * @return Response
101
     */
102
    public function create(): Response
103
    {
104
        try {
105
            $data = $this->getCreateData();
106
107
            $errors = $this->repoService->validateForm($data);
108
109
            if (count($errors) > 0) {
110
                $msg = sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR);
111
112
                return $this->handleErrors($msg, $errors);
113
            }
114
115
            $fileData = $this->getFileData($data);
116
            $entity   = $this->repoService->create($data, $fileData);
117
        } catch (\Exception $e) {
118
            $msg = sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR);
119
120
            return $this->handleException($msg, $e);
121
        }
122
123
        return $this->handleCreateSuccess($entity);
124
    }
125
126
    /**
127
     * @param string $entityId
128
     *
129
     * @return Response
130
     */
131
    public function update(string $entityId): Response
132
    {
133
        try {
134
            $data = $this->getUpdateData();
135
136
            $errors = $this->repoService->validateForm($data);
137
138
            if (count($errors) > 0) {
139
                $msg = sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId);
140
141
                return $this->handleErrors($msg, $errors);
142
            }
143
144
            $fileData = $this->getFileData($data);
145
            $entity   = $this->repoService->retrieveEntity($entityId);
146
            $this->repoService->update($entity, $data, $fileData);
147
        } catch (\Exception $e) {
148
            if ($this->isEntityNotFound($e)) {
149
                return $this->handleNotFound();
150
            }
151
152
            $msg = sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId);
153
154
            return $this->handleException($msg, $e);
155
        }
156
157
        return $this->handleUpdateSuccess($entity);
158
    }
159
160
    /**
161
     * @param string $entityId
162
     *
163
     * @return Response
164
     */
165
    public function delete(string $entityId): Response
166
    {
167
        try {
168
            $entity = $this->repoService->retrieveEntity($entityId);
169
            $this->repoService->delete($entity);
170
        } catch (\Exception $e) {
171
            if ($this->isEntityNotFound($e)) {
172
                return $this->handleNotFound();
173
            }
174
175
            $msg = sprintf(static::LOG_MSG_DELETE_FAILURE, static::ENTITY_SINGULAR, $entityId);
176
177
            return $this->handleException($msg, $e);
178
        }
179
180
        return $this->handleDeleteSuccess();
181
    }
182
183
    /**
184
     * @param \Exception $e
185
     *
186
     * @return bool
187
     */
188
    protected function isEntityNotFound(\Exception $e): bool
189
    {
190
        if (!($e instanceof OrmException)) {
191
            return false;
192
        }
193
194
        return $e->getMessage() === 'Failed to find entity';
195
    }
196
197
    /**
198
     * @return string
199
     */
200
    protected function getUserIdentifier(): string
201
    {
202
        return (string)$this->request->getHeaders()->get('xxx-user-username');
203
    }
204
}
205