Passed
Push — master ( ce58fd...b8d195 )
by Matthias
02:26
created

Response::sendHttpStatus()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 75
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 75
ccs 0
cts 11
cp 0
rs 8.6428
c 1
b 1
f 0
cc 4
eloc 65
nc 4
nop 2
crap 20

How to fix   Long Method   

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
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2015 zepi
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 *
25
 */
26
27
/**
28
 * The Response holds all information which are outputtet at the end
29
 * of the request.
30
 * 
31
 * @package Zepi\Turbo\Response
32
 * @author Matthias Zobrist <[email protected]>
33
 * @copyright Copyright (c) 2015 zepi
34
 */
35
36
namespace Zepi\Turbo\Response;
37
38
use \Zepi\Turbo\Request\RequestAbstract;
39
use \Zepi\Turbo\Request\WebRequest;
40
41
/**
42
 * The Response holds all information which are outputtet at the end
43
 * of the request.
44
 * 
45
 * @author Matthias Zobrist <[email protected]>
46
 * @copyright Copyright (c) 2015 zepi
47
 */
48
class Response
49
{
50
    /**
51
     * @access protected
52
     * @var RequestAbstract
53
     */
54
    protected $request;
55
    
56
    /**
57
     * @access protected
58
     * @var array
59
     */
60
    protected $data = array();
61
    
62
    /**
63
     * @access protected
64
     * @var array
65
     */
66
    protected $outputParts = array();
67
    
68
    /**
69
     * @access protected
70
     * @var string
71
     */
72
    protected $output;
73
    
74
    /**
75
     * Constructs the object
76
     * 
77
     * @access public
78
     * @param \Zepi\Turbo\Request\RequestAbstract $request
79
     */
80 25
    public function __construct(RequestAbstract $request)
81
    {
82 25
        $this->request = $request;
83 25
    }
84
    
85
    /**
86
     * Return the data for the given key. If the key does 
87
     * not exists the function will return false.
88
     * 
89
     * @access public
90
     * @param string $key
91
     * @return mixed
92
     */
93 4
    public function getData($key)
94
    {
95 4
        if (!$this->hasData($key)) {
96 1
            return false;
97
        }
98
        
99 3
        return $this->data[$key];
100
    }
101
    
102
    /**
103
     * Returns true if the given key is set.
104
     * 
105
     * @access public
106
     * @param string $key
107
     * @return boolean
108
     */
109 4
    public function hasData($key)
110
    {
111 4
        return (isset($this->data[$key]));
112
    }
113
    
114
    /**
115
     * Saves the value for the given key in the response object.
116
     * 
117
     * @access public
118
     * @param string $key
119
     * @param mixed $value
120
     */
121 3
    public function setData($key, $value)
122
    {
123 3
        $this->data[$key] = $value;
124 3
    }
125
    
126
    /**
127
     * Returns the output for the given key. If the key does
128
     * not exists the function will return false.
129
     * 
130
     * @access public
131
     * @param string $key
132
     * @return false|string
133
     */
134 2
    public function getOutputPart($key)
135
    {
136 2
        if (!$this->hasOutputPart($key)) {
137 1
            return false;
138
        }
139
        
140 1
        return $this->outputParts[$key];
141
    }
142
    
143
    /**
144
     * Returns true if the given key exists as output key.
145
     * 
146
     * @access public
147
     * @param string $key
148
     * @return boolean
149
     */
150 2
    public function hasOutputPart($key)
151
    {
152 2
        return (isset($this->outputParts[$key]));
153
    }
154
    
155
    /**
156
     * Saves the output for the given key in the Response object.
157
     * 
158
     * @access public
159
     * @param string $key
160
     * @param string $output
161
     */
162 2
    public function setOutputPart($key, $output)
163
    {
164 2
        $this->outputParts[$key] = $output;
165 2
    }
166
    
167
    /**
168
     * Returns all output parts of the Response object.
169
     * 
170
     * @access public
171
     * @return array
172
     */
173 1
    public function getOutputParts()
174
    {
175 1
        return $this->outputParts;
176
    }
177
    
178
    /**
179
     * Returns the output of the response.
180
     * 
181
     * @access public
182
     * @return string
183
     */
184 3
    public function getOutput()
185
    {
186 3
        return $this->output;
187
    }
188
    
189
    /**
190
     * Returns true if the response has an output.
191
     * 
192
     * @access public
193
     * @return boolean
194
     */
195 1
    public function hasOutput()
196
    {
197 1
        return ($this->output != '');
198
    }
199
    
200
    /**
201
     * Sets the output of the response.
202
     * 
203
     * @access public
204
     * @param string $output
205
     */
206 1
    public function setOutput($output)
207
    {
208 1
        $this->output = $output;
209 1
    }
210
    
211
    /**
212
     * Set the Location header to redirect a request
213
     * 
214
     * @access public
215
     * @param string $target
216
     * @param integer $headerCode
217
     * @param boolean $withOrigin
218
     */
219 2
    public function redirectTo($target, $headerCode = 301, $withOrigin = false)
220
    {
221 2
        if (!($this->request instanceof WebRequest)) {
222
            return;
223
        }
224
        
225 2
        if (strpos($target, 'http://') === false) {
226 1
            $target = $this->request->getFullRoute($target);
227
        }
228
        
229 2
        if ($withOrigin) {
230
            $origin = $this->request->getFullRoute();
231
            $additionalQuery = '_origin=' . base64_encode($origin);
232
            
233
            $parts = parse_url($target);
234
            
235
            if ($parts === false) {
236
                return;
237
            }
238
            
239
            if (!isset($parts['query'])) {
240
                $parts['query'] = '';
241
            } else if ($parts['query'] !== '') {
242
                $parts['query'] .= '&';
243
            }
244
            
245
            $parts['query'] .= $additionalQuery;
246
            $target = $this->buildUrl($parts);
247
        }
248
        
249 2
        header("Location: " . $target, true, $headerCode);
250 2
    }
251
    
252
    /**
253
     * Sends a header
254
     * 
255
     * @access public
256
     * @param string $message
257
     * @param integer $code
258
     */
259
    public function sendHeader($message, $code = null)
260
    {
261
        if (!($this->request instanceof WebRequest)) {
262
            return;
263
        }
264
        
265
        if ($code !== null) {
266
            header($message, true, $code);
267
        } else {
268
            header($message);
269
        }
270
    }
271
    
272
    /**
273
     * Sends the status code for the give code
274
     * 
275
     * @access public
276
     * @param integer $code
277
     * @param boolean $resetOutput
278
     */
279
    public function sendHttpStatus($code, $resetOutput = false)
280
    {
281
        if (!($this->request instanceof WebRequest)) {
282
            return;
283
        }
284
        
285
        $codes = array(
286
            100 => 'Continue',
287
            101 => 'Switching Protocols',
288
            102 => 'Processing',
289
            200 => 'OK',
290
            201 => 'Created',
291
            202 => 'Accepted',
292
            203 => 'Non-Authoritative Information',
293
            204 => 'No Content',
294
            205 => 'Reset Content',
295
            206 => 'Partial Content',
296
            207 => 'Multi-Status',
297
            300 => 'Multiple Choices',
298
            301 => 'Moved Permanently',
299
            302 => 'Found',
300
            303 => 'See Other',
301
            304 => 'Not Modified',
302
            305 => 'Use Proxy',
303
            306 => 'Switch Proxy',
304
            307 => 'Temporary Redirect',
305
            400 => 'Bad Request',
306
            401 => 'Unauthorized',
307
            402 => 'Payment Required',
308
            403 => 'Forbidden',
309
            404 => 'Not Found',
310
            405 => 'Method Not Allowed',
311
            406 => 'Not Acceptable',
312
            407 => 'Proxy Authentication Required',
313
            408 => 'Request Timeout',
314
            409 => 'Conflict',
315
            410 => 'Gone',
316
            411 => 'Length Required',
317
            412 => 'Precondition Failed',
318
            413 => 'Request Entity Too Large',
319
            414 => 'Request-URI Too Long',
320
            415 => 'Unsupported Media Type',
321
            416 => 'Requested Range Not Satisfiable',
322
            417 => 'Expectation Failed',
323
            418 => 'I\'m a teapot',
324
            422 => 'Unprocessable Entity',
325
            423 => 'Locked',
326
            424 => 'Failed Dependency',
327
            425 => 'Unordered Collection',
328
            426 => 'Upgrade Required',
329
            449 => 'Retry With',
330
            450 => 'Blocked by Windows Parental Controls',
331
            500 => 'Internal Server Error',
332
            501 => 'Not Implemented',
333
            502 => 'Bad Gateway',
334
            503 => 'Service Unavailable',
335
            504 => 'Gateway Timeout',
336
            505 => 'HTTP Version Not Supported',
337
            506 => 'Variant Also Negotiates',
338
            507 => 'Insufficient Storage',
339
            509 => 'Bandwidth Limit Exceeded',
340
            510 => 'Not Extended'
341
        );
342
        
343
        if (!isset($codes[$code])) {
344
            return false;
345
        }
346
        
347
        $message = $this->request->getProtocol() . ' ' . $code . ' ' . $codes[$code];
348
        header($message, true, $code);
349
        
350
        if ($resetOutput) {
351
            $this->setOutput($message);
352
        }
353
    }
354
    
355
    /**
356
     * Returns a full url for the given url parts array
357
     * from the function `parse_url()`.
358
     * 
359
     * @access public
360
     * @param array $urlParts
361
     * @return string
362
     */
363
    public function buildUrl($urlParts)
364
    {
365
        $url = '';
366
        $auth = false;
367
        
368
        if (isset($urlParts['scheme'])) {
369
            $url .= $urlParts['scheme'] . '://';
370
        }
371
        
372
        if (isset($urlParts['user'])) {
373
            $url .= $urlParts['user'];
374
            $auth = true;
375
        }
376
        
377
        if (isset($urlParts['pass'])) {
378
            $url .= ':' . $urlParts['pass'];
379
            $auth = true;
380
        }
381
        
382
        if ($auth) {
383
            $url .= '@';
384
        }
385
        
386
        if (isset($urlParts['host'])) {
387
            $url .= $urlParts['host'];
388
        }
389
        
390
        if (isset($urlParts['port'])) {
391
            $url .= ':' . $urlParts['port'];
392
        }
393
        
394
        if (isset($urlParts['path'])) {
395
            $url .= $urlParts['path'];
396
        }
397
        
398
        if (isset($urlParts['query'])) {
399
            $url .= '?' . $urlParts['query'];
400
        }
401
        
402
        if (isset($urlParts['fragment'])) {
403
            $url .= '#' . $urlParts['fragment'];
404
        }
405
        
406
        return $url;
407
    }
408
}
409