Completed
Pull Request — master (#18)
by Auke
02:09
created

headers::parse()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 8

Importance

Changes 2
Bugs 1 Features 2
Metric Value
c 2
b 1
f 2
dl 0
loc 30
ccs 25
cts 25
cp 1
rs 5.3846
cc 8
eloc 21
nc 12
nop 1
crap 8
1
<?php
2
3
/*
4
 * This file is part of the Ariadne Component Library.
5
 *
6
 * (c) Muze <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace arc\http;
13
14
/**
15
 * Class headers
16
 * @package arc\http
17
 */
18
final class headers
19
{
20
21
    /**
22
     * Parse response headers string from a HTTP request into an array of headers. e.g.
23
     * [ 'Location' => 'http://www.example.com', ... ]
24
     * When multiple headers with the same name are present, all values will form an array, in the order in which
25
     * they are present in the source.
26
     * @param string $headers The headers string to parse.
27
     * @return array
28
     */
29 5
    public static function parse( $headers ) {
30 5
        if ( !is_array($headers) && !$headers instanceof \ArrayObject ) {
31 3
            $headers = array_filter(
32 3
                array_map( "trim", explode( "\n", (string) $headers ) )
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal trim does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
33 3
            );
34 3
        }
35 5
        $result = [];
36 5
        foreach( $headers as $key => $header ) {
37 5
            $temp = array_map('trim', explode(':', $header, 2) );
38 5
            if ( isset( $temp[1] ) ) {
39 5
                if ( !isset($result[ $temp[0]]) ) {
40
                    // first entry for this header
41 5
                    $result[ $temp[0] ] = $temp[1];
42 5
                } else if ( is_string($result[ $temp[0] ]) ) {
43
                    // second header entry with same name
44 1
                    $result[ $temp[0] ] = [
45 1
                        $result[ $temp[0] ],
46 1
                        $temp[1]
47 1
                    ];
48 1
                } else { // third or later header entry with same name
49 1
                    $result[ $temp[0] ][] = $temp[1];
50
                }
51 5
            } else if (is_numeric($key)) {
52 4
                $result[] = $temp[0];
53 4
            } else { // e.g. HTTP1/1 200 OK
54 2
                $result[$key] = $temp[0];
55
            }
56 5
        }
57 5
        return $result;
58
    }
59
60
    /**
61
     * Return the last value sent for a specific header, uses the output of parse().
62
     * @param (mixed) $headers An array with multiple header strings or a single string.
63
     * @return array|mixed
64
     */
65 4
    private static function getLastHeader($headers) {
66 4
        if ( is_array($headers) ) {
67
            return end($headers);
68
        }
69 4
        return $headers;
70
    }
71
72 3
    public static function parseHeader($header)
73
    {
74 3
        $info = array_map('trim', explode(',', $header));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
75 3
        $header = [];
76 3
        foreach ( $info as $entry ) {
77 3
            $temp = array_map( 'trim', explode( '=', $entry ));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 15 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
78 3
            $header[ $temp[0] ] = (isset($temp[1]) ? $temp[1] : $temp[0] );
79 3
        }
80 3
        return $header;
81
    }
82
83 3
    static private function getCacheControlTime( $header, $private )
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
84
    {
85 3
        $dontcache = false;
86 3
        foreach ( $header as $key => $value ) {
87
            switch($key) {
88 3
                case 'max-age':
89 3
                case 's-maxage':
90 3
                    if ( isset($result) ) {
91 3
                        $result = min($result, (int) $value);
92 3
                    } else {
93 3
                        $result = (int) $value;
94
                    }
95 3
                break;
96 3
                case 'public':
97 2
                break;
98 3
                case 'private':
99 1
                    if ( !$private ) {
100 1
                        $dontcache = true;
101 1
                    }
102 1
                break;
103 2
                case 'no-cache':
104 2
                case 'no-store':
105 1
                    $dontcache = true;
106 1
                break;
107 1
                case 'must-revalidate':
108 1
                case 'proxy-revalidate':
109
                    $dontcache = true; // FIXME: should return more information than just the cache time instead
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "should return more information than just the cache time instead"
Loading history...
110
                break;
111 1
                default:
112 1
                break;
113 1
            }
114 3
        }
115 3
        if ( $dontcache ) {
116 2
            $result = 0;
117 2
        }
118 3
        return $result;
0 ignored issues
show
Bug introduced by
The variable $result 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...
119
    }
120
121
    /**
122
     * Parse response headers to determine if and how long you may cache the response. Doesn't understand ETags.
123
     * @param mixed $headers Headers string or array as returned by parse()
124
     * @param bool $private Whether to store a private cache or public cache image.
125
     * @return int The number of seconds you may cache this result starting from now.
126
     */
127 4
    public static function parseCacheTime( $headers, $private=true )
128
    {
129 4
        $result = null;
130 4
        if ( is_string($headers) || !isset($headers['Content-Type'] )) {
131 3
            $headers = \arc\http\headers::parse( $headers );
132 3
        }
133 4
        if ( isset( $headers['Cache-Control'] ) ) {
134 3
            $header = self::parseHeader( self::getLastHeader( $headers['Cache-Control'] ) );
135 3
            $result = self::getCacheControlTime( $header, $private );
136 3
        }
137 4
        if ( !isset($result) && isset( $headers['Expires'] ) ) {
138 1
            $result = strtotime( self::getLastHeader($headers['Expires']) ) - time();
139 1
        }
140 4
        return (int) $result;
141
    }
142
143
}