Completed
Push — master ( 858d63...cc8c1e )
by Marcus
03:06
created

Itemgroupadmin::updateGroup()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 65
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 65
rs 8.6195
cc 6
eloc 49
nc 6
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\HardcodedText;
25
use HaaseIT\HCSF\HelperConfig;
26
use HaaseIT\Toolbox\Tools;
27
use Zend\ServiceManager\ServiceManager;
28
use Zend\Diactoros\ServerRequest;
29
30
/**
31
 * Class Itemgroupadmin
32
 * @package HaaseIT\HCSF\Controller\Admin\Shop
33
 */
34
class Itemgroupadmin extends Base
35
{
36
    /**
37
     * @var \Doctrine\DBAL\Connection
38
     */
39
    private $dbal;
40
41
    /**
42
     * @var array
43
     */
44
    protected $post;
45
46
    /**
47
     * @var ServerRequest;
48
     */
49
    protected $request;
50
51
    /**
52
     * Itemgroupadmin constructor.
53
     * @param ServiceManager $serviceManager
54
     */
55
    public function __construct(ServiceManager $serviceManager)
56
    {
57
        parent::__construct($serviceManager);
58
        $this->dbal = $serviceManager->get('dbal');
59
        $this->request = $serviceManager->get('request');
60
        $this->post = $this->request->getParsedBody();
61
    }
62
63
    /**
64
     *
65
     */
66
    public function preparePage()
0 ignored issues
show
Coding Style introduced by
preparePage uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
67
    {
68
        $this->P = new \HaaseIT\HCSF\CorePage($this->serviceManager);
69
        $this->P->cb_pagetype = 'content';
70
        $this->P->cb_subnav = 'admin';
71
72
        $this->P->cb_customcontenttemplate = 'shop/itemgroupadmin';
73
74
        $return = '';
75
        if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'insert_lang') {
76
            $querybuilder = $this->dbal->createQueryBuilder();
77
            $querybuilder
78
                ->select('itmg_id')
79
                ->from('itemgroups_base')
80
                ->where('itmg_id = ?')
81
                ->setParameter(0, $_REQUEST['gid'])
82
            ;
83
            $stmt = $querybuilder->execute();
84
85
            $iNumRowsBasis = $stmt->rowCount();
86
87
            $querybuilder = $this->dbal->createQueryBuilder();
88
            $querybuilder
89
                ->select('itmgt_id')
90
                ->from('itemgroups_text')
91
                ->where('itmgt_pid = ? AND itmgt_lang = ?')
92
                ->setParameter(0, $_REQUEST['gid'])
93
                ->setParameter(1, HelperConfig::$lang)
94
            ;
95
            $stmt = $querybuilder->execute();
96
97
            $iNumRowsLang = $stmt->rowCount();
98
99
            if ($iNumRowsBasis === 1 && $iNumRowsLang === 0) {
100
                $iGID = filter_var($_REQUEST['gid'], FILTER_SANITIZE_NUMBER_INT);
101
                $querybuilder = $this->dbal->createQueryBuilder();
102
                $querybuilder
103
                    ->insert('itemgroups_text')
104
                    ->setValue('itmgt_pid', '?')
105
                    ->setValue('itmgt_lang', '?')
106
                    ->setParameter(0, $iGID)
107
                    ->setParameter(1, HelperConfig::$lang)
108
                ;
109
                $querybuilder->execute();
110
                \HaaseIT\HCSF\Helper::redirectToPage('/_admin/itemgroupadmin.html?gid='.$iGID.'&action=editgroup');
111
            }
112
        }
113
114
        if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'editgroup') {
115
            if (isset($_REQUEST['do']) && $_REQUEST['do'] === 'true') {
116
                $this->P->cb_customdata['updatestatus'] = $this->updateGroup();
117
            }
118
119
            $iGID = filter_var($_REQUEST['gid'], FILTER_SANITIZE_NUMBER_INT);
120
            $aGroup = $this->getItemgroups($iGID);
121
            if (isset($_REQUEST['added'])) {
122
                $this->P->cb_customdata['groupjustadded'] = true;
123
            }
124
            $this->P->cb_customdata['showform'] = 'edit';
125
            $this->P->cb_customdata['group'] = $this->prepareGroup('edit', $aGroup[0]);
126
        } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] === 'addgroup') {
127
            $aErr = [];
128
            if (isset($_REQUEST['do']) && $_REQUEST['do'] === 'true') {
129
                $sName = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
130
                $sGNo = filter_var($_REQUEST['no'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
131
                $sImg = filter_var($_REQUEST['img'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
132
133
                if (strlen($sName) < 3) {
134
                    $aErr['nametooshort'] = true;
135
                }
136
                if (strlen($sGNo) < 3) {
137
                    $aErr['grouptooshort'] = true;
138
                }
139
                if (count($aErr) == 0) {
140
                    $querybuilder = $this->dbal->createQueryBuilder();
141
                    $querybuilder
142
                        ->select('itmg_no')
143
                        ->from('itemgroups_base')
144
                        ->where('itmg_no = ?')
145
                        ->setParameter(0, $sGNo)
146
                    ;
147
                    $stmt = $querybuilder->execute();
148
149
                    if ($stmt->rowCount() > 0) {
150
                        $aErr['duplicateno'] = true;
151
                    }
152
                }
153
                if (count($aErr) === 0) {
154
                    $querybuilder = $this->dbal->createQueryBuilder();
155
                    $querybuilder
156
                        ->insert('itemgroups_base')
157
                        ->setValue('itmg_name', '?')
158
                        ->setValue('itmg_no', '?')
159
                        ->setValue('itmg_img', '?')
160
                        ->setParameter(0, $sName)
161
                        ->setParameter(1, $sGNo)
162
                        ->setParameter(2, $sImg)
163
                    ;
164
                    $querybuilder->execute();
165
                    $iLastInsertID = $this->dbal->lastInsertId();
166
                    \HaaseIT\HCSF\Helper::redirectToPage('/_admin/itemgroupadmin.html?action=editgroup&added&gid='.$iLastInsertID);
167 View Code Duplication
                } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
168
                    $this->P->cb_customdata['err'] = $aErr;
169
                    $this->P->cb_customdata['showform'] = 'add';
170
                    $this->P->cb_customdata['group'] = $this->prepareGroup('add');
171
                }
172 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
173
                $this->P->cb_customdata['showform'] = 'add';
174
                $this->P->cb_customdata['group'] = $this->prepareGroup('add');
175
            }
176
        } else {
177
            if (!$return .= $this->showItemgroups($this->getItemgroups(''))) {
178
                $this->P->cb_customdata['err']['nogroupsavaliable'] = true;
179
            }
180
        }
181
        $this->P->oPayload->cl_html = $return;
182
    }
183
184
    /**
185
     * @return string
186
     */
187
    private function updateGroup()
0 ignored issues
show
Coding Style introduced by
updateGroup uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
188
    {
189
        $purifier = false;
190
        if (HelperConfig::$shop['itemgrouptext_enable_purifier']) {
191
            $purifier = \HaaseIT\HCSF\Helper::getPurifier('itemgroup');
192
        }
193
194
        $iGID = filter_var($_REQUEST['gid'], FILTER_SANITIZE_NUMBER_INT);
195
        $sGNo = filter_var($_REQUEST['no'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
196
197
        $querybuilder = $this->dbal->createQueryBuilder();
198
        $querybuilder
199
            ->select('*')
200
            ->from('itemgroups_base')
201
            ->where('itmg_id != ? AND itmg_no = ?')
202
            ->setParameter(0, $iGID)
203
            ->setParameter(1, $sGNo)
204
        ;
205
        $stmt = $querybuilder->execute();
206
207
        if ($stmt->rowCount() > 0) {
208
            return 'duplicateno';
209
        }
210
211
        $querybuilder = $this->dbal->createQueryBuilder();
212
        $querybuilder
213
            ->update('itemgroups_base')
214
            ->set('itmg_name', '?')
215
            ->set('itmg_no', '?')
216
            ->set('itmg_img', '?')
217
            ->where('itmg_id = ?')
218
            ->setParameter(0, filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
219
            ->setParameter(1, $sGNo)
220
            ->setParameter(2, filter_var($_REQUEST['img'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW))
221
            ->setParameter(3, $iGID)
222
        ;
223
        $querybuilder->execute();
224
225
        $querybuilder = $this->dbal->createQueryBuilder();
226
        $querybuilder
227
            ->select('itmgt_id')
228
            ->from('itemgroups_text')
229
            ->where('itmgt_pid = ? AND itmgt_lang = ?')
230
            ->setParameter(0, $iGID)
231
            ->setParameter(1, HelperConfig::$lang)
232
        ;
233
        $stmt = $querybuilder->execute();
234
235
        if ($stmt->rowCount() === 1) {
236
            $aRow = $stmt->fetch();
237
            $querybuilder = $this->dbal->createQueryBuilder();
238
            $querybuilder
239
                ->update('itemgroups_text')
240
                ->set('itmgt_shorttext', '?')
241
                ->set('itmgt_details', '?')
242
                ->where('itmgt_id = ?')
243
                ->setParameter(0, !empty($this->purifier) ? $purifier->purify($this->post['shorttext']) : $this->post['shorttext'])
0 ignored issues
show
Bug introduced by
The property purifier does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
244
                ->setParameter(1, !empty($this->purifier) ? $purifier->purify($this->post['details']) : $this->post['details'])
245
                ->setParameter(2, $aRow['itmgt_id'])
246
            ;
247
            $querybuilder->execute();
248
        }
249
250
        return 'success';
251
    }
252
253
    /**
254
     * @param string $sPurpose
255
     * @param array $aData
256
     * @return array
257
     */
258
    private function prepareGroup($sPurpose = 'none', $aData = [])
259
    {
260
        $aGData = [
261
            'formaction' => Tools::makeLinkHRefWithAddedGetVars('/_admin/itemgroupadmin.html'),
262
            'id' => isset($aData['itmg_id']) ? $aData['itmg_id'] : '',
263
            'name' => isset($aData['itmg_name']) ? $aData['itmg_name'] : '',
264
            'no' => isset($aData['itmg_no']) ? $aData['itmg_no'] : '',
265
            'img' => isset($aData['itmg_img']) ? $aData['itmg_img'] : '',
266
        ];
267
268
        if ($sPurpose === 'edit') {
269
            if ($aData['itmgt_id'] != '') {
270
                $aGData['lang'] = [
271
                    'shorttext' => isset($aData['itmgt_shorttext']) ? $aData['itmgt_shorttext'] : '',
272
                    'details' => isset($aData['itmgt_details']) ? $aData['itmgt_details'] : '',
273
                ];
274
            }
275
        }
276
277
        return $aGData;
278
    }
279
280
    /**
281
     * @param string $iGID
282
     * @return mixed
283
     */
284 View Code Duplication
    private function getItemgroups($iGID = '')
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...
285
    {
286
        $querybuilder = $this->dbal->createQueryBuilder();
287
        $querybuilder
288
            ->select('*')
289
            ->from('itemgroups_base', 'b')
290
            ->leftJoin('b', 'itemgroups_text', 't', 'b.itmg_id = t.itmgt_pid AND t.itmgt_lang = ?')
291
            ->setParameter(0, HelperConfig::$lang)
292
            ->orderBy('itmg_no')
293
        ;
294
295
        if ($iGID != '') {
296
            $querybuilder
297
                ->where('itmg_id = ?')
298
                ->setParameter(1, $iGID)
299
            ;
300
        }
301
        $stmt = $querybuilder->execute();
302
303
        return $stmt->fetchAll();
304
    }
305
306
    /**
307
     * @param $aGroups
308
     * @return bool|mixed
309
     */
310
    private function showItemgroups($aGroups)
311
    {
312
        $aList = [
313
            ['title' => HardcodedText::get('itemgroupadmin_list_no'), 'key' => 'gno', 'width' => 80, 'linked' => false, 'style-data' => 'padding: 5px 0;'],
314
            ['title' => HardcodedText::get('itemgroupadmin_list_name'), 'key' => 'gname', 'width' => 350, 'linked' => false, 'style-data' => 'padding: 5px 0;'],
315
            ['title' => HardcodedText::get('itemgroupadmin_list_edit'), 'key' => 'gid', 'width' => 30, 'linked' => true, 'ltarget' => '/_admin/itemgroupadmin.html', 'lkeyname' => 'gid', 'lgetvars' => ['action' => 'editgroup'], 'style-data' => 'padding: 5px 0;'],
316
        ];
317
        if (count($aGroups) > 0) {
318
            $aData = [];
319
            foreach ($aGroups as $aValue) {
320
                $aData[] = [
321
                    'gid' => $aValue['itmg_id'],
322
                    'gno' => $aValue['itmg_no'],
323
                    'gname' => $aValue['itmg_name'],
324
                ];
325
            }
326
            return Tools::makeListtable($aList, $aData, $this->serviceManager->get('twig'));
327
        }
328
329
        return false;
330
    }
331
}
332