Completed
Pull Request — master (#616)
by Kévin
03:17
created

IriHelper   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 56
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parseIri() 0 17 3
A createIri() 0 17 3
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ApiPlatform\Core\Util;
13
14
use ApiPlatform\Core\Exception\InvalidArgumentException;
15
16
/**
17
 * Parses and creates IRIs.
18
 *
19
 * @author Kévin Dunglas <[email protected]>
20
 *
21
 * @internal
22
 */
23
abstract class IriHelper
24
{
25
    /**
26
     * Parses and standardizes the request IRI.
27
     *
28
     * @param string $iri
29
     * @param string $pageParameterName
30
     *
31
     * @return array
32
     */
33
    public static function parseIri(string $iri, string $pageParameterName) : array
34
    {
35
        $parts = parse_url($iri);
36
        if (false === $parts) {
37
            throw new InvalidArgumentException(sprintf('The request URI "%s" is malformed.', $iri));
38
        }
39
40
        $parameters = [];
41
        if (isset($parts['query'])) {
42
            $parameters = RequestParser::parseRequestParams($parts['query']);
43
44
            // Remove existing page parameter
45
            unset($parameters[$pageParameterName]);
46
        }
47
48
        return ['parts' => $parts, 'parameters' => $parameters];
49
    }
50
51
    /**
52
     * Gets a collection IRI for the given parameters.
53
     *
54
     * @param array  $parts
55
     * @param array  $parameters
56
     * @param string $pageParameterName
57
     * @param float  $page
58
     *
59
     * @return string
60
     */
61
    public static function createIri(array $parts, array $parameters, string $pageParameterName, float $page = null) : string
62
    {
63
        if (null !== $page) {
64
            $parameters[$pageParameterName] = $page;
65
        }
66
67
        $query = http_build_query($parameters, '', '&', PHP_QUERY_RFC3986);
68
        $parts['query'] = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $query);
69
70
        $url = $parts['path'];
71
72
        if ('' !== $parts['query']) {
73
            $url .= '?'.$parts['query'];
74
        }
75
76
        return $url;
77
    }
78
}
79