Completed
Push — master ( 66a152...f0c72f )
by Auke
03:39
created

headers   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 36.62%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 28
c 1
b 0
f 1
lcom 0
cbo 0
dl 0
loc 109
ccs 26
cts 71
cp 0.3662
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 28 7
A getLastHeader() 0 6 2
C parseCacheTime() 0 49 19
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 2
    public static function parse( $headers ) {
30 2
        if ( !is_array($headers) && !$headers instanceof \ArrayObject ) {
31
            $headers = array_filter(
32
                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
            );
34
        }
35 2
        $result = [];
36 2
        foreach( $headers as $header ) {
37 2
            $temp = array_map('trim', explode(':', $header, 2) );
38 2
            if ( isset( $temp[1] ) ) {
39 2
                if ( !isset($result[ $temp[0]]) ) {
40
                    // first entry for this header
41 2
                    $result[ $temp[0] ] = $temp[1];
42 2
                } else if ( is_string($result[ $temp[0] ]) ) {
43
                    // second header entry with same name
44
                    $result[ $temp[0] ] = [
45
                        $result[ $temp[0] ],
46
                        $temp[1]
47
                    ];
48
                } else { // third or later header entry with same name
49
                    $result[ $temp[0] ][] = $temp[1];
50
                }
51 2
            } else { // e.g. HTTP1/1 200 OK
52 1
                $result[] = $temp[0];
53
            }
54 2
        }
55 2
        return $result;
56
    }
57
58
    /**
59
     * Return the last value sent for a specific header, uses the output of parse().
60
     * @param (mixed) $headers An array with multiple header strings or a single string.
61
     * @return array|mixed
62
     */
63 1
    private static function getLastHeader($headers) {
64 1
        if ( is_array($headers) ) {
65
            return end($headers);
66
        }
67 1
        return $headers;
68
    }
69
70
    /**
71
     * Parse response headers to determine if and how long you may cache the response. Doesn't understand ETags.
72
     * @param mixed $headers Headers string or array as returned by parse()
73
     * @param bool $private Whether to store a private cache or public cache image.
74
     * @return int The number of seconds you may cache this result starting from now.
75
     */
76 1
    public static function parseCacheTime( $headers, $private=true ) {
77 1
        $result = 0;
78 1
        if ( is_string($headers) || !isset($headers['Content-Type'] )) {
79 1
            $headers = \arc\http\headers::parse( $headers );
80 1
        }
81 1
        if ( isset( $headers['Cache-Control'] ) ) {
82
            $header = self::getLastHeader($headers['Cache-Control']);
83
            $info = array_map('trim', explode($header, ','));
84
            $header = [];
85
            foreach ( $info as $entry ) {
86
                $temp = array_map( 'trim', explode( $entry, '='));
87
                $header[ $temp[0] ] = (isset($temp[1]) ? $temp[1] : $temp[0] );
88
            }
89
            $dontcache = false;
90
            foreach ( $header as $key => $value ) {
91
                switch($key) {
92
                    case 'max-age':
93
                    case 's-maxage':
94
                        $result = (int) $value;
95
                        break;
96
                    case 'public':
97
                        break;
98
                    case 'private':
99
                        if ( !$private ) {
100
                            $dontcache = true;
101
                        }
102
                        break;
103
                    case 'no-cache':
104
                    case 'no-store':
105
                        $dontcache = true;
106
                        break;
107
                    case 'must-revalidate':
108
                    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
                }
112
            }
113
            if ( $dontcache ) {
114
                return 0;
115
            }
116
            if ( $result ) {
117
                return $result;
118
            }
119
        }
120 1
        if ( isset( $headers['Expires'] ) ) {
121 1
            $result = strtotime( self::getLastHeader($headers['Expires']) ) - time();
122 1
        }
123 1
        return $result;
124
    }
125
126
}