Completed
Pull Request — master (#124)
by ignace nyamagana
02:23
created

UrlBuilder::buildUrl()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 2
Bugs 2 Features 1
Metric Value
c 2
b 2
f 1
dl 0
loc 24
ccs 16
cts 16
cp 1
rs 8.5126
cc 5
eloc 13
nc 10
nop 2
crap 5
1
<?php
2
3
namespace League\Glide\Urls;
4
5
use InvalidArgumentException;
6
use League\Glide\Signatures\SignatureInterface;
7
use League\Uri\Schemes\Http as HttpUri;
8
use League\Uri\Modifiers\AppendSegment;
9
use League\Uri\Modifiers\AddLeadingSlash;
10
use Psr\Http\Message\UriInterface;
11
12
class UrlBuilder
13
{
14
    /**
15
     * The base URI
16
     * @var UriInterface
17
     */
18
    protected $baseUrl;
19
20
    /**
21
     * The HTTP signature used to sign URLs.
22
     * @var SignatureInterface
23
     */
24
    protected $signature;
25
26
    /**
27
     * Create UrlBuilder instance.
28
     * @param string                  $baseUrl   The base URL.
29
     * @param SignatureInterface|null $signature The HTTP signature used to sign URLs.
30
     */
31 30
    public function __construct($baseUrl = '', SignatureInterface $signature = null)
32
    {
33 30
        $this->setBaseUrl($baseUrl);
34 27
        $this->setSignature($signature);
35 27
    }
36
37
    /**
38
     * Set the base URL.
39
     * @param string $baseUrl The base URL.
40
     */
41 30
    public function setBaseUrl($baseUrl)
42
    {
43 30
        static $addLeadingSlash;
44 30
        if (!$addLeadingSlash) {
45 3
            $addLeadingSlash = new AddLeadingSlash();
46 2
        }
47
48 30
        $this->baseUrl = $addLeadingSlash->__invoke(HttpUri::createFromString($baseUrl));
49 27
    }
50
51
    /**
52
     * Set the HTTP signature.
53
     * @param SignatureInterface|null $signature The HTTP signature used to sign URLs.
54
     */
55 27
    public function setSignature(SignatureInterface $signature = null)
56
    {
57 27
        $this->signature = $signature;
58 27
    }
59
60
    /**
61
     * Get the URL.
62
     * @param  string $path   The resource path.
63
     * @param  array  $params The manipulation parameters.
64
     * @return string The URL.
65
     */
66 24
    public function getUrl($path, array $params = [])
67
    {
68 24
        $uri = (new AppendSegment($path))->__invoke($this->baseUrl);
69 24
        if ($this->signature) {
70 9
            $params = $this->signature->addSignature($uri->getPath(), $params);
71 6
        }
72
73 24
        return (string) $uri->withQuery(http_build_query($params, '', '&', PHP_QUERY_RFC3986));
74
    }
75
}
76