Completed
Push — master ( 4d6e43...32bd02 )
by Bohuslav
03:09
created

HeadersFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace Kambo\HttpMessage\Factories\Enviroment\Superglobal;
3
4
// \HttpMessage
5
use Kambo\HttpMessage\Headers;
6
use Kambo\HttpMessage\Enviroment\Enviroment;
7
use Kambo\HttpMessage\Factories\Enviroment\Interfaces\Factory;
8
9
/**
10
 * Create instance of Headers object from instance of Enviroment object
11
 *
12
 * @package Kambo\HttpMessage\Factories\Enviroment\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 Enviroment object
34
     *
35
     * @param Enviroment $enviroment enviroment data
36
     *
37
     * @return Headers Instance of Headers object from enviroment
38
     */
39 4
    public function create(Enviroment $enviroment)
40
    {
41 4
        return new Headers($this->resolveHeaders($enviroment->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 enviroment
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