createUriMergeQuery()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 9.6
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
namespace Germania\MergeQueryUriFactory;
3
4
use Psr\Http\Message\UriFactoryInterface;
5
use Psr\Http\Message\UriInterface;
6
7
/**
8
 * This UriFactory decorator builds an UriInterface
9
 * from an URI string or UriInterface and an Query String Parameters array.
10
 *
11
 * The `createUriMergeQuery` method accepts an array with additional query params
12
 * that will be 'merged' into the resulting UriInterface.
13
 */
14
class MergeQueryUriFactoryDecorator implements UriFactoryInterface
15
{
16
17
18
    /**
19
     * @var UriFactoryInterface
20
     */
21
    public $uri_factory;
22
23
24
    /**
25
     * @param UriFactoryInterface $uri_factory
26
     */
27 4
    public function __construct(UriFactoryInterface $uri_factory)
28
    {
29 4
        $this->uri_factory = $uri_factory;
30 4
    }
31
32
33
    /**
34
     * @inheritDoc
35
     */
36 4
    public function createUri(string $uri = '') : UriInterface
37
    {
38 4
        return $this->uri_factory->createUri($uri);
39
    }
40
41
42
43
    /**
44
     * @param  string|UriInterface  $url           URI string or UriInterface
45
     * @param  string[]             $query_params  Overriding query parameters
46
     * @return UriInterface
47
     *
48
     * @throws InvalidArgumentException when no string or UriInterface is passed
49
     */
50 4
    public function __invoke( $url, array $query_params = array() ) : UriInterface
51
    {
52 4
        return $this->createUriMergeQuery( $url, $query_params );
53
    }
54
55
56
    /**
57
     * @param  string|UriInterface  $url           URI string or UriInterface
58
     * @param  string[]             $query_params  Overriding query parameters
59
     * @return UriInterface
60
     *
61
     * @throws InvalidArgumentException when no string or UriInterface is passed
62
     */
63 12
    public function createUriMergeQuery( $url, array $query_params = array() ) : UriInterface
64
    {
65 12
        if (is_string($url)) {
66 2
            $target_uri = $this->createUri($url);
67
        }
68 12
        elseif ($url instanceOf UriInterface) {
69 4
            $target_uri = $url;
70
        }
71
        else {
72 8
            throw new \InvalidArgumentException("Expected UriInterface or string.");
73
        }
74
75
76
        // Merge redirect params into original parameters
77 4
        parse_str($target_uri->getQuery(), $target_params);
78 4
        $merged_params = array_merge($target_params, $query_params);
79
80 4
        $merged_query = http_build_query($merged_params);
81 4
        return $target_uri->withQuery($merged_query);
82
    }
83
}
84