Completed
Push — master ( b90fcd...1ead19 )
by Pierre
03:17
created

Restful::index()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 11
ccs 9
cts 10
cp 0.9
crap 2.004
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Api\V1;
4
5
use Nymfonya\Component\Container;
6
use Nymfonya\Component\Http\Response;
7
use App\Interfaces\Controllers\IApi;
8
use App\Interfaces\Controllers\IRestful;
9
use App\Reuse\Controllers\AbstractApi;
10
use App\Model\Repository\Users;
11
use App\Component\Db\Core;
12
use OpenApi\Annotations as OA;
13
14
/**
15
 * @OA\Info(
16
 *     version="1.0",
17
 *     title="Api Restful Controller"
18
 * )
19
 */
20
final class Restful extends AbstractApi implements IApi, IRestful
21
{
22
23
    const _ID='id';
24
25
    /**
26
     * core db instance
27
     *
28
     * @var Core
29
     */
30
    protected $db;
31
32
    /**
33
     * user repository
34
     *
35
     * @var Users
36
     */
37
    protected $userRepository;
38
39
    /**
40
     * slugs
41
     *
42
     * @var array
43
     */
44
    protected $slugs;
45
46
    /**
47
     * sql
48
     *
49
     * @var String
50
     */
51
    protected $sql;
52
53
    /**
54
     * sql values to bind statement
55
     *
56
     * @var array
57
     */
58
    protected $bindValues;
59
60
    /**
61
     * error
62
     *
63
     * @var Boolean
64
     */
65
    protected $error;
66
67
    /**
68
     * error message
69
     *
70
     * @var String
71
     */
72
    protected $errorMessage;
73
74
    /**
75
     * instanciate
76
     *
77
     * @param Container $container
78
     */
79 11
    public function __construct(Container $container)
80
    {
81 11
        $this->userRepository = new Users($container);
82 11
        $this->db = new Core($container);
83 11
        $this->db->fromOrm($this->userRepository);
84 11
        $this->error = false;
85 11
        $this->errorMessage = '';
86 11
        parent::__construct($container);
87
    }
88
89
    /**
90
     * index
91
     *
92
     * @OA\Get(
93
     *     path="/api/v1/restful/index",
94
     *     summary="Search for a something item",
95
     *     @OA\RequestBody(
96
     *         @OA\MediaType(
97
     *             mediaType="application/json",
98
     *             @OA\Schema(
99
     *                 @OA\Property(
100
     *                     property="id",
101
     *                     type="string"
102
     *                 ),
103
     *                 @OA\Property(
104
     *                     property="name",
105
     *                     type="string"
106
     *                 ),
107
     *                 example={"id": 10}
108
     *             )
109
     *         )
110
     *     ),
111
     *     @OA\Response(
112
     *         response=200,
113
     *         description="OK"
114
     *     )
115
     * )
116
     * @return Restful
117
     */
118 1
    final public function index(array $slugs = []): Restful
119
    {
120 1
        $this->slugs = $slugs;
121 1
        $where = (isset($slugs[self::_ID]))
122
            ? [self::_ID => $slugs[self::_ID]]
123 1
            : [];
124 1
        $this->userRepository->find(['*'], $where);
125 1
        $this->sql = $this->userRepository->getSql();
126 1
        $this->bindValues = $this->userRepository->getBuilderValues();
127 1
        $this->db->run($this->sql, $this->bindValues)->hydrate();
128 1
        return $this->setResponse(__CLASS__, __FUNCTION__);
129
    }
130
131
    /**
132
     * store
133
     *
134
     * @OA\Post(
135
     *     path="/api/v1/restful",
136
     *     summary="Adds a new something item",
137
     *     @OA\RequestBody(
138
     *         @OA\MediaType(
139
     *             mediaType="application/json",
140
     *             @OA\Schema(
141
     *                 @OA\Property(
142
     *                     property="id",
143
     *                     type="string"
144
     *                 ),
145
     *                 @OA\Property(
146
     *                     property="name",
147
     *                     type="string"
148
     *                 ),
149
     *                 example={"id": 10, "name": "Jessica Smith"}
150
     *             )
151
     *         )
152
     *     ),
153
     *     @OA\Response(
154
     *         response=200,
155
     *         description="OK"
156
     *     )
157
     * )
158
     * @return Restful
159
     */
160 2
    final public function store(array $slugs = []): Restful
161
    {
162 2
        $this->slugs = $slugs;
163 2
        $this->bindValues = [];
164
        try {
165 2
            $this->userRepository->insert($this->getParams());
166 1
            $this->sql = $this->userRepository->getSql();
167 1
            $this->bindValues = $this->userRepository->getBuilderValues();
168 1
            $this->db->run($this->sql, $this->bindValues)->hydrate();
169 1
        } catch (\Exception $e) {
170 1
            $this->error = true;
171 1
            $this->errorMessage = $e->getMessage();
172 1
            $this->sql = '';
173
        }
174 2
        return $this->setResponse(__CLASS__, __FUNCTION__);
175
    }
176
177
    /**
178
     * update
179
     *
180
     * @OA\Put(
181
     *     path="/api/v1/restful",
182
     *     summary="Modify something item",
183
     *     @OA\RequestBody(
184
     *         @OA\MediaType(
185
     *             mediaType="application/json",
186
     *             @OA\Schema(
187
     *                 @OA\Property(
188
     *                     property="id",
189
     *                     type="string"
190
     *                 ),
191
     *                 @OA\Property(
192
     *                     property="name",
193
     *                     type="string"
194
     *                 ),
195
     *                 example={"id": 10, "name": "Jessica Smoke"}
196
     *             )
197
     *         )
198
     *     ),
199
     *     @OA\Response(
200
     *         response=200,
201
     *         description="OK"
202
     *     )
203
     * )
204
     * @return Restful
205
     */
206 2
    final public function update(array $slugs = []): Restful
207
    {
208 2
        $this->slugs = $slugs;
209 2
        $this->bindValues = [];
210
        try {
211 2
            $params = $this->getParams();
212 2
            $pk = $this->userRepository->getPrimary();
213 2
            if (false === isset($params[$pk])) {
214 1
                throw new \Exception('Missing primary : ' . $pk);
215
            }
216 1
            $pkValue = $params[$pk];
217 1
            unset($params[$pk]);
218 1
            $this->userRepository->update($params, [$pk => $pkValue]);
219 1
            $this->sql = $this->userRepository->getSql();
220 1
            $this->bindValues = $this->userRepository->getBuilderValues();
221 1
            $this->db->run($this->sql, $this->bindValues);
222 1
        } catch (\Exception $e) {
223 1
            $this->error = true;
224 1
            $this->errorMessage = $e->getMessage();
225 1
            $this->sql = '';
226
        }
227 2
        return $this->setResponse(__CLASS__, __FUNCTION__);
228
    }
229
230
    /**
231
     * delete
232
     *
233
     * @OA\Delete(
234
     *     path="/api/v1/restful",
235
     *     summary="Delete something item",
236
     *     @OA\RequestBody(
237
     *         @OA\MediaType(
238
     *             mediaType="application/json",
239
     *             @OA\Schema(
240
     *                 @OA\Property(
241
     *                     property="id",
242
     *                     type="string"
243
     *                 ),
244
     *                 example={"id": 10}
245
     *             )
246
     *         )
247
     *     ),
248
     *     @OA\Response(
249
     *         response=200,
250
     *         description="OK"
251
     *     )
252
     * )
253
     * @return Restful
254
     */
255 2
    final public function delete(array $slugs = []): Restful
256
    {
257 2
        $this->slugs = $slugs;
258 2
        $this->bindValues = [];
259
        try {
260 2
            $params = $this->getParams();
261 2
            $pk = $this->userRepository->getPrimary();
262 2
            if (false === isset($params[$pk])) {
263 1
                throw new \Exception('Missing primary : ' . $pk);
264
            }
265 1
            $this->userRepository->delete([$pk => $params[$pk]]);
266 1
            $this->sql = $this->userRepository->getSql();
267 1
            $this->bindValues = $this->userRepository->getBuilderValues();
268 1
            $this->db->run($this->sql, $this->bindValues);
269 1
        } catch (\Exception $e) {
270 1
            $this->error = true;
271 1
            $this->errorMessage = $e->getMessage();
272 1
            $this->sql = '';
273
        }
274 2
        return $this->setResponse(__CLASS__, __FUNCTION__);
275
    }
276
277
    /**
278
     * set response with for a classname and action
279
     *
280
     * @param string $classname
281
     * @param string $action
282
     * @return Restful
283
     */
284 1
    protected function setResponse(string $classname, string $action): Restful
285
    {
286 1
        $this->response
287 1
            ->setCode($this->getStatusCode())
288 1
            ->setContent(
289
                [
290 1
                    'error' => $this->error,
291 1
                    'errorMessage' => $this->errorMessage,
292
                    'datas' => [
293 1
                        'method' => $this->getRequest()->getMethod(),
294 1
                        'params' => $this->getParams(),
295 1
                        'controller' => $classname,
296 1
                        'action' => $action,
297 1
                        'query' => $this->sql,
298 1
                        'queryValues' => $this->bindValues,
299 1
                        'slugs' => $this->slugs,
300 1
                        'rowset' => $this->db->getRowset()
301
                    ]
302
                ]
303
            );
304 1
        return $this;
305
    }
306
307
    /**
308
     * returns true if error happened
309
     *
310
     * @return boolean
311
     */
312 7
    protected function isError(): bool
313
    {
314 7
        return $this->error === true;
315
    }
316
317
    /**
318
     * returns http status code
319
     *
320
     * @return int
321
     */
322 7
    protected function getStatusCode(): int
323
    {
324 7
        return (true === $this->isError())
325 3
            ? Response::HTTP_BAD_REQUEST
326 7
            : Response::HTTP_OK;
327
    }
328
}
329