Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\UrlPresenter;
- use Illuminate\Support\Facades\Route;
- use Illuminate\Support\Str;
- use Symfony\Component\Routing\Exception\RouteNotFoundException;
- /**
- * Trait EloquentUrlPresenter
- * @package App\UrlPresenter
- */
- trait EloquentUrlPresenter
- {
- /**
- * @return mixed
- */
- public function getRouteAttribute()
- {
- $routePrefix = $this->routePrefix ?? Str::plural(strtolower(class_basename($this)));
- $defaults = [
- 'index' => [$routePrefix . '.index'],
- 'create' => [$routePrefix . '.create'],
- 'store' => [$routePrefix . '.store'],
- 'show' => [$routePrefix . '.show', 'id'],
- 'edit' => [$routePrefix . '.edit', 'id'],
- 'update' => [$routePrefix . '.update', 'id'],
- 'destroy' => [$routePrefix . '.destroy', 'id']
- ];
- $routes = array_merge($defaults, $this->routes ?? []);
- $routes = collect($routes)
- ->filter()
- ->map(function ($routeParams) {
- $routeName = array_shift($routeParams);
- $routeParams = collect($routeParams)
- ->map(function ($data, $routeParam) use ($routeName) {
- $key = explode('->', $data);
- if (count($key) === 1) {
- $routeParamValue = $this->{$key[0]};
- return empty($routeParamValue) ? $data : $routeParamValue;
- }
- return collect($key)
- ->reduce(function ($model, $field) {
- return $model->$field;
- }, $this);
- })
- ->toArray();
- return Route::has($routeName) ? route($routeName, $routeParams) : null;
- })
- ->filter()
- ->toArray();
- return $this->prepareResponse($routes, $routePrefix);
- }
- /**
- * @param array $routes
- * @param string $routePrefix
- *
- * @return mixed
- */
- private function prepareResponse(array $routes, string $routePrefix)
- {
- return new Class($routes, $routePrefix)
- {
- private $routes;
- private $routePrefix;
- public function __construct($routes, $routePrefix)
- {
- $this->routes = (object)$routes;
- $this->routePrefix = $routePrefix;
- }
- /**
- * @param $key
- *
- * @return string
- */
- public function __get($key)
- {
- $route = $this->routes->$key ?? '';
- if (!$route) {
- throw new RouteNotFoundException(sprintf('[%s.%s] route not found', $this->routePrefix, $key));
- }
- return $route;
- }
- /**
- * @param string $name
- * @param array $arguments
- *
- * @return mixed
- */
- public function __call(string $name, array $arguments)
- {
- if (isset($this->routes->{$name})) {
- $routeName = sprintf('%s.%s', $this->routePrefix, $name);
- $this->routes->{$name} = Route::has($routeName) ? route($routeName, collect($arguments)->flatten()->toArray()) : null;
- return $this->routes->{$name};
- } else {
- throw new RouteNotFoundException(sprintf('[%s.%s] route not found', $this->routePrefix, $name));
- }
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement