Completed
Push — master ( f85b73...7f85ed )
by Bohuslav
02:46
created

HeadersFactory::resolveHeaders()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
ccs 13
cts 13
cp 1
rs 8.7624
cc 6
eloc 10
nc 6
nop 1
crap 6
1
<?php
2
namespace Kambo\HttpMessage\Factories\Environment\Superglobal;
3
4
// \HttpMessage
5
use Kambo\HttpMessage\Headers;
6
use Kambo\HttpMessage\Environment\Environment;
7
use Kambo\HttpMessage\Factories\Environment\Interfaces\Factory;
8
9
/**
10
 * Create instance of Headers object from instance of Environment object
11
 *
12
 * @package Kambo\HttpMessage\Factories\Environment\Superglobal
13
 * @author  Bohuslav Simek <[email protected]>
14
 * @license MIT
15
 */
16
class HeadersFactory implements Factory
17
{
18
    /**
19
     * Special HTTP headers without "HTTP_" prefix for resolving headers
20
     *
21
     * @var array
22
     */
23
    private $specialHeaders = [
24
        'CONTENT_TYPE' => true,
25
        'CONTENT_LENGTH' => true,
26
        'PHP_AUTH_USER' => true,
27
        'PHP_AUTH_PW' => true,
28
        'PHP_AUTH_DIGEST' => true,
29
        'AUTH_TYPE' => true,
30
    ];
31
32
    /**
33
     * Create instance of Headers object from instance of Environment object
34
     *
35
     * @param Environment $environment environment data
36
     *
37
     * @return Headers Instance of Headers object from environment
38
     */
39 4
    public function create(Environment $environment)
40
    {
41 4
        return new Headers($this->resolveHeaders($environment->getServer()));
42
    }
43
44
    /**
45
     * Resolve headers from provided array
46
     *
47
     * @param array $headersForResolve array compatible with $_SERVER superglobal variable
48
     *
49
     * @return Headers Instance of Headers object from environment
50
     */
51 4
    private function resolveHeaders($headersForResolve)
52
    {
53 4
        $headers = [];
54
55 4
        foreach ($headersForResolve as $name => $value) {
56 3
            if (strpos($name, 'REDIRECT_') === 0) {
57 3
                $name = substr($name, 9);
58
59
                // Do not replace existing variables
60 3
                if (array_key_exists($name, $headersForResolve)) {
61 2
                     continue;
62
                }
63 3
            }
64
65 3
            if (substr($name, 0, 5) == 'HTTP_' || isset($this->specialHeaders[$name])) {
66 3
                $headers[$name] = $value;
67 3
            }
68 4
        }
69
70 4
        return $headers;
71
    }
72
}
73