Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
RouteUtils | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
10 | |
100.00% |
1 / 1 |
makeRoute | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
10 |
1 | <?php |
2 | |
3 | namespace San\Crud\Utils; |
4 | |
5 | |
6 | use Illuminate\Support\Facades\Route; |
7 | |
8 | class RouteUtils { |
9 | public static function makeRoute(?string $name, string|array|null $vars, ?string $prefix) { |
10 | //check route exists |
11 | if (Route::has($name)) { |
12 | $args = is_scalar($vars) ? $vars : sprintf("compact(%s)", join(', ', array_map(fn($var) => sprintf("'%s'", $var), (array) $vars)) ?: '[]'); |
13 | return sprintf("route('%s', %s)", $name, $args); |
14 | } else { //fallback code to handle undefined routes to prevent errors |
15 | $parts = explode('.', $name); |
16 | $values = array_values((array) $vars); |
17 | |
18 | $path = [sprintf("'%s'", rtrim("/" . trim($prefix ?: '', '/'), '/'))]; |
19 | |
20 | for ($i = 0; $i < count($parts); $i++) { |
21 | if ($parts[$i] === 'index') continue; |
22 | |
23 | if ($parts[$i] !== 'show') { |
24 | $path[] = sprintf("'%s'", $parts[$i]); |
25 | } |
26 | |
27 | if (!empty($values[$i])) { |
28 | $path[] = is_scalar($vars) ? $values[$i] : sprintf("$%s?->id ?: 0", $values[$i]); |
29 | } |
30 | } |
31 | |
32 | return sprintf("implode('/', [%s])", join(',', $path)); |
33 | } |
34 | } |
35 | } |