Completed
Push — master ( c631b6...ab9e5a )
by Mikael
01:55
created

RemServerController::catchAllDelete()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 11
cts 11
cp 1
rs 8.9617
c 0
b 0
f 0
cc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Anax\RemServer;
4
5
use Anax\Commons\ContainerInjectableInterface;
6
use Anax\Commons\ContainerInjectableTrait;
7
8
/**
9
 * A controller for the REM Server.
10
 */
11
class RemServerController implements ContainerInjectableInterface
12
{
13
    use ContainerInjectableTrait;
14
15
16
17
    /**
18
     * Initiate the REM server before each action, if it has not already
19
     * some dataset(s).
20
     *
21
     * @return void
22
     */
23 23
    public function initialize() : void
24
    {
25 23
        $rem = $this->di->get("remserver");
26
27 23
        if (!$rem->hasDataset()) {
28 13
            $rem->init();
29
        }
30 23
    }
31
32
33
34
    /**
35
     * Init or re-init the REM Server.
36
     *
37
     * @return array
38
     */
39 9 View Code Duplication
    public function initActionGet() : array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40
    {
41 9
        $rem = $this->di->get("remserver");
42 9
        $rem->init();
43
        $json = [
44 9
            "message" => "The session is initiated with the default dataset(s).",
45 9
            "dataset" => $rem->getDefaultDataset(),
46
        ];
47 9
        return [$json];
48
    }
49
50
51
52
    /**
53
     * Get a dataset $key or parts of it by using the querystring.
54
     *
55
     * @param array $args variadic argument containg all parts of the
56
     *                    request.
57
     *
58
     * @return array
59
     */
60 12
    public function catchAllGet(...$args) : array
61
    {
62 12
        $dataSetKey = $args[0] ?? null;
63 12
        $itemId = $args[1] ?? null;
64 12
        $rest = $args[2] ?? null;
65
66
        // Type check that $itemId is int
67
68 12
        if ($dataSetKey && is_null($itemId)) {
69 5
            return $this->getDataset($dataSetKey);
70 7
        } elseif ($dataSetKey && !is_null($itemId) && is_null($rest)) {
71 7
            return $this->getItem($dataSetKey, $itemId);
0 ignored issues
show
Documentation introduced by
$dataSetKey is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$itemId is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
        }
73
74
        return $this->catchAll($args);
0 ignored issues
show
Unused Code introduced by
The call to RemServerController::catchAll() has too many arguments starting with $args.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
75
    }
76
77
78
79
    /**
80
     * Get a dataset $key or parts of it by using the querystring.
81
     *
82
     * @param array $key to the dataset to get.
83
     *
84
     * @return array
85
     */
86 5
    public function getDataset($key) : array
87
    {
88 5
        $request = $this->di->get("request");
89 5
        $dataset = $this->di->get("remserver")->getDataset($key);
90 5
        $offset  = $request->getGet("offset", 0);
91 5
        $limit   = $request->getGet("limit", 25);
92
        $json = [
93 5
            "data" => array_slice($dataset, $offset, $limit),
94 5
            "offset" => $offset,
95 5
            "limit" => $limit,
96 5
            "total" => count($dataset)
97
        ];
98 5
        return [$json];
99
    }
100
101
102
103
    /**
104
     * Get one item from the dataset.
105
     *
106
     * @param string $key    for the dataset
107
     * @param int $itemId for the item to get
108
     *
109
     * @return array
110
     */
111 7 View Code Duplication
    public function getItem(string $key, int $itemId) : array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
    {
113 7
        $item = $this->di->get("remserver")->getItem($key, $itemId);
114 7
        if (!$item) {
115 2
            return [["message" => "The item is not found."]];
116
        }
117 6
        return [$item];
118
    }
119
120
121
122
    /**
123
     * Create a new item by getting the entry from the request body and add
124
     * to the dataset.
125
     *
126
     * @param string $key for the dataset
0 ignored issues
show
Bug introduced by
There is no parameter named $key. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
127
     *
128
     * @return array
129
     */
130 4
    public function catchAllPost(...$args) : array
131
    {
132 4
        $dataSetKey = $args[0] ?? null;
133
134 4
        if (is_null($dataSetKey)) {
135
            return $this->catchAll();
136
        }
137
138
        try {
139 4
            $entry = $this->getRequestBody();
140 2
        } catch (Exception $e) {
141
            return [
142 2
                ["message" => "500. HTTP request body is not an object/array or valid JSON."],
143
                500
144
            ];
145
        }
146
147 2
        $item = $this->di->get("remserver")->addItem($dataSetKey, $entry);
148 2
        return [$item];
149
    }
150
151
152
    /**
153
     * Upsert/replace an item in the dataset, entry is taken from request body.
154
     *
155
     * @param string $key    for the dataset
0 ignored issues
show
Bug introduced by
There is no parameter named $key. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
156
     * @param string $itemId where to save the entry
0 ignored issues
show
Bug introduced by
There is no parameter named $itemId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
157
     *
158
     * @return void
159
     */
160 4
    public function catchAllPut(...$args) : array
161
    {
162 4
        $dataSetKey = $args[0] ?? null;
163 4
        $itemId = $args[1] ?? null;
164
165 4
        if (!($dataSetKey && !is_null($itemId))) {
166
            return $this->catchAll($args);
0 ignored issues
show
Unused Code introduced by
The call to RemServerController::catchAll() has too many arguments starting with $args.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
167
        }
168
169
        // This should be managed through the typed route
170 4
        $itemId = intval($itemId);
171
172
        try {
173 4
            $entry = $this->getRequestBody();
174 2
        } catch (Exception $e) {
175
            return [
176 2
                ["message" => "500. HTTP request body is not an object/array or valid JSON."],
177
                500
178
            ];
179
        }
180
181 2
        $item = $this->di->get("remserver")->upsertItem($dataSetKey, $itemId, $entry);
182 2
        return [$item];
183
    }
184
185
186
187
    /**
188
     * Delete an item from the dataset.
189
     *
190
     * @param string $key    for the dataset
0 ignored issues
show
Bug introduced by
There is no parameter named $key. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
191
     * @param string $itemId for the item to delete
0 ignored issues
show
Bug introduced by
There is no parameter named $itemId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
192
     *
193
     * @return array
194
     */
195 5
    public function catchAllDelete(...$args) : array
196
    {
197 5
        $dataSetKey = $args[0] ?? null;
198 5
        $itemId = $args[1] ?? null;
199
200 5
        if (!($dataSetKey && !is_null($itemId))
201 5
            || count($args) != 2
202 5
            || !(is_int($itemId) || ctype_digit($itemId))
203
        ) {
204 2
            return $this->catchAll($args);
0 ignored issues
show
Unused Code introduced by
The call to RemServerController::catchAll() has too many arguments starting with $args.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
205
        }
206
207
        // This should be managed through the typed route
208 3
        $itemId = intval($itemId);
209
210 3
        $this->di->get("remserver")->deleteItem($dataSetKey, $itemId);
211
        $json = [
212 3
            "message" => "Item id '$itemId' was deleted from dataset '$dataSetKey'.",
213
        ];
214 3
        return [$json];
215
    }
216
217
218
219
    /**
220
     * Get the request body from the HTTP request and treat it as
221
     * JSON data.
222
     *
223
     * @throws Exception when request body is invalid JSON.
224
     *
225
     * @return mixed as the JSON converted content.
226
     */
227 8
    protected function getRequestBody()
228
    {
229 8
        $entry = $this->di->get("request")->getBody();
230 8
        $entry = json_decode($entry, true);
231
232 8
        if (is_null($entry)) {
233 4
            throw new Exception("Could not read HTTP request body as JSON.");
234
        }
235
236 4
        return $entry;
237
    }
238
239
240
241
    /**
242
     * Show a message that the route is unsupported, a local 404.
243
     *
244
     * @return void
245
     */
246 3
    public function catchAll()
247
    {
248 3
        return [["message" => "404. The api does not support that."], 404];
249
    }
250
}
251