Completed
Push — dev-master ( 34bab5...a36613 )
by Vijay
04:51
created

Response::json()   C

Complexity

Conditions 15
Paths 96

Size

Total Lines 50
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 0 Features 0
Metric Value
c 10
b 0
f 0
dl 0
loc 50
rs 5.3624
cc 15
eloc 28
nc 96
nop 2

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
namespace FFMVC\Helpers;
4
5
/**
6
 * HTTP Response Helper Class.
7
 *
8
 * @author Vijay Mahrra <[email protected]>
9
 * @copyright (c) Copyright 2015 Vijay Mahrra
10
 * @license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
11
 */
12
class Response extends \Prefab
13
{
14
    /**
15
     * Encode the input parameter $data as JSON and output it with appropriate http headers.
16
     *
17
     * @param mixed $data   input variable, takes origin, age, methods
18
     * @param array $params parameters for the http headers: ttl, origin, methods (GET, POST, PUT, DELETE)
19
     *
20
     * @return void()
0 ignored issues
show
Documentation introduced by
The doc-type void() could not be parsed: Expected "|" or "end of type", but got "(" at position 4. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
21
     *
22
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
23
     * @see https://www.w3.org/TR/cors/
24
     */
25
    public static function json(array $data, array $params = [])
26
    {
27
        $f3 = \Base::instance();
28
29
        $body    = json_encode($data, JSON_PRETTY_PRINT);
30
        $headers = array_key_exists('headers', $params) ? $params['headers'] : [];
31
32
        // set ttl
33
        $ttl = (int) array_key_exists('ttl', $params) ? $params['ttl'] : 0; // cache for $ttl seconds
34
35
        $headers = array_merge($headers, [
36
            'Content-type'                     => 'application/json; charset=utf-8',
37
            'Expires'                          => Time::http(time() + $ttl),
38
            'Access-Control-Max-Age'           => $ttl,
39
            'Access-Control-Expose-Headers'    => array_key_exists('acl_expose_headers', $params) ? $params['acl_expose_headers'] : null,
40
            'Access-Control-Allow-Methods'     => array_key_exists('acl_http_methods', $params) ? $params['acl_http_methods'] : null,
41
            'Access-Control-Allow-Origin'      => array_key_exists('acl_origin', $params) ? $params['acl_origin'] : '*',
42
            'Access-Control-Allow-Credentials' => array_key_exists('acl_credentials', $params) && !empty($params['acl_credentials']) ?  'true' : 'false',
43
            'ETag'                             => array_key_exists('etag', $params) ? $params['etag'] : md5($body),
44
            'Content-Length'                   => \UTF::instance()->strlen($body),
45
        ]);
46
47
        // send the headers + data
48
49
        if (empty($ttl)) {
50
            $f3->expire(0);
51
            $ttl = 0;
0 ignored issues
show
Unused Code introduced by
$ttl is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
        }
53
54
        // default status is 200 - OK
55
        $f3->status(array_key_exists('http_status', $params) ? $params['http_status'] : 200);
56
57
        // do not send session cookie
58
        if (!array_key_exists('cookie', $params)) {
59
            header_remove('Set-Cookie'); // prevent php session
60
        }
61
62
        ksort($headers);
63
        foreach ($headers as $header => $value) {
64
            if (!isset($value)) {
65
                continue;
66
            }
67
            header($header . ': ' . $value);
68
        }
69
70
        // HEAD request should be identical headers to GET request but no body
71
        if ('HEAD' !== $f3->get('VERB')) {
72
            echo $body;
73
        }
74
    }
75
}
76