ProductsCategories   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 249
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 34
eloc 155
c 1
b 0
f 1
dl 0
loc 249
rs 9.68

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B update() 0 46 8
B delete() 0 39 6
B create() 0 52 7
B index() 0 39 6
B read() 0 36 6
1
<?php
2
3
namespace WagnerMontanini\GoomerApi\Api;
4
5
use WagnerMontanini\GoomerApi\Support\Pager;
6
use WagnerMontanini\GoomerApi\Models\ProductCategory;
7
use WagnerMontanini\GoomerApi\Models\Restaurant;
8
9
/**
10
 * Class ProductsCategories
11
 * @package WagnerMontanini\GoomerApi
12
 */
13
class ProductsCategories extends GoomerApi
14
{
15
    /**
16
     * ProductsCategories constructor.
17
     * @throws \Exception
18
     */
19
    public function __construct()
20
    {
21
        parent::__construct();
22
    }
23
24
    /**
25
     * list all products_categories
26
     * @param array $data
27
     * @throws \Exception
28
     */
29
    public function index(array $data): void
30
    {   
31
        $values = $this->headers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->headers can also be of type boolean. However, the property $headers is declared as type array|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
32
33
        if (empty($data["restaurant_id"]) || !$restaurant_id = filter_var($data["restaurant_id"], FILTER_VALIDATE_INT) ) {
34
            $this->call(
35
                400,
36
                "invalid_data",
37
                "É preciso informar o ID do restaurante para verificar as categorias"
38
            )->back();
39
            return;
40
        }
41
42
        //get products_categories
43
        $products_categories = (new ProductCategory())->find("restaurant_id=:restaurant_id","restaurant_id={$restaurant_id}");
44
        
45
        if (!$products_categories->count()) {
46
            $this->call(
47
                404,
48
                "not_found",
49
                "Nada encontrado para sua busca."
50
            )->back(["results" => 0]);
51
            return;
52
        }
53
        
54
        $page = (!empty($values["page"]) ? $values["page"] : 1);
55
        $pager = new Pager(url("/restaurants/{restaurant_id}/categories"));
56
        $pager->pager($products_categories->count(), 10, $page);
57
58
        $response["results"] = $products_categories->count();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.
Loading history...
59
        $response["page"] = $pager->page();
60
        $response["pages"] = $pager->pages();
61
62
        foreach ($products_categories->limit($pager->limit())->offset($pager->offset())->order("name ASC")->fetch(true) as $product_category) {
63
            $response["products_categories"][] = $product_category->restaurant()->data();
64
        }
65
66
        $this->back($response);
67
        return;
68
    }
69
70
    /**
71
     * @param array $data
72
     * @throws \Exception
73
     */
74
    public function create(array $data): void
75
    {
76
        $request = $this->requestLimit("productsCategoriesCreate", 5, 60);
77
        if (!$request) {
78
            return;
79
        }
80
81
        if (empty($data["restaurant_id"]) || !$restaurant_id = filter_var($data["restaurant_id"], FILTER_VALIDATE_INT) ) {
82
            $this->call(
83
                400,
84
                "invalid_data",
85
                "É preciso informar o ID do restaurante para criar os produtos"
86
            )->back();
87
            return;
88
        }
89
        
90
        $restaurant = (new Restaurant())->findById($restaurant_id);
91
92
        if (!$restaurant) {
93
            $this->call(
94
                404,
95
                "not_found",
96
                "Você tentou cadastrar uma categoria em um restaurante que não existe"
97
            )->back();
98
            return;
99
        }
100
101
        if ( empty($data["name"]) ) {
102
            $this->call(
103
                400,
104
                "empty_data",
105
                "Para criar informe o nome da categoria"
106
            )->back();
107
            return ;
108
        }
109
110
        $product_category = new ProductCategory();
111
        $product_category->restaurant_id = $restaurant_id;
0 ignored issues
show
Bug Best Practice introduced by
The property restaurant_id does not exist on WagnerMontanini\GoomerApi\Models\ProductCategory. Since you implemented __set, consider adding a @property annotation.
Loading history...
112
        $product_category->name = filter_var($data["name"], FILTER_SANITIZE_STRIPPED);
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on WagnerMontanini\GoomerApi\Models\ProductCategory. Since you implemented __set, consider adding a @property annotation.
Loading history...
113
        $product_category->save();
114
115
        if($product_category->fail()){
116
            $this->call(
117
                400,
118
                "empty_data",
119
                $product_category->fail()->getMessage()
120
            )->back();
121
            return;
122
        }
123
124
        $this->back(["product_category" => $product_category->restaurant()->data()]);
125
        return;
126
    }
127
128
    /**
129
     * @param array $data
130
     */
131
    public function read(array $data): void
132
    {
133
        if (empty($data["restaurant_id"]) || !$restaurant_id = filter_var($data["restaurant_id"], FILTER_VALIDATE_INT) ) {
134
            $this->call(
135
                400,
136
                "invalid_data",
137
                "É preciso informar o ID do restaurante para verificar a categoria"
138
            )->back();
139
            return;
140
        }
141
142
        
143
        if (empty($data["product_category_id"]) || !$product_category_id = filter_var($data["product_category_id"], FILTER_VALIDATE_INT) ) {
144
            $this->call(
145
                400,
146
                "invalid_data",
147
                "É preciso informar o ID da categoria que deseja consultar"
148
            )->back();
149
            return;
150
        }
151
152
        $product_category = (new ProductCategory())->find("restaurant_id = :restaurant_id AND id = :id",
153
                                "restaurant_id={$restaurant_id}&id=$product_category_id")->fetch();
154
155
        if (!$product_category) {
156
            $this->call(
157
                404,
158
                "not_found",
159
                "Você tentou acessar uma categoria que não existe neste restaurante"
160
            )->back();
161
            return;
162
        }
163
164
        $response["product_category"] = $product_category->restaurant()->data();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.
Loading history...
165
        
166
        $this->back($response);
167
    }
168
169
    /**
170
     * @param array $data
171
     */
172
    public function update(array $data): void
173
    {
174
        if ( empty($data["restaurant_id"]) || !$restaurant_id = filter_var($data["restaurant_id"], FILTER_VALIDATE_INT)) {
175
            $this->call(
176
                400,
177
                "invalid_data",
178
                "É preciso informar o ID do restaurante para atualizar a categoria"
179
            )->back();
180
            return;
181
        }
182
183
        if (empty($data["product_category_id"]) || !$product_category_id = filter_var($data["product_category_id"], FILTER_VALIDATE_INT) ) {
184
            $this->call(
185
                400,
186
                "invalid_data",
187
                "É preciso informar o ID da categoria que deseja atualizar"
188
            )->back();
189
            return;
190
        }
191
192
        $product_category = (new ProductCategory())->find("restaurant_id = :restaurant_id AND id = :id",
193
                                "restaurant_id={$restaurant_id}&id=$product_category_id")->fetch();
194
195
        if (!$product_category) {
196
            $this->call(
197
                404,
198
                "not_found",
199
                "Você tentou atualizar uma categoria de um restaurante que não existe"
200
            )->back();
201
            return;
202
        }
203
        
204
        $product_category->name = (!empty($data["name"])) ? filter_var($data["name"], FILTER_SANITIZE_STRIPPED) : $product_category->name;
205
        $product_category->save();
206
207
        if($product_category->fail()){
208
            $this->call(
209
                400,
210
                "empty_data",
211
                $product_category->fail()->getMessage()
212
            )->back();
213
            return;
214
        }
215
216
        $this->back(["product_category" => $product_category->restaurant()->data()]);
217
        return;
218
    }
219
220
    /**
221
     * @param array $data
222
     */
223
    public function delete(array $data): void
224
    {
225
        if (empty($data["restaurant_id"]) || !$restaurant_id = filter_var($data["restaurant_id"], FILTER_VALIDATE_INT)) {
226
            $this->call(
227
                400,
228
                "invalid_data",
229
                "É preciso informar o ID do restaurante para deletar a categoria"
230
            )->back();
231
            return;
232
        }
233
234
        if (empty($data["product_category_id"]) || !$product_category_id = filter_var($data["product_category_id"], FILTER_VALIDATE_INT) ) {
235
            $this->call(
236
                400,
237
                "invalid_data",
238
                "É preciso informar o ID da categoria que deseja deletar"
239
            )->back();
240
            return;
241
        }
242
243
        $product_category = (new ProductCategory())->find("restaurant_id = :restaurant_id AND id = :id",
244
                                "restaurant_id={$restaurant_id}&id=$product_category_id")->fetch();
245
246
        if (!$product_category) {
247
            $this->call(
248
                404,
249
                "not_found",
250
                "Você tentou excluir uma categoria de um restaurante que não existe"
251
            )->back();
252
            return;
253
        }
254
255
        $product_category->destroy();
256
        $this->call(
257
            200,
258
            "success",
259
            "A categoria foi excluído com sucesso",
260
            "accepted"
261
        )->back();
262
    }
263
}