Completed
Push — master ( d34ae1...d2cd4a )
by kill
10:24
created

Dispatch::dispatch()   D

Complexity

Conditions 10
Paths 132

Size

Total Lines 46
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 35
nc 132
nop 2
dl 0
loc 46
rs 4.75
c 0
b 0
f 0

How to fix   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
namespace puck\helpers;
5
6
7
class Dispatch
8
{
9
    static public function init(){
0 ignored issues
show
Coding Style introduced by
init 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
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
10
        define('NOW_TIME', $_SERVER['REQUEST_TIME']);
11
        define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
12
        define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
13
        define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
14
        define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
15
        define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
16
        define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ) ? true : false);
17
        define('__SELF__', strip_tags($_SERVER['REQUEST_URI']));
18
    }
19
    static public function dispatch($path='',$app='\\admin') {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
Coding Style Best Practice introduced by
Please use __construct() instead of a PHP4-style constructor that is named after the class.
Loading history...
20
        self::init();
21
        if($path==''){
22
            $path=array();
23
        }else{
24
            $path=str_replace('-','_',$path);
25
            $path   = explode('/',$path);
26
        }
27
28
        if(count($path)==0){
29
            array_push($path,'home');
30
            array_push($path,'index');
31
        }
32
        elseif (count($path)==1){
33
            array_push($path,'index');
34
        }
35
        if(!empty($path)){
36
            $tmpAction=array_pop($path);
37
            $tmpAction=preg_replace('/\.(html|aspx|do|php|htm|h5|api)$/i', '', $tmpAction);
38
            $tmpAction=parse_name($tmpAction,1);
39
            $var['a']=$tmpAction;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$var was never initialized. Although not strictly required by PHP, it is generally a good practice to add $var = 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...
40
        }
41
        define('ACTION_NAME',$var['a']);
0 ignored issues
show
Bug introduced by
The variable $var 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...
42
        if (!preg_match('/^[A-Za-z](\w)*$/', ACTION_NAME)) {
43
            die("error action");
0 ignored issues
show
Coding Style Compatibility introduced by
The method dispatch() 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...
44
        }
45
        if(!empty($path)){
46
            $tmpController=array_pop($path);
47
            $tmpController=parse_name($tmpController,1);
48
            $var['c']=$tmpController;
49
        }
50
        define('CONTROLLER_NAME',$var['c']);
51
        if (!preg_match('/^[A-Za-z](\/|\w)*$/', CONTROLLER_NAME)) {
52
            die("error controller");
0 ignored issues
show
Coding Style Compatibility introduced by
The method dispatch() 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...
53
        }
54
        $class=$app.'\\controllers\\'.ucfirst(CONTROLLER_NAME);
55
        if (!class_exists($class)) {
56
            not_found('this controller is can not work now!');
57
        }
58
        $class= new $class();
59
        if (!method_exists($class,ACTION_NAME)) {
60
            not_found();
61
        }
62
        self::param();
63
        self::exec($class,ACTION_NAME);
64
    }
65
    static public function exec($class,$function){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
66
        $method = new \ReflectionMethod($class, $function);
67
        if ($method->isPublic() && !$method->isStatic()) {
68
            $refClass = new \ReflectionClass($class);
69
            //前置方法
70
            if ($refClass->hasMethod('_before_' . $function)) {
71
                $before = $refClass->getMethod('_before_' . $function);
72
                if ($before->isPublic()) {
73
                    $before->invoke($class);
74
                }
75
            }
76
            //方法本身
77
            $response=$method->invoke($class);
78
            //后置方法
79
            if ($refClass->hasMethod('_after_' . $function)) {
80
                $after = $refClass->getMethod('_after_' . $function);
81
                if ($after->isPublic()) {
82
                    $after->invoke($class);
83
                }
84
            }
85
            self::render($response);
86
        }
87
    }
88
    static public function param(){
0 ignored issues
show
Coding Style introduced by
param 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
param uses the super-global variable $_GET 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
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
89
        $vars=array();
90
        parse_str(parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY),$vars);
91
        $_GET=$vars;
92
    }
93
    static public function render($res){
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
94
        $response=$res;
95
        if(is_array($res)){
96
            $response=json($res);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $response is correct as json($res) (which targets json()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
97
        }
98
        echo $response;
99
    }
100
}