Request::run()   C
last analyzed

Complexity

Conditions 11
Paths 20

Size

Total Lines 52
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 11
eloc 27
c 5
b 0
f 0
nc 20
nop 0
dl 0
loc 52
rs 5.9999

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
/**
4
 * Luthier Request middleware (internal)
5
 *
6
 * @author    Anderson Salas <[email protected]>
7
 * @copyright 2017
8
 * @license   GNU-3.0
9
 *
10
 */
11
12
namespace Luthier\Middleware;
13
14
use Luthier\Core\Route as Route;
15
16
class Request extends \Luthier\Core\Middleware
17
{
18
19
    /**
20
     * Current (improved) route
21
     *
22
     * @var $route
23
     *
24
     * @access protected
25
     */
26
    protected $route;
27
28
    /**
29
     * Infered request method
30
     *
31
     * @var $requestMethod
32
     *
33
     * @access protected
34
     */
35
    protected $requestMethod;
36
37
    /**
38
     * Class constructor
39
     *
40
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
41
     *
42
     * @access public
43
     */
44
    public function __construct()
45
    {
46
        parent::__construct();
47
        $this->deterimeRequestMethod();
48
        $this->route = Route::getRouteByPath(self::$uri_string, $this->requestMethod);
49
    }
50
51
    /**
52
     * Determines the actual request method
53
     *
54
     * @return void
55
     *
56
     * @access private
57
     */
58
    private function deterimeRequestMethod()
0 ignored issues
show
Coding Style introduced by
deterimeRequestMethod 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...
Coding Style introduced by
deterimeRequestMethod uses the super-global variable $_POST 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...
59
    {
60
61
        $requestMethod = $_SERVER['REQUEST_METHOD'];
62
        $formMethod    = NULL;
63
        $validMethods  = Route::getHTTPVerbs();
64
65
        // FIXME: Solve ambiguity here! POST with _method="GET" makes no sense
66
67
        if (isset($_POST['_method']) && in_array(strtoupper($_POST['_method']), $validMethods, TRUE))
68
            $formMethod = strtoupper($_POST['_method']);
69
70
        if (is_null($formMethod))
71
        {
72
            $this->requestMethod = $requestMethod;
73
        }
74
        else
75
        {
76
            if ($requestMethod == 'POST')
77
                $this->requestMethod = $formMethod;
78
79
            if (!$this->CI->input->is_ajax_request() && $this->requestMethod == 'HEAD')
0 ignored issues
show
Bug introduced by
The property input does not seem to exist in Luthier\Core\Middleware.

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...
80
                $this->requestMethod = 'POST';
81
        }
82
    }
83
84
    /**
85
     * Entry point of the middleware
86
     *
87
     * @return void
88
     *
89
     * @access public
90
     */
91
    public function run()
92
    {
93
        if (!$this->route)
94
        {
95
            if (ENVIRONMENT != 'production')
96
                show_error('The request method '.$this->requestMethod.' is not allowed to view the resource', 403, 'Forbidden method');
97
98
            if(is_null(Route::get404()))
99
                show_404();
100
101
            if (Route::get404()->controller != get_class($this->CI))
0 ignored issues
show
Bug introduced by
The property controller does not seem to exist. Did you mean defaultController?

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...
102
                Route::trigger404();
103
        }
104
        else
105
        {
106
            if (method_exists($this->CI, $this->route->method))
107
            {
108
                $path_args  = Route::getRouteArgs($this->route, self::$uri_string);
0 ignored issues
show
Documentation introduced by
self::$uri_string is of type object<Luthier\Core\Middleware>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
109
                $route_args = Route::compileRoute($this->route)->args;
110
111
                // Redirect to 404 if not enough parameters provided
112
113
                if(count($path_args) < count($route_args['required']))
114
                    redirect(Route::get404()->path);
115
116
                if(count($path_args) == 0)
117
                {
118
                    $this->CI->{$this->route->method}();
119
                }
120
                else
121
                {
122
                    call_user_func_array( [$this->CI, $this->route->method], array_values($path_args) );
123
                }
124
125
                // TODO: Add support to hooks in this execution thread
126
127
                $this->CI->output->_display();
0 ignored issues
show
Bug introduced by
The property output does not seem to exist in Luthier\Core\Middleware.

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...
128
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method run() 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...
129
            }
130
            else
131
            {
132
                if (ENVIRONMENT != 'production')
133
                    show_error('The method '.$this->route->controller.'::'.$this->route->method.'() does not exists', 500, 'Method not found');
134
135
                if(is_null(Route::get404()))
136
                    show_404();
137
138
                if (Route::get404()->controller != get_class($this->CI))
0 ignored issues
show
Bug introduced by
The property controller does not seem to exist. Did you mean defaultController?

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...
139
                    Route::trigger404();
140
            }
141
        }
142
    }
143
}