Completed
Push — master ( db6695...470eb5 )
by Marcus
02:45
created

Router   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 198
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 35
lcom 1
cbo 6
dl 0
loc 198
rs 9
c 4
b 0
f 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F getPage() 0 140 28
B getRoutingoverride() 0 33 6
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: mhaase
5
 * Date: 14.01.16
6
 * Time: 23:04
7
 */
8
9
namespace HaaseIT\HCSF;
10
11
12
use Zend\ServiceManager\ServiceManager;
13
14
class Router
15
{
16
    private $P;
17
18
    /**
19
     * @var string
20
     */
21
    private $sPath;
22
23
    /**
24
     * @var ServiceManager
25
     */
26
    private $serviceManager;
27
28
    /**
29
     * Router constructor.
30
     * @param ServiceManager $serviceManager
31
     */
32
    public function __construct(ServiceManager $serviceManager)
33
    {
34
        $this->serviceManager = $serviceManager;
35
    }
36
37
    public function getPage()
0 ignored issues
show
Coding Style introduced by
getPage uses the super-global variable $_SERVER 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...
38
    {
39
        if (HelperConfig::$core['maintenancemode']) {
40
            try {
41
                $controller = new \HaaseIT\HCSF\Controller\Maintenance($this->serviceManager);
42
                $this->P = $controller->getPage();
43
            } catch (\Exception $e) {
44
                $this->P = $e->getMessage();
45
            }
46
        } else {
47
            $map = [
48
                '/_admin/index.html' => 'Admin\\Index',
49
                '/_admin/' => 'Admin\\Index',
50
                '/_admin' => 'Admin\\Index',
51
                '/_admin/cleartemplatecache.html' => 'Admin\\ClearTemplateCache',
52
                '/_admin/clearimagecache.html' => 'Admin\\ClearImageCache',
53
                '/_admin/phpinfo.html' => 'Admin\\Phpinfo',
54
                '/_admin/pageadmin.html' => 'Admin\\Pageadmin',
55
                '/_admin/textcatadmin.html' => 'Admin\\Textcatadmin',
56
                '/_admin/customeradmin.html' => 'Admin\\Customer\\Customeradmin',
57
                '/_admin/itemadmin.html' => 'Admin\\Shop\\Itemadmin',
58
                '/_admin/shopadmin.html' => 'Admin\\Shop\\Shopadmin',
59
                '/_admin/shopadmin_export.csv' => 'Admin\\Shop\\ShopadminExportCSV',
60
                '/_admin/itemgroupadmin.html' => 'Admin\\Shop\\Itemgroupadmin',
61
                '/_admin/dbstatus.html' => 'Admin\\DBStatus',
62
                '/_misc/login.html' => 'Customer\\Login',
63
                '/_misc/logout.html' => 'Customer\\Logout',
64
                '/_misc/userhome.html' => 'Customer\\Userhome',
65
                '/_misc/register.html' => 'Customer\\Register',
66
                '/_misc/forgotpassword.html' => 'Customer\\Forgotpassword',
67
                '/_misc/rp.html' => 'Customer\\Resetpassword',
68
                '/_misc/verifyemail.html' => 'Customer\\Verifyemail',
69
                '/_misc/resendverificationmail.html' => 'Customer\\Resendverificationmail',
70
                '/_misc/myorders.html' => 'Shop\\Myorders',
71
                '/_misc/itemsearch.html' => 'Shop\\Itemsearch',
72
                '/_misc/checkedout.html' => 'Shop\\Checkedout',
73
                '/_misc/updateshippingcost.html' => 'Shop\\Updateshippingcost',
74
                '/_misc/shoppingcart.html' => 'Shop\\Shoppingcart',
75
                '/_misc/update-cart.html' => 'Shop\\Updatecart',
76
                '/_misc/sofortueberweisung.html' => 'Shop\\Sofortueberweisung',
77
                '/_misc/paypal.html' => 'Shop\\Paypal',
78
                '/_misc/paypal_notify.html' => 'Shop\\Paypalnotify',
79
            ];
80
            if (HelperConfig::$core['enable_sandbox']) {
81
                $map['/_misc/sandbox.html'] = 'Sandbox'; // dev sandbox for testing new functionality
82
            }
83
            $this->P = 404;
84
            $aURL = parse_url($this->serviceManager->get('request')->getRequestTarget());
85
            $this->sPath = $aURL["path"];
86
87
            $aPath = explode('/', $this->sPath);
88
            if (!empty($map[$this->sPath])) {
89
                $class = '\\HaaseIT\\HCSF\\Controller\\' . $map[$this->sPath];
90
            } else {
91
                if ($aPath[1] == HelperConfig::$core['directory_images']) {
92
                    $class = '\\HaaseIT\\HCSF\\Controller\\Glide';
93
                }
94
            }
95
96
            if (!empty($class)) {
97
                try {
98
                    $controller = new $class($this->serviceManager, $aPath);
99
                    $this->P = $controller->getPage();
100
                } catch (\Exception $e) {
101
                    $this->P = 500;
102
                    // todo: write error message
103
                    //echo $e->getMessage();
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
104
105
                }
106
            } else {
107
                if (HelperConfig::$core["enable_module_shop"]) {
108
                    $aRoutingoverride = $this->getRoutingoverride($aPath);
109
                }
110
111
                $this->P = new UserPage($this->serviceManager, $this->sPath);
112
113
                // go and look if the page can be loaded yet
114
                if ($this->P->cb_id == NULL) {
115
                    /*
116
                    If the last part of the path doesn't include a dot (.) and is not empty, apend a slash.
117
                    If there is already a slash at the end, the last part of the path array will be empty.
118
                     */
119
                    if (mb_strpos($aPath[count($aPath) - 1], '.') === false && $aPath[count($aPath) - 1] != '') {
120
                        $this->sPath .= '/';
121
                    }
122
123
                    if ($this->sPath[strlen($this->sPath) - 1] === '/') {
124
                        $this->sPath .= 'index.html';
125
                    }
126
127
                    $this->P = new UserPage($this->serviceManager, $this->sPath);
128
                }
129
130
                if ($this->P->cb_id == NULL) { // if the page is still not found, unset the page object
131
                    $this->P = 404;
132
                } else { // if it is found, go on
133
                    // Support for shorturls
134
                    if ($this->P->cb_pagetype === 'shorturl') {
135
                        header('Location: ' . $this->P->cb_pageconfig, true, 302);
136
                        exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method getPage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
137
                    }
138
139
                    if (isset($this->P, $aRoutingoverride) && count($aRoutingoverride)) {
140
                        $this->P->cb_pagetype = $aRoutingoverride["cb_pagetype"];
141
                        $this->P->cb_pageconfig->itemno = $aRoutingoverride["itemno"];
142
                    }
143
                }
144
            }
145
146
            if (!is_object($this->P) && $this->P == 404) {
147
                $this->P = new CorePage($this->serviceManager);
148
                $this->P->cb_pagetype = 'error';
149
                $this->P->iStatus = 404;
150
151
                $this->P->oPayload->cl_html = $this->serviceManager->get('textcats')->T("misc_page_not_found");
152
                header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
153
            } elseif (!is_object($this->P) && $this->P == 500) {
154
                $this->P = new CorePage($this->serviceManager);
155
                $this->P->cb_pagetype = 'error';
156
                $this->P->iStatus = 500;
157
158
                $this->P->oPayload->cl_html = $this->serviceManager->get('textcats')->T("misc_server_error");
159
                header($_SERVER["SERVER_PROTOCOL"] . " 500 Internal Server Error");
160
            } elseif (is_object($this->P) && $this->P->oPayload == NULL) {// elseif the page has been found but contains no payload...
161
                if (
162
                    !(
163
                        $this->P->cb_pagetype === 'itemoverview'
164
                        || $this->P->cb_pagetype === 'itemoverviewgrpd'
165
                        || $this->P->cb_pagetype === 'itemdetail'
166
                    )
167
                ) { // no payload is fine if page is one of these
168
                    $this->P->oPayload->cl_html = $this->serviceManager->get('textcats')->T("misc_content_not_found");
169
                    header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
170
                }
171
            } elseif ($this->P->oPayload->cl_lang != NULL && $this->P->oPayload->cl_lang != HelperConfig::$lang) { // if the page is available but not in the current language, display info
172
                $this->P->oPayload->cl_html = $this->serviceManager->get('textcats')->T("misc_page_not_available_lang") . '<br><br>' . $this->P->oPayload->cl_html;
173
            }
174
        }
175
        return $this->P;
176
    }
177
178
    private function getRoutingoverride($aPath)
179
    {
180
        $aRoutingoverride = [];
181
        // /xxxx/item/0010.html
182
        $aTMP["parts_in_path"] = count($aPath);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aTMP was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aTMP = 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...
183
        // if the last dir in path is 'item' and the last part of the path is not empty
184
        if ($aPath[$aTMP["parts_in_path"] - 2] === 'item' && $aPath[$aTMP["parts_in_path"] - 1] != '') {
185
186
            // explode the filename by .
187
            $aTMP["exploded_request_file"] = explode('.', $aPath[$aTMP["parts_in_path"] - 1]);
188
189
            // if the filename ends in '.html', get the requested itemno
190
            if ($aTMP["exploded_request_file"][count($aTMP["exploded_request_file"]) - 1] === 'html') {
191
                // to allow dots in the filename, we have to iterate through all parts of the filename
192
                $aRoutingoverride["itemno"] = '';
193
                for ($i = 0; $i < count($aTMP["exploded_request_file"]) - 1; $i++) {
194
                    $aRoutingoverride["itemno"] .= $aTMP["exploded_request_file"][$i] . '.';
195
                }
196
                // remove the trailing dot
197
                $aRoutingoverride["itemno"] = \HaaseIT\Toolbox\Tools::cutStringend($aRoutingoverride["itemno"], 1);
198
199
                $aRoutingoverride["cb_pagetype"] = 'itemdetail';
200
201
                // rebuild the path string without the trailing '/item/itemno.html'
202
                $this->sPath = '';
203
                for ($i = 0; $i < $aTMP["parts_in_path"] - 2; $i++) {
204
                    $this->sPath .= $aPath[$i] . '/';
205
                }
206
            }
207
        }
208
209
        return $aRoutingoverride;
210
    }
211
}
212