Ajde_Http_Response::dieOnRoute()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 2
nop 1
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
1
<?php
2
3
class Ajde_Http_Response extends Ajde_Object_Standard
4
{
5
    const REDIRECT_HOMEPAGE = 1;
6
    const REDIRECT_REFFERER = 2;
7
    const REDIRECT_SELF = 3;
8
9
    const RESPONSE_TYPE_NOT_MODIFIED = 304;
10
    const RESPONSE_TYPE_UNAUTHORIZED = 401;
11
    const RESPONSE_TYPE_FORBIDDEN = 403;
12
    const RESPONSE_TYPE_NOTFOUND = 404;
13
    const RESPONSE_TYPE_SERVERERROR = 500;
14
15
    public static function redirectNotFound()
16
    {
17
        self::dieOnCode(self::RESPONSE_TYPE_NOTFOUND);
18
    }
19
20
    public static function redirectServerError()
21
    {
22
        self::dieOnCode(self::RESPONSE_TYPE_SERVERERROR);
23
    }
24
25
    /**
26
     * Use only when user is not logged in, or for failed logon attempts.
27
     */
28
    public static function redirectUnauthorized()
29
    {
30
        self::dieOnCode(self::RESPONSE_TYPE_UNAUTHORIZED);
31
    }
32
33
    /**
34
     * Use for ACL declines / requests with no permission granted for the current user.
35
     */
36
    public static function redirectForbidden()
37
    {
38
        self::dieOnCode(self::RESPONSE_TYPE_FORBIDDEN);
39
    }
40
41
    public static function dieOnCode($code)
42
    {
43
        self::setResponseType($code);
44
45
        header('Content-type: text/html; charset=UTF-8');
46
47
        $_SERVER['REDIRECT_STATUS'] = $code;
48
49
        $errorRoutes = config('routes.errors');
50
        if (isset($errorRoutes[$code])) {
51
            try {
52
                self::dieOnRoute($errorRoutes[$code]);
53
            } catch (Exception $e) {
54
                Ajde_Exception_Log::logException($e);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

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...
55
            }
56
        }
57
58
        // fallback
59
        ob_get_clean();
60
        include LOCAL_ROOT.PUBLIC_DIR.'error.php';
61
        die();
62
    }
63
64
    public static function dieOnRoute($route)
65
    {
66
        ob_get_clean();
67
        // We start a mini app here to display the route
68
        // Copied from Ajde_Application
69
        $route = new Ajde_Core_Route($route);
70
        $document = Ajde_Document::fromRoute($route);
71
72
        // replace document in Ajde_Application
73
        Ajde::app()->setDocument($document);
0 ignored issues
show
Documentation Bug introduced by
The method setDocument does not exist on object<Ajde_Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
74
75
        // replace route in Ajde_Application
76
        Ajde::app()->setRoute($route);
0 ignored issues
show
Documentation Bug introduced by
The method setRoute does not exist on object<Ajde_Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
77
78
        $controller = Ajde_Controller::fromRoute($route);
79
        $actionResult = $controller->invoke();
80
        $document->setBody($actionResult);
81
        if (!$document->hasLayout()) {
0 ignored issues
show
Documentation Bug introduced by
The method hasLayout does not exist on object<Ajde_Document>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
82
            $layout = new Ajde_Layout(config('layout.frontend'));
83
            $document->setLayout($layout);
84
        }
85
        echo $document->render();
86
        die();
87
    }
88
89
    public static function setResponseType($code)
90
    {
91
        header('HTTP/1.1 '.$code.' '.self::getResponseType($code));
92
        ob_get_clean();
93
        header('Status: '.$code.' '.self::getResponseType($code));
94
    }
95
96 View Code Duplication
    protected static function getResponseType($code)
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...
97
    {
98
        switch ($code) {
99
            case 304:
100
                return 'Not Modified';
101
            case 400:
102
                return 'Bad Request';
103
            case 401:
104
                return 'Unauthorized';
105
            case 403:
106
                return 'Forbidden';
107
            case 404:
108
                return 'Not Found';
109
            case 500:
110
                return 'Internal Server Error';
111
            case 501:
112
                return 'Not Implemented';
113
            case 502:
114
                return 'Bad Gateway';
115
            case 503:
116
                return 'Service Unavailable';
117
            case 504:
118
                return 'Bad Timeout';
119
        }
120
    }
121
122
    public function setRedirect($url = self::REDIRECT_SELF)
123
    {
124
        if ($url === true || $url === self::REDIRECT_HOMEPAGE) {
125
            $this->addHeader('Location', config('app.rootUrl'));
126
        } elseif ($url === self::REDIRECT_REFFERER) {
127
            $this->addHeader('Location', Ajde_Http_Request::getRefferer());
128
        } elseif ($url === self::REDIRECT_SELF || empty($url)) {
129
            $route = (string) Ajde::app()->getRoute();
130
            $this->addHeader('Location', config('app.rootUrl').$route);
131
        } elseif (substr($url, 0, 7) == 'http://' || substr($url, 0, 8) == 'https://') {
132
            $this->addHeader('Location', $url);
133
        } elseif ($url) {
134
            $this->addHeader('Location', config('app.rootUrl').$url);
135
        }
136
        // Don't load any content after Location header is set
137
        Ajde::app()->getDocument()->setLayout(new Ajde_Layout('empty'));
138
    }
139
140
    public function addHeader($name, $value)
141
    {
142
        $headers = [];
143
        if ($this->has('headers')) {
144
            $headers = $this->get('headers');
145
        }
146
        $headers[$name] = $value;
147
        $this->set('headers', $headers);
148
    }
149
150
    public function removeHeader($name)
151
    {
152
        // TODO: also remove from $this->_data['headers']
153
        header("$name:");
154
        if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
155
            header_remove($name);
156
        }
157
    }
158
159
    public function setData($data)
160
    {
161
        $this->set('data', $data);
162
    }
163
164
    public function send()
165
    {
166
        if ($this->has('headers')) {
167
            foreach ($this->get('headers') as $name => $value) {
168
                header("$name: $value");
169
            }
170
        }
171
172
        if (!array_key_exists('Location', $this->get('headers'))) {
173
            echo $this->getData();
0 ignored issues
show
Documentation Bug introduced by
The method getData does not exist on object<Ajde_Http_Response>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
174
        }
175
    }
176
}
177