Dispatch::exec()   C
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 14
c 0
b 0
f 0
nc 10
nop 2
dl 0
loc 23
ccs 0
cts 21
cp 0
crap 56
rs 6.7272
1
<?php
2
3
4
namespace puck\helpers;
5
6
7
class Dispatch
8
{
9
    static $path;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $path.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
10
    static $ext;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $ext.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
11
    static public function init() {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
12
        if (!IS_CLI) {
13
            define('NOW_TIME', $_SERVER['REQUEST_TIME']);
14
            define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
15
            define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
16
            define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
17
            define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
18
            define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
19
            define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) ? true : false);
20
            define('__SELF__', strip_tags($_SERVER['REQUEST_URI']));
21
        }
22
    }
23
    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...
24
        self::init();
25
        self::$path=$path;
26
        if ($path == '') {
27
            $path=array();
28
        } else {
29
            $path=str_replace('-', '_', $path);
30
            $path=explode('/', $path);
31
        }
32
33
        if (count($path) == 0) {
34
            array_push($path, 'home');
35
            array_push($path, 'index');
36
        } elseif (count($path) == 1) {
37
            array_push($path, 'index');
38
        }
39
        if (!empty($path)) {
40
            $tmpAction=array_pop($path);
41
            $tmpArray=explode(".",$tmpAction);
42
            self::$ext=$tmpArray[1]??"";
43
            $tmpAction=preg_replace('/\.(html|aspx|do|php|htm|h5|api|json|xml)$/i', '', $tmpAction);
44
            $tmpAction=parse_name($tmpAction, 1);
45
            $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...
46
        }
47
        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...
48
        if (!preg_match('/^[A-Za-z](\w)*$/', ACTION_NAME)) {
49
            die("error action");
50
        }
51
        if (!empty($path)) {
52
            $tmpController=array_pop($path);
53
            $tmpController=parse_name($tmpController, 1);
54
            $var['c']=$tmpController;
55
        }
56
        define('CONTROLLER_NAME', $var['c']);
57
        if (!preg_match('/^[A-Za-z](\/|\w)*$/', CONTROLLER_NAME)) {
58
            die("error controller");
59
        }
60
        $class=$app.'\\controllers\\'.ucfirst(CONTROLLER_NAME);
61
        if (!class_exists($class)) {
62
            not_found('this controller is can not work now!');
63
        }
64
        $class=new $class();
65
        if (!method_exists($class, ACTION_NAME)) {
66
            not_found();
67
        }
68
        self::param();
69
        self::exec($class, ACTION_NAME);
70
    }
71
72
    /**
73
     * @param string $function
74
     */
75
    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...
76
        $method=new \ReflectionMethod($class, $function);
77
        if ($method->isPublic() && !$method->isStatic()) {
78
            $refClass=new \ReflectionClass($class);
79
            //前置方法
80
            if ($refClass->hasMethod('_before_'.$function)) {
81
                $before=$refClass->getMethod('_before_'.$function);
82
                if ($before->isPublic()) {
83
                    $before->invoke($class);
84
                }
85
            }
86
            //方法本身
87
            $response=$method->invoke($class);
88
            //后置方法
89
            if ($refClass->hasMethod('_after_'.$function)) {
90
                $after=$refClass->getMethod('_after_'.$function);
91
                if ($after->isPublic()) {
92
                    $after->invoke($class);
93
                }
94
            }
95
            self::render($response);
96
        }
97
    }
98
    static public function param() {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
99
        if (!IS_CLI) {
100
            $vars=array();
101
            parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $vars);
102
            $_GET=$vars;
103
        }
104
105
    }
106
    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...
107
        $response=$res;
108
        $renderType=self::$ext;
109
110
        if($renderType=='json'){
111
            $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...
112
        }elseif ($renderType=='xml'){
113
            //todo:: 支持xml格式化输出
114
            $response='don\'t support xml now!';
115
        }elseif ($renderType==""){
116
            if(is_array($res)||is_object($res)){
117
                $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...
118
            }
119
        }
120
121
        echo $response;
122
    }
123
}