Itemadmin::prepareItem()   B
last analyzed

Complexity

Conditions 6
Paths 16

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 8.4905
c 0
b 0
f 0
cc 6
nc 16
nop 1
1
<?php
2
3
/*
4
    HCSF - A multilingual CMS and Shopsystem
5
    Copyright (C) 2014  Marcus Haase - [email protected]
6
7
    This program is free software: you can redistribute it and/or modify
8
    it under the terms of the GNU General Public License as published by
9
    the Free Software Foundation, either version 3 of the License, or
10
    (at your option) any later version.
11
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
    GNU General Public License for more details.
16
17
    You should have received a copy of the GNU General Public License
18
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
namespace HaaseIT\HCSF\Controller\Admin\Shop;
22
23
24
use HaaseIT\HCSF\HelperConfig;
25
use HaaseIT\Toolbox\Tools;
26
use Zend\ServiceManager\ServiceManager;
27
28
/**
29
 * Class Itemadmin
30
 * @package HaaseIT\HCSF\Controller\Admin\Shop
31
 */
32
class Itemadmin extends Base
33
{
34
    /**
35
     * @var \Doctrine\DBAL\Connection
36
     */
37
    protected $dbal;
38
39
    /**
40
     * @var \HaaseIT\HCSF\HardcodedText
41
     */
42
    private $hardcodedtextcats;
43
44
    /**
45
     * Itemadmin constructor.
46
     * @param ServiceManager $serviceManager
47
     */
48
    public function __construct(ServiceManager $serviceManager)
49
    {
50
        parent::__construct($serviceManager);
51
        $this->dbal = $serviceManager->get('dbal');
52
        $this->hardcodedtextcats = $serviceManager->get('hardcodedtextcats');
53
    }
54
55
    /**
56
     *
57
     */
58
    public function preparePage()
59
    {
60
        $this->P = new \HaaseIT\HCSF\CorePage($this->serviceManager, [], 'admin/base.twig');
61
        $this->P->cb_pagetype = 'content';
62
        $this->P->cb_subnav = 'admin';
63
64
        $this->P->cb_customcontenttemplate = 'shop/itemadmin';
65
66
        $getaction = filter_input(INPUT_GET, 'action');
67
        if ($getaction === 'insert_lang') {
68
            $aItemdata = $this->getItem();
69
70
            if (isset($aItemdata['base']) && !isset($aItemdata['text'])) {
71
                $querybuilder = $this->dbal->createQueryBuilder();
72
                $querybuilder
73
                    ->insert('item_lang')
74
                    ->setValue('itml_pid', '?')
75
                    ->setValue('itml_lang', '?')
76
                    ->setParameter(0, $aItemdata['base']['itm_id'])
77
                    ->setParameter(1, $this->config->getLang())
78
                ;
79
                $querybuilder->execute();
80
81
                $this->helper->redirectToPage('/_admin/itemadmin.html?itemno='.filter_input(INPUT_GET, 'itemno').'&action=showitem');
82
            }
83
        }
84
        $this->P->cb_customdata['searchform'] = $this->prepareItemlistsearchform();
85
86
        if ($getaction !== null) {
87
            if ($getaction === 'search') {
88
                $this->P->cb_customdata['searchresult'] = true;
89
                if ($aItemlist = $this->getItemlist()) {
90
                    if (count($aItemlist['data']) == 1) {
91
                        $aItemdata = $this->getItem($aItemlist['data'][0]['itm_no']);
92
                        $this->P->cb_customdata['item'] = $this->prepareItem($aItemdata);
93
                    } else {
94
                        $this->P->cb_customdata['itemlist'] = $this->prepareItemlist($aItemlist);
95
                    }
96
                }
97
            } elseif (filter_input(INPUT_POST, 'doaction') === 'edititem') {
98
                $this->updateItem();
99
                $this->P->cb_customdata['itemupdated'] = true;
100
101
                $aItemdata = $this->getItem();
102
                $this->P->cb_customdata['item'] = $this->prepareItem($aItemdata);
103
            } elseif ($getaction === 'showitem') {
104
                $aItemdata = $this->getItem();
105
                $this->P->cb_customdata['item'] = $this->prepareItem($aItemdata);
106
            } elseif ($getaction === 'additem') {
107
                $aErr = [];
108
                if (filter_input(INPUT_POST, 'additem') === 'do') {
109
                    $postitemno = trim(filter_input(INPUT_POST, 'itemno', FILTER_SANITIZE_SPECIAL_CHARS));
110
                    if (strlen($postitemno) < 4) {
111
                        $aErr['itemnotooshort'] = true;
112
                    } else {
113
                        $querybuilder = $this->dbal->createQueryBuilder();
114
                        $querybuilder
115
                            ->select('itm_no')
116
                            ->from('item_base')
117
                            ->where('itm_no = ?')
118
                            ->setParameter(0, $postitemno)
119
                        ;
120
                        $stmt = $querybuilder->execute();
121
122
                        if ($stmt->rowCount() > 0) {
123
                            $aErr['itemnoalreadytaken'] = true;
124
                        } else {
125
                            $querybuilder = $this->dbal->createQueryBuilder();
126
                            $querybuilder
127
                                ->insert('item_base')
128
                                ->setValue('itm_no', '?')
129
                                ->setParameter(0, $postitemno)
130
                            ;
131
132
                            $querybuilder->execute();
133
                            $iInsertID = $this->dbal->lastInsertId();
134
135
                            $queryBuilder = $this->dbal->createQueryBuilder();
136
                            $queryBuilder
137
                                ->select('itm_no')
138
                                ->from('item_base')
139
                                ->where('itm_id = '.$queryBuilder->createNamedParameter($iInsertID))
140
                            ;
141
                            $statement = $queryBuilder->execute();
142
                            $row = $statement->fetch();
143
144
                            $this->helper->redirectToPage('/_admin/itemadmin.html?itemno='.$row['itm_no'].'&action=showitem');
145
                        }
146
                    }
147
                }
148
                $this->P->cb_customdata['showaddform'] = true;
149
                $this->P->cb_customdata['err'] = $aErr;
150
            }
151
        }
152
    }
153
154
    /**
155
     * @return mixed
156
     */
157
    private function prepareItemlistsearchform()
158
    {
159
        $aData = [
160
            'searchcats' => [
161
                'nummer|'.$this->hardcodedtextcats->get('itemadmin_search_itemno'),
162
                'name|'.$this->hardcodedtextcats->get('itemadmin_search_itemname'),
163
                'index|'.$this->hardcodedtextcats->get('itemadmin_search_itemindex'),
164
            ],
165
            'orderbys' => [
166
                'nummer|'.$this->hardcodedtextcats->get('itemadmin_search_itemno'),
167
                'name|'.$this->hardcodedtextcats->get('itemadmin_search_itemname'),
168
            ],
169
        ];
170
171
        $getsearchcat = filter_input(INPUT_GET, 'searchcat');
172
        if (isset($getsearchcat)) {
173
            $aData['searchcat'] = $getsearchcat;
174
            $_SESSION['itemadmin_searchcat'] = $getsearchcat;
175
        } elseif (isset($_SESSION['itemadmin_searchcat'])) {
176
            $aData['searchcat'] = $_SESSION['itemadmin_searchcat'];
177
        }
178
179
        $getorderby = filter_input(INPUT_GET, 'orderby');
180
        if (isset($getorderby)) {
181
            $aData['orderby'] = $getorderby;
182
            $_SESSION['itemadmin_orderby'] = $getorderby;
183
        } elseif (isset($_SESSION['itemadmin_orderby'])) {
184
            $aData['orderby'] = $_SESSION['itemadmin_orderby'];
185
        }
186
187
        return $aData;
188
    }
189
190
    /**
191
     * @return bool
192
     */
193
    private function getItemlist()
194
    {
195
        $sSearchstring = filter_input(INPUT_GET, 'searchstring', FILTER_SANITIZE_SPECIAL_CHARS);
196
        $sSearchstring = str_replace('*', '%', $sSearchstring);
197
198
        $querybuilder = $this->dbal->createQueryBuilder();
199
        $querybuilder
200
            ->select('itm_no, itm_name, itm_index')
201
            ->from('item_base', 'b')
202
            ->leftJoin('b', 'item_lang', 'l', 'b.itm_id = l.itml_pid AND l.itml_lang = :lang')
203
        ;
204
205
        $getsearchcat = filter_input(INPUT_GET, 'searchcat');
206
        if ($getsearchcat === 'name') {
207
            $querybuilder->where('itm_name LIKE :searchstring');
208
        } elseif ($getsearchcat === 'nummer') {
209
            $querybuilder->where('itm_no LIKE :searchstring');
210
        } elseif ($getsearchcat === 'index') {
211
            $querybuilder->where('itm_index LIKE :searchstring');
212
        } else {
213
            $this->helper->terminateScript();
214
        }
215
216
        $getorderby = filter_input(INPUT_GET, 'orderby');
217
        if ($getorderby === 'name') {
218
            $querybuilder->orderBy('itm_name');
219
        } elseif ($getorderby === 'nummer') {
220
            $querybuilder->orderBy('itm_no');
221
        }
222
223
        $querybuilder
224
            ->setParameter(':searchstring', $sSearchstring)
225
            ->setParameter(':lang', $this->config->getLang())
226
        ;
227
228
        $stmt = $querybuilder->execute();
229
230
        $aItemlist = ['numrows' => $stmt->rowCount()];
231
232
        if ($aItemlist['numrows'] !== 0) {
233
            while ($aRow = $stmt->fetch()) {
234
                $aItemlist['data'][] = $aRow;
235
            }
236
            return $aItemlist;
237
        }
238
239
        return false;
240
    }
241
242
    /**
243
     * @param $aItemlist
244
     * @return array
245
     */
246
    private function prepareItemlist($aItemlist)
247
    {
248
        $aList = [
249
            ['title' => $this->hardcodedtextcats->get('itemadmin_list_active'), 'key' => 'itemindex', 'width' => 30, 'linked' => false, 'callback' => 'renderItemStatusIcon',],
250
            ['title' => $this->hardcodedtextcats->get('itemadmin_list_itemno'), 'key' => 'itemno', 'width' => 100, 'linked' => false,],
251
            ['title' => $this->hardcodedtextcats->get('itemadmin_list_name'), 'key' => 'name', 'width' => 350, 'linked' => false,],
252
            ['title' => $this->hardcodedtextcats->get('itemadmin_list_edit'), 'key' => 'itemno', 'width' => 30, 'linked' => true, 'ltarget' => '/_admin/itemadmin.html', 'lkeyname' => 'itemno', 'lgetvars' => ['action' => 'showitem'],],
253
        ];
254
        $aData = [];
255
        foreach ($aItemlist['data'] as $aValue) {
256
            $aData[] = [
257
                'itemindex' => $aValue['itm_index'],
258
                'itemno' => $aValue['itm_no'],
259
                'name' => $aValue['itm_name'],
260
            ];
261
        }
262
263
        return [
264
            'numrows' => $aItemlist['numrows'],
265
            'listtable' => Tools::makeListtable($aList, $aData, $this->serviceManager->get('twig')),
266
        ];
267
    }
268
269
    /**
270
     * @param string $sItemno
271
     * @return bool|array
272
     */
273
    private function getItem($sItemno = '')
274
    {
275
        if ($sItemno === '') {
276
            $sItemno = filter_input(INPUT_GET, 'itemno', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
277
            if (empty($sItemno)) {
278
                return false;
279
            }
280
        }
281
282
        $querybuilder = $this->dbal->createQueryBuilder();
283
        $querybuilder
284
            ->select('*')
285
            ->from('item_base')
286
            ->where('itm_no = ?')
287
            ->setParameter(0, $sItemno)
288
        ;
289
        $stmt = $querybuilder->execute();
290
291
        $aItemdata = ['base' => $stmt->fetch()];
292
293
        $querybuilder = $this->dbal->createQueryBuilder();
294
        $querybuilder
295
            ->select('*')
296
            ->from('item_lang')
297
            ->where('itml_pid = ? AND itml_lang = ?')
298
            ->setParameter(0, $aItemdata['base']['itm_id'])
299
            ->setParameter(1, $this->config->getLang())
300
        ;
301
        $stmt = $querybuilder->execute();
302
303
        if ($stmt->rowCount() != 0) {
304
            $aItemdata['text'] = $stmt->fetch();
305
        }
306
307
        return $aItemdata;
308
    }
309
310
    /**
311
     * @param $aItemdata
312
     * @return array
313
     */
314
    private function prepareItem($aItemdata)
315
    {
316
        $aData = [
317
            'form' => ['action' => Tools::makeLinkHRefWithAddedGetVars('/_admin/itemadmin.html', ['action' => 'showitem', 'itemno' => $aItemdata['base']['itm_no']]),],
318
            'id' => $aItemdata['base']['itm_id'],
319
            'itemno' => $aItemdata['base']['itm_no'],
320
            'name' => $aItemdata['base']['itm_name'],
321
            'img' => $aItemdata['base']['itm_img'],
322
            'price' => $aItemdata['base']['itm_price'],
323
            'vatid' => $aItemdata['base']['itm_vatid'],
324
            'rg' => $aItemdata['base']['itm_rg'],
325
            'index' => $aItemdata['base']['itm_index'],
326
            'prio' => $aItemdata['base']['itm_order'],
327
            'group' => $aItemdata['base']['itm_group'],
328
            'data' => $aItemdata['base']['itm_data'],
329
            'weight' => $aItemdata['base']['itm_weight'],
330
        ];
331
332
        if (!$this->config->getShop('vat_disable')) {
333
            $aOptions[] = '|';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aOptions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aOptions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
334
            foreach ($this->config->getShop('vat') as $sKey => $sValue) {
335
                $aOptions[] = $sKey.'|'.$sValue;
336
            }
337
            $aData['vatoptions'] = $aOptions;
338
            unset($aOptions);
339
        }
340
        $aData['rgoptions'][] = '';
341
        foreach ($this->config->getShop('rebate_groups') as $sKey => $aValue) {
342
            $aData['rgoptions'][] = $sKey;
343
        }
344
345
        $aGroups = $this->getItemgroups('');
346
        $aData['groupoptions'][] = '';
347
        foreach ($aGroups as $aValue) {
348
            $aData['groupoptions'][] = $aValue['itmg_id'].'|'.$aValue['itmg_no'].' - '.$aValue['itmg_name'];
349
        }
350
        unset($aGroups);
351
352
        if (isset($aItemdata['text'])) {
353
            $aData['lang'] = [
354
                'textid' => $aItemdata['text']['itml_id'],
355
                'nameoverride' => $aItemdata['text']['itml_name_override'],
356
                'text1' => $aItemdata['text']['itml_text1'],
357
                'text2' => $aItemdata['text']['itml_text2'],
358
            ];
359
        }
360
361
        return $aData;
362
    }
363
364
    /**
365
     * @return bool
366
     */
367
    private function updateItem()
368
    {
369
        $purifier = false;
370
        if ($this->config->getShop('itemtext_enable_purifier')) {
371
            $purifier = $this->helper->getPurifier('item');
372
        }
373
374
        $querybuilder = $this->dbal->createQueryBuilder();
375
        $querybuilder
376
            ->update('item_base')
377
            ->set('itm_name', ':itm_name')
378
            ->set('itm_group', ':itm_group')
379
            ->set('itm_img', ':itm_img')
380
            ->set('itm_index', ':itm_index')
381
            ->set('itm_order', ':itm_order')
382
            ->set('itm_price', ':itm_price')
383
            ->set('itm_rg', ':itm_rg')
384
            ->set('itm_data', ':itm_data')
385
            ->set('itm_weight', ':itm_weight')
386
            ->set('itm_vatid', ':itm_vatid')
387
            ->where('itm_id = :itm_id')
388
            ->setParameter(':itm_name', filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
389
            ->setParameter(':itm_group', filter_input(INPUT_POST, 'group', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
390
            ->setParameter(':itm_img', filter_input(INPUT_POST, 'bild', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
391
            ->setParameter(':itm_index', filter_input(INPUT_POST, 'index', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
392
            ->setParameter(':itm_order', filter_input(INPUT_POST, 'prio', FILTER_SANITIZE_NUMBER_INT))
393
            ->setParameter(':itm_price', filter_input(INPUT_POST, 'price', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION))
394
            ->setParameter(':itm_rg', filter_input(INPUT_POST, 'rg', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
395
            ->setParameter(':itm_data', filter_input(INPUT_POST, 'data', FILTER_UNSAFE_RAW))
396
            ->setParameter(':itm_weight', filter_input(INPUT_POST, 'weight', FILTER_SANITIZE_NUMBER_INT))
397
            ->setParameter(':itm_id', filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT))
398
        ;
399
400
        if (!$this->config->getShop('vat_disable')) {
401
            $querybuilder->setParameter(':itm_vatid', filter_input(INPUT_POST, 'vatid', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW));
402
        } else {
403
            $querybuilder->setParameter(':itm_vatid', 'full');
404
        }
405
        $querybuilder->execute();
406
407
        $posttextid = filter_input(INPUT_POST, 'textid', FILTER_SANITIZE_NUMBER_INT);
408
        if ($posttextid !== null) {
409
            $posttext1 = filter_input(INPUT_POST, 'text1');
410
            $posttext2 = filter_input(INPUT_POST, 'text2');
411
412
            $querybuilder = $this->dbal->createQueryBuilder();
413
            $querybuilder
414
                ->update('item_lang')
415
                ->set('itml_text1', ':itml_text1')
416
                ->set('itml_text2', ':itml_text2')
417
                ->set('itml_name_override', ':itml_name_override')
418
                ->where('itml_id = :itml_id')
419
                ->setParameter(':itml_text1', !empty($purifier) ? $purifier->purify($posttext1) : $posttext1)
420
                ->setParameter(':itml_text2', !empty($purifier) ? $purifier->purify($posttext2) : $posttext2)
421
                ->setParameter(':itml_name_override', filter_input(INPUT_POST, 'name_override', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW))
422
                ->setParameter(':itml_id', $posttextid)
423
            ;
424
            $querybuilder->execute();
425
        }
426
427
        return true;
428
    }
429
430
    /**
431
     * @param string $iGID
432
     * @return mixed
433
     */
434 View Code Duplication
    private function getItemgroups($iGID = '') // this function should be outsourced, a duplicate is used in admin itemgroups!
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...
435
    {
436
        $querybuilder = $this->dbal->createQueryBuilder();
437
        $querybuilder
438
            ->select('*')
439
            ->from('itemgroups_base', 'b')
440
            ->leftJoin('b', 'itemgroups_text', 't', 'b.itmg_id = t.itmgt_pid AND t.itmgt_lang = ?')
441
            ->setParameter(0, $this->config->getLang())
442
            ->orderBy('itmg_no')
443
        ;
444
445
        if ($iGID != '') {
446
            $querybuilder
447
                ->where('itmg_id = :gid')
448
                ->setParameter(1, $iGID)
449
            ;
450
        }
451
        $stmt = $querybuilder->execute();
452
453
        return $stmt->fetchAll();
454
    }
455
}
456