Completed
Push — 4.0 ( 53586d...4a5124 )
by Marco
11:49
created

RoutingTable::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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