Completed
Pull Request — master (#2)
by René
05:31 queued 03:25
created

Request::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Zortje\MVC\Network;
5
6
use Zortje\MVC\Storage\Cookie\Cookie;
7
8
/**
9
 * Class Request
10
 *
11
 * @package Zortje\MVC\Network
12
 */
13
class Request
14
{
15
16
    /**
17
     * @var string Full URL
18
     */
19
    protected $url;
20
21
    /**
22
     * @var array POST data
23
     */
24
    protected $post;
25
26
    /**
27
     * @var Cookie Cookie
28
     */
29
    protected $cookie;
30
31
    /**
32
     * Request constructor.
33
     *
34
     * @param array  $server
35
     * @param array  $post
36
     * @param Cookie $cookie
37
     */
38
    public function __construct(Cookie $cookie, array $server = [], array $post = [])
39
    {
40
        $this->url    = $this->createUrlFromServerArray($server, !empty($server['HTTPS']));
41
        $this->post   = $post;
42
        $this->cookie = $cookie;
43
    }
44
45
    /**
46
     * Get request URL path
47
     *
48
     * @return string URL path
49
     */
50
    public function getPath(): string
51
    {
52
        $path = parse_url($this->url, PHP_URL_PATH);
53
54
        if (is_string($path) === false) {
55
            $path = '';
56
        }
57
58
        return $path;
59
    }
60
61
    /**
62
     * Get request POST data
63
     *
64
     * @return array POST data
65
     */
66
    public function getPost(): array
67
    {
68
        return $this->post;
69
    }
70
71
    /**
72
     * Get cookie
73
     *
74
     * @return Cookie
75
     */
76
    public function getCookie(): Cookie
77
    {
78
        return $this->cookie;
79
    }
80
81
    /**
82
     * Create URL from _SERVER array
83
     *
84
     * @param array $server _SERVER array
85
     * @param bool  $secure
86
     *
87
     * @return string URL
88
     */
89
    protected function createUrlFromServerArray(array $server, bool $secure = true): string
90
    {
91
        $protocol = $secure ? 'https' : 'http';
92
        $host     = !empty($server['HTTP_HOST']) ? $server['HTTP_HOST'] : 'www.example.com';
93
        $path     = !empty($server['REQUEST_URI']) ? $server['REQUEST_URI'] : '';
94
95
        $url = "$protocol://$host$path";
96
97
        return rtrim($url, '/');
98
    }
99
}
100