ldc-legaulois/app/Lib/Link.php
2026-09-25 16:25:31 +02:00

125 lines
3.2 KiB
PHP

<?php
namespace App\Lib;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Str;
use Stringable;
/**
* Can only handle fo routes
*/
class Link implements Arrayable, Jsonable, Stringable
{
/**
* Link.
*
* @param null|string $url A valid url.
* @param null|string $routeName A valid route name.
* @return void
*
* @throws \RuntimeException In case parameters are incorrect (Need to provide one only).
*/
public function __construct(protected ?string $url = null, protected ?string $routeName = null)
{
if (! is_null($url) && ! is_null($routeName)) {
throw new \RuntimeException('You have to provide either url string or routeName');
}
if ($routeName !== null and ! self::hasRouteName($routeName)) {
throw new \RuntimeException("Route {$routeName} could not be found into actual front route list");
}
if ($url !== null and validator(['url' => $url], ['url' => 'url'])->fails()) {
throw new \RuntimeException("Url '{$url} is not a valid url");
}
}
/**
* Check has route
*/
private function hasRouteName(string $routeName): bool
{
/** @var \Illuminate\Routing\Router $router */
$router = app('router');
return (bool) collect($router->getRoutes()->getRoutes())
->filter(fn ($route) => Str::of($route->getName())->startsWith('fo.'))
->filter(fn ($route) => Str::of($route->getName())->exactly($routeName))->count();
}
// * METHODS
/**
* Get the link url
*/
public function getUrl(): string
{
$url = $this->url;
if (! is_null($url)) {
return $url;
}
$routeName = $this->getRouteName();
return $routeName ? route($routeName) : route('fo.home.show');
}
/**
* Get the unformatted url.
*/
public function getUnformattedUrl(): ?string
{
return $this->url;
}
/**
* Get the route name if the link is bound to a route
*/
public function getRouteName(): ?string
{
return $this->routeName;
}
// * TRANSFORMERS
/**
* Get the instance as an array.
*
* @return array<'url'|'routeName', string|null>
*/
public function toArray(): array
{
return ['url' => $this->url, 'routeName' => $this->routeName];
}
/**
* Convert the object to its JSON representation.
*
* @param int $options
*
* @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing
*/
public function toJson($options = 0): string
{
// phpcs:enable
return \json_encode($this->toArray(), $options);
}
/**
* @return string
*
* @throws \RuntimeException If the link cannot be converted to string.
*/
public function __toString()
{
if (! is_null($this->url)) {
return $this->url;
}
if (! is_null($this->routeName)) {
return route($this->routeName);
}
throw new \RuntimeException("This link could not be converted to string '{$this->toJson()}'");
}
}