Passed
Push — master ( 760c61...42e827 )
by Peter
02:23
created

ApiAbstract::isEntityNotFound()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Http\Controllers;
6
7
use AbterPhp\Framework\Config\Provider as ConfigProvider;
8
use AbterPhp\Framework\Databases\Queries\FoundRows;
9
use AbterPhp\Framework\Http\Service\Execute\RepoServiceAbstract;
10
use Opulence\Http\Responses\Response;
11
use Opulence\Orm\OrmException;
12
use Opulence\Routing\Controller;
13
use Psr\Log\LoggerInterface;
14
15
abstract class ApiAbstract extends Controller
16
{
17
    use ApiResponseTrait;
18
    use ApiIssueTrait;
19
    use ApiDataTrait;
20
21
    const LOG_MSG_CREATE_FAILURE = 'Creating %1$s failed.';
22
    const LOG_MSG_UPDATE_FAILURE = 'Updating %1$s with id "%2$s" failed.';
23
    const LOG_MSG_DELETE_FAILURE = 'Deleting %1$s with id "%2$s" failed.';
24
    const LOG_MSG_GET_FAILURE    = 'Retrieving %1$s with id "%2$s" failed.';
25
    const LOG_MSG_LIST_FAILURE   = 'Retrieving %1$s failed.';
26
27
    const LOG_CONTEXT_EXCEPTION  = 'Exception';
28
    const LOG_PREVIOUS_EXCEPTION = 'Previous exception #%d';
29
30
    const ENTITY_SINGULAR = '';
31
    const ENTITY_PLURAL   = '';
32
33
    /** @var LoggerInterface */
34
    protected $logger;
35
36
    /** @var RepoService */
0 ignored issues
show
Bug introduced by
The type AbterPhp\Framework\Http\Controllers\RepoService was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
    protected $repoService;
38
39
    /** @var FoundRows */
40
    protected $foundRows;
41
42
    /**
43
     * ApiAbstract constructor.
44
     *
45
     * @param LoggerInterface     $logger
46
     * @param RepoServiceAbstract $repoService
47
     * @param FoundRows           $foundRows
48
     * @param ConfigProvider      $configProvider
49
     */
50
    public function __construct(
51
        LoggerInterface $logger,
52
        RepoServiceAbstract $repoService,
53
        FoundRows $foundRows,
54
        ConfigProvider $configProvider
55
    ) {
56
        $this->logger         = $logger;
57
        $this->repoService    = $repoService;
0 ignored issues
show
Documentation Bug introduced by
It seems like $repoService of type AbterPhp\Framework\Http\...ute\RepoServiceAbstract is incompatible with the declared type AbterPhp\Framework\Http\Controllers\RepoService of property $repoService.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
58
        $this->foundRows      = $foundRows;
59
        $this->problemBaseUrl = $configProvider->getProblemBaseUrl();
60
    }
61
62
    /**
63
     * @param string $entityId
64
     *
65
     * @return Response
66
     */
67
    public function get(string $entityId): Response
68
    {
69
        try {
70
            $entity = $this->repoService->retrieveEntity($entityId);
71
        } catch (\Exception $e) {
72
            $msg = sprintf(static::LOG_MSG_GET_FAILURE, static::ENTITY_SINGULAR, $entityId);
73
74
            return $this->handleException($msg, $e);
75
        }
76
77
        return $this->handleGetSuccess($entity);
78
    }
79
80
    /**
81
     * @return Response
82
     */
83
    public function list(): Response
84
    {
85
        $query = $this->request->getQuery();
86
87
        $offset = (int)$query->get('offset', 0);
88
        $limit  = (int)$query->get('limit', 100);
89
90
        try {
91
            $entities = $this->repoService->retrieveList($offset, $limit, [], [], []);
92
        } catch (\Exception $e) {
93
            $msg = sprintf(static::LOG_MSG_LIST_FAILURE, static::ENTITY_PLURAL);
94
95
            return $this->handleException($msg, $e);
96
        }
97
98
        $maxCount = $this->foundRows->get();
99
100
        return $this->handleListSuccess($entities, $maxCount);
101
    }
102
103
    /**
104
     * @return Response
105
     */
106
    public function create(): Response
107
    {
108
        try {
109
            $data = $this->getCreateData();
110
111
            $errors = $this->repoService->validateForm($data);
112
113
            if (count($errors) > 0) {
114
                $msg = sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR);
115
116
                return $this->handleErrors($msg, $errors);
117
            }
118
119
            $fileData = $this->getFileData($data);
120
            $entity   = $this->repoService->create($data, $fileData);
121
        } catch (\Exception $e) {
122
            $msg = sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR);
123
124
            return $this->handleException($msg, $e);
125
        }
126
127
        return $this->handleCreateSuccess($entity);
128
    }
129
130
    /**
131
     * @param string $entityId
132
     *
133
     * @return Response
134
     */
135
    public function update(string $entityId): Response
136
    {
137
        try {
138
            $data = $this->getUpdateData();
139
140
            $errors = $this->repoService->validateForm($data);
141
142
            if (count($errors) > 0) {
143
                $msg = sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId);
144
145
                return $this->handleErrors($msg, $errors);
146
            }
147
148
            $fileData = $this->getFileData($data);
149
            $entity   = $this->repoService->retrieveEntity($entityId);
150
            $this->repoService->update($entity, $data, $fileData);
151
        } catch (\Exception $e) {
152
            if ($this->isEntityNotFound($e)) {
153
                return $this->handleNotFound();
154
            }
155
156
            $msg = sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId);
157
158
            return $this->handleException($msg, $e);
159
        }
160
161
        return $this->handleUpdateSuccess($entity);
162
    }
163
164
    /**
165
     * @param string $entityId
166
     *
167
     * @return Response
168
     */
169
    public function delete(string $entityId): Response
170
    {
171
        try {
172
            $entity = $this->repoService->retrieveEntity($entityId);
173
            $this->repoService->delete($entity);
174
        } catch (\Exception $e) {
175
            if ($this->isEntityNotFound($e)) {
176
                return $this->handleNotFound();
177
            }
178
179
            $msg = sprintf(static::LOG_MSG_DELETE_FAILURE, static::ENTITY_SINGULAR, $entityId);
180
181
            return $this->handleException($msg, $e);
182
        }
183
184
        return $this->handleDeleteSuccess();
185
    }
186
187
    /**
188
     * @param \Exception $e
189
     *
190
     * @return bool
191
     */
192
    protected function isEntityNotFound(\Exception $e): bool
193
    {
194
        if (!($e instanceof OrmException)) {
195
            return false;
196
        }
197
198
        return $e->getMessage() === 'Failed to find entity';
199
    }
200
201
    /**
202
     * @return string
203
     */
204
    protected function getUserIdentifier(): string
205
    {
206
        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...
207
    }
208
}
209