Completed
Branch master (dd17f1)
by Marcus
112:41 queued 100:32
created

Pageadmin::handleEditPage()   B

Complexity

Conditions 8
Paths 19

Size

Total Lines 59
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 59
rs 7.132
cc 8
eloc 42
nc 19
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;
22
23
use HaaseIT\HCSF\HelperConfig;
24
use HaaseIT\HCSF\UserPage;
25
use HaaseIT\HCSF\HardcodedText;
26
use Zend\ServiceManager\ServiceManager;
27
28
/**
29
 * Class Pageadmin
30
 * @package HaaseIT\HCSF\Controller\Admin
31
 */
32
class Pageadmin extends Base
33
{
34
    /**
35
     * Pageadmin constructor.
36
     * @param ServiceManager $serviceManager
37
     */
38
    public function __construct(ServiceManager $serviceManager)
39
    {
40
        parent::__construct($serviceManager);
41
    }
42
43
    /**
44
     *
45
     */
46
    public function preparePage()
47
    {
48
        $this->P = new \HaaseIT\HCSF\CorePage($this->serviceManager);
49
        $this->P->cb_pagetype = 'content';
50
        $this->P->cb_subnav = 'admin';
51
52
        $this->P->cb_customcontenttemplate = 'pageadmin';
53
54
        // adding language to page here
55
        if (filter_input(INPUT_GET, 'action') === 'insert_lang') {
56
            $this->insertLang();
57
        }
58
59
        $getaction = filter_input(INPUT_GET, 'action');
60
        if ($getaction === null) {
61
            $this->P->cb_customdata['pageselect'] = $this->showPageselect();
62
        } elseif (!empty(filter_input(INPUT_GET, 'page_key')) && ($getaction === 'edit' || $getaction === 'delete')) {
63
            if ($getaction === 'delete' && filter_input(INPUT_POST, 'delete') === 'do') {
64
                $this->handleDeletePage();
65
            } else { // edit or update page
66
                $this->handleEditPage();
67
            }
68
        } elseif ($getaction === 'addpage') {
69
            $this->handleAddPage();
70
        }
71
    }
72
73
    protected function handleDeletePage()
74
    {
75
        // delete and put message in customdata
76
        $Ptodelete = new UserPage($this->serviceManager, filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH), true);
77
        if ($Ptodelete->cb_id != NULL) {
78
            $Ptodelete->remove();
79
        } else {
80
            \HaaseIT\HCSF\Helper::terminateScript(HardcodedText::get('pageadmin_exception_pagetodeletenotfound'));
81
        }
82
        $this->P->cb_customdata['deleted'] = true;
83
    }
84
85
    protected function handleAddPage()
86
    {
87
        $aErr = [];
88
        if (filter_input(INPUT_POST, 'addpage') === 'do') {
89
            $sPagekeytoadd = trim(filter_input(INPUT_POST, 'pagekey', FILTER_SANITIZE_SPECIAL_CHARS));
90
91
            if (mb_substr($sPagekeytoadd, 0, 2) === '/_') {
92
                $aErr['reservedpath'] = true;
93
            } elseif (strlen($sPagekeytoadd) < 4) {
94
                $aErr['keytooshort'] = true;
95
            } else {
96
                $Ptoadd = new UserPage($this->serviceManager, $sPagekeytoadd, true);
97
                if ($Ptoadd->cb_id == NULL) {
98
                    if ($Ptoadd->insert($sPagekeytoadd)) {
99
                        \HaaseIT\HCSF\Helper::redirectToPage('/_admin/pageadmin.html?page_key='.$sPagekeytoadd.'&action=edit');
100
                    } else {
101
                        \HaaseIT\HCSF\Helper::terminateScript(HardcodedText::get('pageadmin_exception_couldnotinsertpage'));
102
                    }
103
                } else {
104
                    $aErr['keyalreadyinuse'] = true;
105
                }
106
            }
107
            $this->P->cb_customdata['err'] = $aErr;
108
            unset($aErr);
109
        }
110
        $this->P->cb_customdata['showaddform'] = true;
111
    }
112
113
    /**
114
     * @return array
115
     */
116
    protected function showPageselect() {
117
        $aGroups = [];
118
        foreach (HelperConfig::$core['admin_page_groups'] as $sValue) {
119
            $TMP = explode('|', $sValue);
120
            $aGroups[$TMP[0]] = $TMP[1];
121
        }
122
123
        $dbal = $this->serviceManager->get('dbal');
124
125
        /** @var \Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
126
        $queryBuilder = $dbal->createQueryBuilder();
127
        $queryBuilder
128
            ->select('*')
129
            ->from('content_base')
130
            ->orderBy('cb_key')
131
        ;
132
        $statement = $queryBuilder->execute();
133
134
        while ($aResult = $statement->fetch()) {
135
            if (isset($aGroups[$aResult['cb_group']])) {
136
                $aTree[$aResult['cb_group']][] = $aResult;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aTree was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aTree = 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...
137
            } else {
138
                $aTree['_'][] = $aResult;
0 ignored issues
show
Bug introduced by
The variable $aTree does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
139
            }
140
        }
141
142
        foreach ($aGroups as $sKey => $sValue) {
143
            if (isset($aTree[$sKey])) {
144
                $aOptions_g[] = $sKey.'|'.$sValue;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aOptions_g was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aOptions_g = 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...
145
            }
146
        }
147
148
        return [
149
            'options_groups' => isset($aOptions_g) ? $aOptions_g : [],
150
            'tree' => isset($aTree) ? $aTree : [],
151
        ];
152
    }
153
154
    protected function insertLang()
155
    {
156
        $Ptoinsertlang = new UserPage(
157
            $this->serviceManager,
158
            filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH),
159
            true)
160
        ;
161
162
        if ($Ptoinsertlang->cb_id != NULL && $Ptoinsertlang->oPayload->cl_id == NULL) {
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
163
            $Ptoinsertlang->oPayload->insert($Ptoinsertlang->cb_id);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class HaaseIT\HCSF\PagePayload as the method insert() does only exist in the following sub-classes of HaaseIT\HCSF\PagePayload: HaaseIT\HCSF\UserPagePayload. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
164
            \HaaseIT\HCSF\Helper::redirectToPage('/_admin/pageadmin.html?page_key='.$Ptoinsertlang->cb_key.'&action=edit');
165
        } else {
166
            \HaaseIT\HCSF\Helper::terminateScript(HardcodedText::get('pageadmin_exception_couldnotinsertlang'));
167
        }
168
    }
169
170
    protected function handleEditPage()
171
    {
172
        $requestpagekey = filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
173
        if ($requestpagekey !== null && $Ptoedit = new UserPage($this->serviceManager, $requestpagekey, true)) {
174
            if (filter_input(INPUT_POST, 'action_a') === 'true') {
175
                $Ptoedit = $this->updatePage($Ptoedit);
176
            }
177
            $this->P->cb_customdata['page'] = $Ptoedit;
178
            $this->P->cb_customdata['admin_page_types'] = HelperConfig::$core['admin_page_types'];
179
            $this->P->cb_customdata['admin_page_groups'] = HelperConfig::$core['admin_page_groups'];
180
            $aOptions = [''];
181
            foreach (HelperConfig::$navigation as $sKey => $aValue) {
182
                if ($sKey === 'admin') {
183
                    continue;
184
                }
185
                $aOptions[] = $sKey;
186
            }
187
            $this->P->cb_customdata['subnavarea_options'] = $aOptions;
188
            unset($aOptions);
189
190
            // show archived versions of this page
191
            if ($Ptoedit->oPayload->cl_id != NULL) {
192
193
                $dbal = $this->serviceManager->get('dbal');
194
195
                /** @var \Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
196
                $queryBuilder = $dbal->createQueryBuilder();
197
                $queryBuilder
198
                    ->select('*')
199
                    ->from('content_lang_archive')
200
                    ->where('cl_id = ?')
201
                    ->andWhere('cl_lang = ?')
202
                    ->setParameter(0, $Ptoedit->oPayload->cl_id)
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
203
                    ->setParameter(1, HelperConfig::$lang)
204
                    ->orderBy('cla_timestamp', 'DESC')
205
                ;
206
                $statement = $queryBuilder->execute();
207
                $iArchivedRows = $statement->rowCount();
208
209
                if ($iArchivedRows > 0) {
210
                    $aListSetting = [
211
                        ['title' => 'cla_timestamp', 'key' => 'cla_timestamp', 'width' => '15%', 'linked' => false,],
212
                        ['title' => 'cl_html', 'key' => 'cl_html', 'width' => '40%', 'linked' => false, 'escapehtmlspecialchars' => true,],
213
                        ['title' => 'cl_keywords', 'key' => 'cl_keywords', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
214
                        ['title' => 'cl_description', 'key' => 'cl_description', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
215
                        ['title' => 'cl_title', 'key' => 'cl_title', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
216
                    ];
217
                    $aData = $statement->fetchAll();
218
                    $this->P->cb_customdata['archived_list'] = \HaaseIT\Toolbox\Tools::makeListtable(
219
                        $aListSetting,
220
                        $aData,
221
                        $this->serviceManager->get('twig')
222
                    );
223
                }
224
            }
225
        } else {
226
            \HaaseIT\HCSF\Helper::terminateScript(HardcodedText::get('pageadmin_exception_pagenotfound'));
227
        }
228
    }
229
230
    protected function updatePage(UserPage $Ptoedit)
231
    {
232
        $purifier = false;
233
        if (HelperConfig::$core['pagetext_enable_purifier']) {
234
            $purifier = \HaaseIT\HCSF\Helper::getPurifier('page');
235
        }
236
237
        $Ptoedit->cb_pagetype = filter_input(INPUT_POST, 'page_type', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
238
        $Ptoedit->cb_group = filter_input(INPUT_POST, 'page_group', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
239
        $Ptoedit->cb_pageconfig = filter_input(INPUT_POST, 'page_config', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
0 ignored issues
show
Documentation Bug introduced by
It seems like filter_input(INPUT_POST,...FILTER_FLAG_STRIP_HIGH) of type * is incompatible with the declared type array of property $cb_pageconfig.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
240
        $Ptoedit->cb_subnav = filter_input(INPUT_POST, 'page_subnav', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
241
        $Ptoedit->purifier = $purifier;
0 ignored issues
show
Documentation Bug introduced by
It seems like $purifier can also be of type false. However, the property $purifier is declared as type object<HTMLPurifier>. 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...
242
        $Ptoedit->write();
243
244
        if ($Ptoedit->oPayload->cl_id != NULL) {
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
245
            $Ptoedit->oPayload->cl_html = filter_input(INPUT_POST, 'page_html');
246
            $Ptoedit->oPayload->cl_title = filter_input(INPUT_POST, 'page_title', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
247
            $Ptoedit->oPayload->cl_description = filter_input(INPUT_POST, 'page_description', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
248
            $Ptoedit->oPayload->cl_keywords = filter_input(INPUT_POST, 'page_keywords', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
249
            $Ptoedit->oPayload->purifier = $purifier;
0 ignored issues
show
Bug introduced by
The property purifier does not seem to exist in HaaseIT\HCSF\PagePayload.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
250
            $Ptoedit->oPayload->write();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class HaaseIT\HCSF\PagePayload as the method write() does only exist in the following sub-classes of HaaseIT\HCSF\PagePayload: HaaseIT\HCSF\UserPagePayload. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
251
        }
252
253
        $Ptoedit = new UserPage(
254
            $this->serviceManager,
255
            filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH),
256
            true
257
        );
258
        $this->P->cb_customdata['updated'] = true;
259
260
        return $Ptoedit;
261
    }
262
}
263