Request::createHostHeader()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 3
rs 10
1
<?php
2
3
namespace kalanis\RemoteRequestPsr\Content;
4
5
6
use kalanis\RemoteRequestPsr\Traits\TBody;
7
use kalanis\RemoteRequestPsr\Traits\THeaders;
8
use kalanis\RemoteRequestPsr\Traits\TProtocol;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\UriInterface;
11
use RuntimeException;
12
13
14
/**
15
 * Class Request
16
 * @package kalanis\RemoteRequestPsr\Content
17
 * Note: Contrary the PSR requirements this class does not offer immutability
18
 * That's because you need to change request properties before you set them to RemoteRequest
19
 */
20
class Request implements RequestInterface
21
{
22
    use THeaders;
23
    use TBody;
24
    use TProtocol;
25
26
    protected string $target = '';
27
    protected string $method = 'GET';
28
    protected ?UriInterface $uri = null;
29
30 4
    public function getRequestTarget(): string
31
    {
32 4
        return $this->target;
33
    }
34
35 1
    public function withRequestTarget(string $requestTarget): RequestInterface
36
    {
37 1
        $this->target = $requestTarget;
38 1
        return $this;
39
    }
40
41 4
    public function getMethod(): string
42
    {
43 4
        return $this->method;
44
    }
45
46 1
    public function withMethod(string $method): RequestInterface
47
    {
48 1
        $this->method = $method;
49 1
        return $this;
50
    }
51
52 5
    public function getUri(): UriInterface
53
    {
54 5
        if (is_null($this->uri)) {
55 1
            throw new RuntimeException('You must set URI first!');
56
        }
57 4
        return $this->uri;
58
    }
59
60 4
    public function withUri(UriInterface $uri, bool $preserveHost = false): RequestInterface
61
    {
62 4
        $this->uri = $uri;
63 4
        $this->withHeader('Host', $this->createHostHeader($uri));
64 4
        return $this;
65
    }
66
67 4
    protected function createHostHeader(UriInterface $uri): string
68
    {
69 4
        $port = $uri->getPort();
70 4
        return $uri->getHost()
71 4
            . (empty($port) || (80 == $port) ? '' : ':' . $port);
72
    }
73
}
74