Completed
Push — master ( 1d1f79...85914a )
by Harald
06:13 queued 02:42
created

Shop::init()   D

Complexity

Conditions 20
Paths 144

Size

Total Lines 97
Code Lines 51

Duplication

Lines 18
Ratio 18.56 %

Importance

Changes 0
Metric Value
cc 20
eloc 51
nc 144
nop 0
dl 18
loc 97
rs 4.4507
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
  * osCommerce Online Merchant
4
  *
5
  * @copyright Copyright (c) 2015 osCommerce; http://www.oscommerce.com
6
  * @license GPL; http://www.oscommerce.com/gpllicense.txt
7
  */
8
9
namespace OSC\Sites\Shop;
10
11
use OSC\OM\Apps;
12
use OSC\OM\Cache;
13
use OSC\OM\Cookies;
14
use OSC\OM\Db;
15
use OSC\OM\Hooks;
16
use OSC\OM\HTML;
17
use OSC\OM\Language;
18
use OSC\OM\OSCOM;
19
use OSC\OM\Registry;
20
use OSC\OM\Session;
21
22
class Shop extends \OSC\OM\SitesAbstract
23
{
24
    protected function init()
25
    {
26
        global $PHP_SELF, $currencies, $messageStack, $oscTemplate, $breadcrumb;
27
28
        $OSCOM_Cookies = new Cookies();
29
        Registry::set('Cookies', $OSCOM_Cookies);
30
31
        Registry::set('Cache', new Cache());
32
33
        $OSCOM_Db = Db::initialize();
34
        Registry::set('Db', $OSCOM_Db);
35
36
        Registry::set('Hooks', new Hooks());
37
38
        Registry::set('Language', new Language());
39
40
// set the application parameters
41
        $Qcfg = $OSCOM_Db->get('configuration', [
42
            'configuration_key as k',
43
            'configuration_value as v'
44
        ]);//, null, null, null, 'configuration'); // TODO add cache when supported by admin
45
46
        while ($Qcfg->fetch()) {
47
            define($Qcfg->value('k'), $Qcfg->value('v'));
48
        }
49
50
// set php_self in the global scope
51
        $req = parse_url($_SERVER['SCRIPT_NAME']);
52
        $PHP_SELF = substr($req['path'], strlen(OSCOM::getConfig('http_path', 'Shop')));
53
54
        $OSCOM_Session = Session::load();
55
        Registry::set('Session', $OSCOM_Session);
56
57
// start the session
58
        $OSCOM_Session->start();
59
60
        $this->ignored_actions[] = session_name();
0 ignored issues
show
Bug introduced by
The property ignored_actions 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...
61
62
// create the shopping cart
63 View Code Duplication
        if (!isset($_SESSION['cart']) || !is_object($_SESSION['cart']) || (get_class($_SESSION['cart']) != 'shoppingCart')) {
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...
64
            $_SESSION['cart'] = new \shoppingCart();
65
        }
66
67
// include currencies class and create an instance
68
        $currencies = new \currencies();
69
70
// set the language
71 View Code Duplication
        if (!isset($_SESSION['language']) || isset($_GET['language'])) {
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...
72
            $lng = new \language();
73
74
            if (isset($_GET['language']) && !empty($_GET['language'])) {
75
                $lng->set_language($_GET['language']);
76
            } else {
77
                $lng->get_browser_language();
78
            }
79
80
            $_SESSION['language'] = $lng->language['directory'];
0 ignored issues
show
Bug introduced by
The property language does not seem to exist. Did you mean languages?

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...
81
            $_SESSION['languages_id'] = $lng->language['id'];
0 ignored issues
show
Bug introduced by
The property language does not seem to exist. Did you mean languages?

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...
82
        }
83
84
// include the language translations
85
        $system_locale_numeric = setlocale(LC_NUMERIC, 0);
86
        include(OSCOM::getConfig('dir_root') . 'includes/languages/' . $_SESSION['language'] . '.php');
87
        setlocale(LC_NUMERIC, $system_locale_numeric); // Prevent LC_ALL from setting LC_NUMERIC to a locale with 1,0 float/decimal values instead of 1.0 (see bug #634)
88
89
// currency
90
        if (!isset($_SESSION['currency']) || isset($_GET['currency']) || ((USE_DEFAULT_LANGUAGE_CURRENCY == 'true') && (LANGUAGE_CURRENCY != $_SESSION['currency']))) {
91
            if (isset($_GET['currency']) && $currencies->is_set($_GET['currency'])) {
0 ignored issues
show
Bug introduced by
The method is_set() does not seem to exist on object<currencies>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
92
                $_SESSION['currency'] = $_GET['currency'];
93
            } else {
94
                $_SESSION['currency'] = ((USE_DEFAULT_LANGUAGE_CURRENCY == 'true') && $currencies->is_set(LANGUAGE_CURRENCY)) ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;
0 ignored issues
show
Bug introduced by
The method is_set() does not seem to exist on object<currencies>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
95
            }
96
        }
97
98
// navigation history
99 View Code Duplication
        if (!isset($_SESSION['navigation']) || !is_object($_SESSION['navigation']) || (get_class($_SESSION['navigation']) != 'navigationHistory')) {
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...
100
            $_SESSION['navigation'] = new \navigationHistory();
101
        }
102
103
        $_SESSION['navigation']->add_current_page();
104
105
        $messageStack = new \messageStack();
106
107
        tep_update_whos_online();
108
109
        tep_activate_banners();
110
        tep_expire_banners();
111
112
        tep_expire_specials();
113
114
        $oscTemplate = new \oscTemplate();
115
116
        $breadcrumb = new \breadcrumb();
117
118
        $breadcrumb->add(HEADER_TITLE_TOP, OSCOM::getConfig('http_server', 'Shop'));
119
        $breadcrumb->add(HEADER_TITLE_CATALOG, OSCOM::link('index.php'));
120
    }
121
122
    public function setPage()
123
    {
124
        if (!empty($_GET)) {
125
            if (($route = Apps::getRouteDestination()) !== null) {
126
                $this->route = $route;
127
128
                list($vendor_app, $page) = explode('/', $route['destination'], 2);
129
130
// get controller class name from namespace
131
                $page_namespace = explode('\\', $page);
132
                $page_code = $page_namespace[count($page_namespace)-1];
133
134
                if (class_exists('OSC\Apps\\' . $vendor_app . '\\' . $page . '\\' . $page_code)) {
135
                    $class = 'OSC\Apps\\' . $vendor_app . '\\' . $page . '\\' . $page_code;
136
                }
137
            } else {
138
                $req = basename(array_keys($_GET)[0]);
139
140 View Code Duplication
                if (class_exists('OSC\Sites\\' . $this->code . '\Pages\\' . $req . '\\' . $req)) {
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...
141
                    $page_code = $req;
142
143
                    $class = 'OSC\Sites\\' . $this->code . '\Pages\\' . $page_code . '\\' . $page_code;
144
                }
145
            }
146
        }
147
148 View Code Duplication
        if (isset($class)) {
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...
149
            if (is_subclass_of($class, 'OSC\OM\PagesInterface')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
150
                $this->page = new $class($this);
151
152
                $this->page->runActions();
153
            } else {
154
                trigger_error('OSC\Sites\Shop\Shop::setPage() - ' . $page_code . ': Page does not implement OSC\OM\PagesInterface and cannot be loaded.');
0 ignored issues
show
Bug introduced by
The variable $page_code 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...
155
            }
156
        }
157
    }
158
159
    public static function resolveRoute(array $route, array $routes)
160
    {
161
        $result = [];
162
163
        foreach ($routes as $vendor_app => $paths) {
164
            foreach ($paths as $path => $page) {
165
                $path_array = explode('&', $path);
166
167
                if (count($path_array) <= count($route)) {
168
                    if ($path_array == array_slice($route, 0, count($path_array))) {
169
                        $result[] = [
170
                            'path' => $path,
171
                            'destination' => $vendor_app . '/' . $page,
172
                            'score' => count($path_array)
173
                        ];
174
                    }
175
                }
176
            }
177
        }
178
179
        if (!empty($result)) {
180
            usort($result, function ($a, $b) {
181
                if ($a['score'] == $b['score']) {
182
                    return 0;
183
                }
184
185
                return ($a['score'] < $b['score']) ? 1 : -1; // sort highest to lowest
186
            });
187
188
            return $result[0];
189
        }
190
    }
191
}
192