|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Locale\Parsers; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Arr; |
|
6
|
|
|
use Illuminate\Support\Str; |
|
7
|
|
|
|
|
8
|
|
|
class UriParameters |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Replace route parameters. |
|
12
|
|
|
* |
|
13
|
|
|
* @param $uri |
|
14
|
|
|
* @param array $parameters |
|
15
|
|
|
* @return mixed|string |
|
16
|
|
|
*/ |
|
17
|
7 |
|
public static function replace($uri, $parameters = []) |
|
18
|
|
|
{ |
|
19
|
7 |
|
$parameters = (array) $parameters; |
|
20
|
|
|
|
|
21
|
7 |
|
$uri = static::replaceRouteParameters($uri, $parameters); |
|
|
|
|
|
|
22
|
7 |
|
$uri = str_replace('//', '/', $uri); |
|
23
|
|
|
|
|
24
|
7 |
|
return $uri; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Replace all of the wildcard parameters for a route path. |
|
29
|
|
|
* |
|
30
|
|
|
* @note: based on the Illuminate\Routing\UrlGenerator code |
|
31
|
|
|
* |
|
32
|
|
|
* @param string $path |
|
33
|
|
|
* @param array $parameters |
|
34
|
|
|
* |
|
35
|
|
|
* @return string |
|
36
|
|
|
*/ |
|
37
|
7 |
|
private static function replaceRouteParameters($path, array $parameters) |
|
38
|
|
|
{ |
|
39
|
7 |
|
$path = static::replaceNamedParameters($path, $parameters); |
|
|
|
|
|
|
40
|
|
|
|
|
41
|
7 |
|
$path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) { |
|
42
|
4 |
|
return (empty($parameters) && !Str::endsWith($match[0], '?}')) |
|
43
|
1 |
|
? $match[0] |
|
44
|
4 |
|
: array_shift($parameters); |
|
45
|
7 |
|
}, $path); |
|
46
|
|
|
|
|
47
|
7 |
|
return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Replace all of the named parameters in the path. |
|
52
|
|
|
* |
|
53
|
|
|
* @note: based on the Illuminate\Routing\UrlGenerator code |
|
54
|
|
|
* |
|
55
|
|
|
* @param string $path |
|
56
|
|
|
* @param array $parameters |
|
57
|
|
|
* |
|
58
|
|
|
* @return string |
|
59
|
|
|
*/ |
|
60
|
|
|
private static function replaceNamedParameters($path, &$parameters) |
|
61
|
|
|
{ |
|
62
|
7 |
|
return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) { |
|
63
|
7 |
|
return isset($parameters[$m[1]]) ? Arr::pull($parameters, $m[1]) : $m[0]; |
|
64
|
7 |
|
}, $path); |
|
65
|
|
|
} |
|
66
|
|
|
} |
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClassto useselfinstead: