UrlResolver::replaceRouteParameters()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 1
nop 2
dl 0
loc 15
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Spatie\ResourceLinks;
4
5
use Illuminate\Routing\Exceptions\UrlGenerationException;
6
use Illuminate\Routing\Route;
7
use Illuminate\Routing\RouteUrlGenerator;
8
use Illuminate\Routing\UrlGenerator;
9
use Illuminate\Support\Str;
10
11
class UrlResolver extends RouteUrlGenerator
12
{
13
    public function __construct(UrlGenerator $urlGenerator)
14
    {
15
        parent::__construct($urlGenerator, $urlGenerator->getRequest());
16
17
        $this->defaults($urlGenerator->getDefaultParameters());
18
    }
19
20
    public function resolve(Route $route, array $parameters): string
21
    {
22
        $parameters = $this->url->formatParameters($parameters);
23
24
        try {
25
            return $this->to($route, $parameters, true);
26
        } catch (UrlGenerationException $exception) {
27
            // Create a URI with missing parameters between brackets
28
            $domain = $this->getRouteDomain($route, $parameters);
29
30
            return $this->addQueryString($this->url->format(
31
                $this->replaceRootParameters($route, $domain, $parameters),
32
                $this->replaceRouteParameters($route->uri(), $parameters),
33
                $route
34
            ), $parameters);
35
        }
36
    }
37
38
    protected function replaceRouteParameters($path, array &$parameters)
39
    {
40
        // We should try to find a solution to not including this function,
41
        // this had to be added to support Laravel 6:
42
        // https://github.com/laravel/framework/issues/29736
43
44
        $path = $this->replaceNamedParameters($path, $parameters);
45
46
        $path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) {
47
            return (empty($parameters) && ! Str::endsWith($match[0], '?}'))
48
                ? $match[0]
49
                : array_shift($parameters);
50
        }, $path);
51
52
        return trim(preg_replace('/\{.*?\?\}/', '', $path), '/');
53
    }
54
}
55