ldc-legaulois/app/Lib/Link.php
2024-10-08 11:57:56 +02:00

115 lines
3 KiB
PHP

<?php
namespace App\Lib;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Stringable;
/**
* Can only handle fo routes
*
* @package App\Lib
*/
class Link implements Jsonable, Arrayable, 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
*
* @param string $routeName
* @return boolean
*/
private function hasRouteName(string $routeName): bool
{
/** @var \Illuminate\Routing\Router $router */
$router = app('router');
return (bool)collect($router->getRoutes()->getRoutes())
->filter(fn ($route) => str($route->getName())->startsWith('fo.'))
->filter(fn ($route) => str($route->getName())->exactly($routeName))->count();
}
// * METHODS
/**
* Get the link url
*
* @return string
*/
public function getUrl(): string
{
return $this->url ?? route($this->routeName);
}
/**
* Get the route name if the link is bound to a route
*
* @return null|string
*/
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 integer $options
* @return string
* @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()}'");
}
}