Completed
Push — master ( dbac5b...8dd423 )
by Alejandro
08:15
created

Router::__construct()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 12
rs 8.8571
cc 5
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Tight;
4
5
/*
6
 * The MIT License
7
 *
8
 * Copyright 2016 Alejandro Peña Florentín ([email protected])
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a copy
11
 * of this software and associated documentation files (the "Software"), to deal
12
 * in the Software without restriction, including without limitation the rights
13
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
 * copies of the Software, and to permit persons to whom the Software is
15
 * furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included in
18
 * all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
 * THE SOFTWARE.
27
 */
28
29
/**
30
 * Description of Route
31
 *
32
 * @author Alejandro Peña Florentín ([email protected])
33
 */
34
class Router
35
{
36
37
    /**
38
     * @var array Routes
39
     */
40
    protected $routes;
41
42
    /**
43
     * @var string Base path for rutes. If Router is not instanciated in 
44
     * document root this value must be set
45
     */
46
    private $basePath;
47
48
    public function __construct($basePath) {
1 ignored issue
show
Coding Style introduced by
__construct 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...
49
        if (null !== $basePath && is_string($basePath) && !empty($basePath)) {
50
            $basePath = Utils::filterPath($basePath);
51
            if (Utils::inString($basePath, $_SERVER['DOCUMENT_ROOT'])) {
52
                $this->basePath = Utils::removeSubstring($basePath, $_SERVER['DOCUMENT_ROOT']);
53
            } else {
54
                $this->basePath = $basePath;
55
            }
56
        } else {
57
            $this->basePath = "/";
58
        }
59
    }
60
61
    /**
62
     * 
63
     * @param type $pattern
0 ignored issues
show
Bug introduced by
There is no parameter named $pattern. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
64
     * @param type $args
0 ignored issues
show
Bug introduced by
There is no parameter named $args. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
65
     * @return 
66
     */
67
    public function get() {
68
69
        return $this->url(Route::METHOD_GET, func_get_args());
70
    }
71
72
    public function post() {
73
        return $this->url(Route::METHOD_POST, func_get_args());
74
    }
75
76
    public function update() {
77
        return $this->url(Route::METHOD_DELETE, func_get_args());
78
    }
79
80
    public function delete() {
81
        return $this->url(Route::METHOD_UPDATE, func_get_args());
82
    }
83
84
    public function url($methods, $args) {
85
        if (is_string($methods)) {
86
            $methods = [$methods];
87
        }
88
        $pattern = array_shift($args); // 2nd-> Pattern
89
        $callable = array_pop($args); // Last -> callable
90
        $route = new Route(Utils::removeDouble($this->basePath . $pattern, "/"), $callable);
91
        $route->setHttpMethods($methods);
92
        if (count($args) > 0) {
93
            $route->setMiddleware($args);
94
        }
95
        $this->routes[] = $route;
96
        return $this;
97
    }
98
99
    public function run() {
1 ignored issue
show
Coding Style introduced by
run 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...
100
        $uri = $_SERVER['REQUEST_URI'];
101
        $method = $_SERVER['REQUEST_METHOD'];
102
        $found = null;
103
        $index = 0;
104
        while ($index < count($this->routes) && null === $found) {
105
            if ($this->routes[$index]->match($uri)) {
106
                $found = $this->routes[$index];
107
            }
108
            $index++;
109
        }
110
        if (null !== $found && in_array(strtolower($method), $found->getHttpMethods())) {
111
            $found->dispatch();
112
        } else {
113
            $this->notFound();
114
        }
115
    }
116
117
    public function notFound() {
118
        echo "The requested URL cant be found";
119
    }
120
121
}
122