Passed
Push — master ( f85738...3d85c1 )
by Peter
04:52
created

ApiAbstract::update()   A

Complexity

Conditions 4
Paths 18

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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