Passed
Pull Request — master (#888)
by Tobias
01:50
created

UrlManipulator::getParamsAsArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 9.4285
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
 */
24
namespace Facebook\Url;
25
26
/**
27
 *
28
 * @package Facebook
29
 */
30
class UrlManipulator
31
{
32
    /**
33
     * Remove params from a URL.
34
     *
35
     * @param string $url            The URL to filter.
36
     * @param array  $paramsToFilter The params to filter from the URL.
37
     *
38
     * @return string The URL with the params removed.
39
     */
40
    public static function removeParamsFromUrl($url, array $paramsToFilter)
41
    {
42
        $parts = parse_url($url);
43
44
        $query = '';
45
        if (isset($parts['query'])) {
46
            $params = [];
47
            parse_str($parts['query'], $params);
48
49
            // Remove query params
50
            foreach ($paramsToFilter as $paramName) {
51
                unset($params[$paramName]);
52
            }
53
54
            if (count($params) > 0) {
55
                $query = '?' . http_build_query($params, null, '&');
56
            }
57
        }
58
59
        $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
60
        $host = isset($parts['host']) ? $parts['host'] : '';
61
        $port = isset($parts['port']) ? ':' . $parts['port'] : '';
62
        $path = isset($parts['path']) ? $parts['path'] : '';
63
        $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
64
65
        return $scheme . $host . $port . $path . $query . $fragment;
66
    }
67
68
    /**
69
     * Gracefully appends params to the URL.
70
     *
71
     * @param string $url       The URL that will receive the params.
72
     * @param array  $newParams The params to append to the URL.
73
     *
74
     * @return string
75
     */
76
    public static function appendParamsToUrl($url, array $newParams = [])
77
    {
78
        if (empty($newParams)) {
79
            return $url;
80
        }
81
82
        if (strpos($url, '?') === false) {
83
            return $url . '?' . http_build_query($newParams, null, '&');
84
        }
85
86
        list($path, $query) = explode('?', $url, 2);
87
        $existingParams = [];
88
        parse_str($query, $existingParams);
89
90
        // Favor params from the original URL over $newParams
91
        $newParams = array_merge($newParams, $existingParams);
92
93
        // Sort for a predicable order
94
        ksort($newParams);
95
96
        return $path . '?' . http_build_query($newParams, null, '&');
97
    }
98
99
    /**
100
     * Returns the params from a URL in the form of an array.
101
     *
102
     * @param string $url The URL to parse the params from.
103
     *
104
     * @return array
105
     */
106
    public static function getParamsAsArray($url)
107
    {
108
        $query = parse_url($url, PHP_URL_QUERY);
109
        if (!$query) {
110
            return [];
111
        }
112
        $params = [];
113
        parse_str($query, $params);
114
115
        return $params;
116
    }
117
118
    /**
119
     * Adds the params of the first URL to the second URL.
120
     *
121
     * Any params that already exist in the second URL will go untouched.
122
     *
123
     * @param string $urlToStealFrom The URL harvest the params from.
124
     * @param string $urlToAddTo     The URL that will receive the new params.
125
     *
126
     * @return string The $urlToAddTo with any new params from $urlToStealFrom.
127
     */
128
    public static function mergeUrlParams($urlToStealFrom, $urlToAddTo)
129
    {
130
        $newParams = static::getParamsAsArray($urlToStealFrom);
131
        // Nothing new to add, return as-is
132
        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...
133
            return $urlToAddTo;
134
        }
135
136
        return static::appendParamsToUrl($urlToAddTo, $newParams);
137
    }
138
139
    /**
140
     * Check for a "/" prefix and prepend it if not exists.
141
     *
142
     * @param string|null $string
143
     *
144
     * @return string
145
     */
146
    public static function forceSlashPrefix($string)
147
    {
148
        if (!$string) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $string of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
149
            return '';
150
        }
151
152
        return strpos($string, '/') === 0 ? $string : '/' . $string;
153
    }
154
155
    /**
156
     * Trims off the hostname and Graph version from a URL.
157
     *
158
     * @param string $urlToTrim The URL the needs the surgery.
159
     *
160
     * @return string The $urlToTrim with the hostname and Graph version removed.
161
     */
162
    public static function baseGraphUrlEndpoint($urlToTrim)
163
    {
164
        return '/' . preg_replace('/^https:\/\/.+\.facebook\.com(\/v.+?)?\//', '', $urlToTrim);
165
    }
166
}
167