Completed
Push — 4.0 ( 4a5124...28beb2 )
by Marco
12:39
created

RoutingTable::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 13
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 13
loc 13
rs 9.4285
cc 2
eloc 5
nc 2
nop 4
1
<?php namespace Comodojo\Dispatcher\Router;
2
3
use \Monolog\Logger;
4
use \Exception;
5
6
/**
7
 * @package     Comodojo Dispatcher
8
 * @author      Marco Giovinazzi <[email protected]>
9
 * @author      Marco Castiello <[email protected]>
10
 * @license     GPL-3.0+
11
 *
12
 * LICENSE:
13
 *
14
 * This program is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License as
16
 * published by the Free Software Foundation, either version 3 of the
17
 * License, or (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU Affero General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Affero General Public License
25
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26
 */
27
28
class RoutingTable implements RoutingTableInterface {
29
30
    private $routes = array();
31
    private $logger;
32
33
    public function __construct(Logger $logger) {
34
35
        $this->logger = $logger;
36
37
    }
38
39 View Code Duplication
    public function put($route, $type, $class, $parameters = array()) {
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...
40
41
        $folders = explode("/", $route);
42
43
        $regex = $this->readpath($folders);
44
45
        if (!isset($this->routes[$regex])) {
46
47
            $this->add($folders, $type, $class, $parameters);
48
49
        }
50
51
    }
52
53 View Code Duplication
    public function set($route, $type, $class, $parameters = array()) {
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...
54
55
        $folders = explode("/", $route);
56
57
        $regex = $this->readpath($folders);
58
59
        if (isset($this->routes[$regex])) {
60
61
            $this->add($folders, $type, $class, $parameters);
62
63
        }
64
65
    }
66
67 View Code Duplication
    public function get($route) {
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...
68
69
        $folders = explode("/", $route);
70
71
        $regex = $this->readpath($folders);
72
73
        if (isset($this->routes[$regex]))
74
            return $this->routes[$regex];
75
        else
76
            return null;
77
78
    }
79
80 View Code Duplication
    public function remove($route) {
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...
81
82
        $folders = explode("/", $route);
83
84
        $regex = $this->readpath($folders);
85
86
        if (isset($this->routes[$regex])) unset($this->routes[$regex]);
87
88
    }
89
90
    public function routes() {
91
92
        return $this->routes;
93
94
    }
95
96
    public function defaultRoute() {
97
98
        return $this->get('/');
99
100
    }
101
102
    private function readpath($folders = array(), &$value = null, $regex = '') {
103
104
        while (!empty($folders) && empty($folders[0])) {
105
106
            array_shift($folders);
107
108
        }
109
110
        if (empty($folders)) {
111
112
            return '^'.$regex.'[\/]?$';
113
114
        } else {
115
116
            $folder  = array_shift($folders);
117
118
            $decoded = json_decode($folder, true);
119
120
            if (!is_null($decoded) && is_array($decoded)) {
121
122
                $param_regex    = '';
123
124
                $param_required = false;
125
126
                foreach ($decoded as $key => $string) {
127
128
                    $this->logger->debug("PARAMETER KEY: " . $key);
129
130
                    $this->logger->debug("PARAMETER STRING: " . $string);
131
132
                    $param_regex .= $this->readparam($key, $string, $param_required);
133
134
                    $this->logger->debug("PARAMETER REGEX: " . $param_regex);
135
136
                }
137
138
                $this->readpath(
139
                    $folders,
140
                    $value,
141
                    $regex.'(?:\/'.$param_regex.')'. (($param_required)?'{1}':'?')
142
                );
143
144
            } else {
145
146
                array_push($value['service'], $folder);
147
148
                $this->readpath(
149
                    $folders,
150
                    $value,
151
                    $regex.'\/'.$folder
152
                );
153
154
            }
155
156
        }
157
158
    }
159
160
    private function readparam($key, $string, &$param_required) {
161
162
        $field_required = false;
163
164
        if (preg_match('/^(.+)\*$/', $key, $bits)) {
165
166
            $key            = $bits[1];
167
            $field_required = true;
168
            $param_required = true;
169
170
        }
171
172
        if (!is_null($value)) {
0 ignored issues
show
Bug introduced by
The variable $value does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
173
174
            $value['query'][$key] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$value was never initialized. Although not strictly required by PHP, it is generally a good practice to add $value = 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...
175
                'regex'    => $string,
176
                'required' => $required
0 ignored issues
show
Bug introduced by
The variable $required does not exist. Did you mean $param_required?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
177
            );
178
179
        }
180
181
        $string = preg_replace('/(?<!\\)\((?!\?)/', '(?:', $string);
182
        $string = preg_replace('/\.([\*\+])(?!\?)/', '.\${1}?', $string);
183
184
        return '(?P<' . $key . '>' . $string . ')' . (($field_required)?'{1}':'?');
185
186
    }
187
188
    private function add($route, $type, $class, $parameters) {
189
190
        $folders = explode("/", $route);
191
192
        $value   = array(
193
            "type"       => $type,
194
            "class"      => $class,
195
            "service"    => array(),
196
            "parameters" => $parameters,
197
            "query"      => array()
198
        );
199
200
        $this->logger->debug("ROUTE: " . $route);
201
202
        $this->logger->debug("PARAMETERS: " . var_export($value, true));
203
204
        $regex = $this->readpath($folders, $value);
205
206
        $this->logger->debug("ROUTE: " . $regex);
207
208
        $this->logger->debug("PARAMETERS: " . var_export($value, true));
209
210
        $this->routes[$regex] = $value;
211
212
    }
213
214
}
215