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
|
|
|
* |
16
|
|
|
* @return mixed|string |
17
|
|
|
*/ |
18
|
4 |
|
public static function replace($uri, $parameters = []) |
19
|
|
|
{ |
20
|
4 |
|
$parameters = (array) $parameters; |
21
|
|
|
|
22
|
4 |
|
$uri = static::replaceRouteParameters($uri, $parameters); |
|
|
|
|
23
|
4 |
|
$uri = str_replace('//', '/', $uri); |
24
|
|
|
|
25
|
4 |
|
return $uri; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Replace all of the wildcard parameters for a route path. |
30
|
|
|
* |
31
|
|
|
* @note: taken from the Illuminate\Routing\UrlGenerator code |
32
|
|
|
* |
33
|
|
|
* @param string $path |
34
|
|
|
* @param array $parameters |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
4 |
|
private static function replaceRouteParameters($path, array $parameters) |
39
|
|
|
{ |
40
|
4 |
|
$path = static::replaceNamedParameters($path, $parameters); |
|
|
|
|
41
|
|
|
|
42
|
4 |
|
$path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) { |
43
|
3 |
|
return (empty($parameters) && !Str::endsWith($match[0], '?}')) |
44
|
1 |
|
? $match[0] |
45
|
3 |
|
: array_shift($parameters); |
46
|
4 |
|
}, $path); |
47
|
|
|
|
48
|
4 |
|
return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Replace all of the named parameters in the path. |
53
|
|
|
* |
54
|
|
|
* @note: taken from the Illuminate\Routing\UrlGenerator code |
55
|
|
|
* |
56
|
|
|
* @param string $path |
57
|
|
|
* @param array $parameters |
58
|
|
|
* |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
|
|
private static function replaceNamedParameters($path, &$parameters) |
62
|
|
|
{ |
63
|
4 |
|
return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) { |
64
|
4 |
|
return isset($parameters[$m[1]]) ? Arr::pull($parameters, $m[1]) : $m[0]; |
65
|
4 |
|
}, $path); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
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
SomeClass
to useself
instead: