UrlManipulator::getParamsAsArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright 2017 Facebook, Inc.
4
 *
5
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
6
 * use, copy, modify, and distribute this software in source code or binary
7
 * form for use in connection with the web services and APIs provided by
8
 * Facebook.
9
 *
10
 * As with any software that integrates with the Facebook platform, your use
11
 * of this software is subject to the Facebook Developer Principles and
12
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
13
 * shall be included in all copies or substantial portions of the software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
 * DEALINGS IN THE SOFTWARE.
22
 */
23
namespace Facebook\Url;
24
25
/**
26
 * @package Facebook
27
 */
28
class UrlManipulator
29
{
30
    /**
31
     * Remove params from a URL.
32
     *
33
     * @param string $url            the URL to filter
34
     * @param array  $paramsToFilter the params to filter from the URL
35
     *
36
     * @return string the URL with the params removed
37
     */
38 110
    public static function removeParamsFromUrl($url, array $paramsToFilter)
39
    {
40 110
        $parts = parse_url($url);
41
42 110
        $query = '';
43 110
        if (isset($parts['query'])) {
44 45
            $params = [];
45 45
            parse_str($parts['query'], $params);
46
47
            // Remove query params
48 45
            foreach ($paramsToFilter as $paramName) {
49 45
                unset($params[$paramName]);
50
            }
51
52 45
            if (count($params) > 0) {
53 43
                $query = '?' . http_build_query($params, null, '&');
54
            }
55
        }
56
57 110
        $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
58 110
        $host = $parts['host'] ?? '';
59 110
        $port = isset($parts['port']) ? ':' . $parts['port'] : '';
60 110
        $path = $parts['path'] ?? '';
61 110
        $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
62
63 110
        return $scheme . $host . $port . $path . $query . $fragment;
64
    }
65
66
    /**
67
     * Gracefully appends params to the URL.
68
     *
69
     * @param string $url       the URL that will receive the params
70
     * @param array  $newParams the params to append to the URL
71
     *
72
     * @return string
73
     */
74 15
    public static function appendParamsToUrl($url, array $newParams = [])
75
    {
76 15
        if (empty($newParams)) {
77 1
            return $url;
78
        }
79
80 15
        if (strpos($url, '?') === false) {
81 12
            return $url . '?' . http_build_query($newParams, null, '&');
82
        }
83
84 4
        list($path, $query) = explode('?', $url, 2);
85 4
        $existingParams = [];
86 4
        parse_str($query, $existingParams);
87
88
        // Favor params from the original URL over $newParams
89 4
        $newParams = array_merge($newParams, $existingParams);
90
91
        // Sort for a predicable order
92 4
        ksort($newParams);
93
94 4
        return $path . '?' . http_build_query($newParams, null, '&');
95
    }
96
97
    /**
98
     * Returns the params from a URL in the form of an array.
99
     *
100
     * @param string $url the URL to parse the params from
101
     *
102
     * @return array
103
     */
104 104
    public static function getParamsAsArray($url)
105
    {
106 104
        $query = parse_url($url, PHP_URL_QUERY);
107 104
        if (!$query) {
108 67
            return [];
109
        }
110 38
        $params = [];
111 38
        parse_str($query, $params);
112
113 38
        return $params;
114
    }
115
116
    /**
117
     * Adds the params of the first URL to the second URL.
118
     *
119
     * Any params that already exist in the second URL will go untouched.
120
     *
121
     * @param string $urlToStealFrom the URL harvest the params from
122
     * @param string $urlToAddTo     the URL that will receive the new params
123
     *
124
     * @return string the $urlToAddTo with any new params from $urlToStealFrom
125
     */
126 4
    public static function mergeUrlParams($urlToStealFrom, $urlToAddTo)
127
    {
128 4
        $newParams = static::getParamsAsArray($urlToStealFrom);
129
        // Nothing new to add, return as-is
130 4
        if (!$newParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $newParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
131 2
            return $urlToAddTo;
132
        }
133
134 2
        return static::appendParamsToUrl($urlToAddTo, $newParams);
135
    }
136
137
    /**
138
     * Check for a "/" prefix and prepend it if not exists.
139
     *
140
     * @param null|string $string
141
     *
142
     * @return string
143
     */
144 23
    public static function forceSlashPrefix($string)
145
    {
146 23
        if (!$string) {
147 17
            return '';
148
        }
149
150 23
        return strpos($string, '/') === 0 ? $string : '/' . $string;
151
    }
152
153
    /**
154
     * Trims off the hostname and Graph version from a URL.
155
     *
156
     * @param string $urlToTrim the URL the needs the surgery
157
     *
158
     * @return string the $urlToTrim with the hostname and Graph version removed
159
     */
160 4
    public static function baseGraphUrlEndpoint($urlToTrim)
161
    {
162 4
        return '/' . preg_replace('/^https:\/\/.+\.facebook\.com(\/v.+?)?\//', '', $urlToTrim);
163
    }
164
}
165