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

headers   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 96.47%

Importance

Changes 4
Bugs 2 Features 4
Metric Value
wmc 33
c 4
b 2
f 4
lcom 1
cbo 0
dl 0
loc 136
ccs 82
cts 85
cp 0.9647
rs 9.3999

5 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 30 8
A getLastHeader() 0 6 2
A parseHeader() 0 11 4
C getCacheControlTime() 0 38 13
B parseCacheTime() 0 15 6
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
    /**
73
     * Return an array with values from a header like Cache-Control
74
     * e.g. 'max-age=300,public,no-store'
75
     * results in
76
     * [ 'max-age' => '300', 'public' => 'public', 'no-store' => 'no-store' ]
77
     * @param string $header
78
     * @return array
79
     */
80 3
    public static function parseHeader($header)
81
    {
82 3
        $header = (strpos($header, ':')!==false) ? explode(':', $header)[1] : $header;
83 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...
84 3
        $header = [];
85 3
        foreach ( $info as $entry ) {
86 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...
87 3
            $header[ $temp[0] ] = (isset($temp[1]) ? $temp[1] : $temp[0] );
88 3
        }
89 3
        return $header;
90
    }
91
92 3
    private static function getCacheControlTime( $header, $private )
93
    {
94 3
        $result = null;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 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...
95 3
        $dontcache = false;
96 3
        foreach ( $header as $key => $value ) {
97
            switch($key) {
98 3
                case 'max-age':
99 3
                case 's-maxage':
100 3
                    if ( isset($result) ) {
101 3
                        $result = min($result, (int) $value);
102 3
                    } else {
103 3
                        $result = (int) $value;
104
                    }
105 3
                break;
106 3
                case 'public':
107 2
                break;
108 3
                case 'private':
109 1
                    if ( !$private ) {
110 1
                        $dontcache = true;
111 1
                    }
112 1
                break;
113 2
                case 'no-cache':
114 2
                case 'no-store':
115 1
                    $dontcache = true;
116 1
                break;
117 1
                case 'must-revalidate':
118 1
                case 'proxy-revalidate':
119
                    $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...
120
                break;
121 1
                default:
122 1
                break;
123 1
            }
124 3
        }
125 3
        if ( $dontcache ) {
126 2
            $result = 0;
127 2
        }
128 3
        return $result;
129
    }
130
131
    /**
132
     * Parse response headers to determine if and how long you may cache the response. Doesn't understand ETags.
133
     * @param mixed $headers Headers string or array as returned by parse()
134
     * @param bool $private Whether to store a private cache or public cache image.
135
     * @return int The number of seconds you may cache this result starting from now.
136
     */
137 4
    public static function parseCacheTime( $headers, $private=true )
138
    {
139 4
        $result = null;
140 4
        if ( is_string($headers) || !isset($headers['Content-Type'] )) {
141 3
            $headers = \arc\http\headers::parse( $headers );
142 3
        }
143 4
        if ( isset( $headers['Cache-Control'] ) ) {
144 3
            $header = self::parseHeader( self::getLastHeader( $headers['Cache-Control'] ) );
145 3
            $result = self::getCacheControlTime( $header, $private );
146 3
        }
147 4
        if ( !isset($result) && isset( $headers['Expires'] ) ) {
148 1
            $result = strtotime( self::getLastHeader($headers['Expires']) ) - time();
149 1
        }
150 4
        return (int) $result;
151
    }
152
153
}