|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Blueprint\Generators; |
| 4 | + |
| 5 | +use Blueprint\Contracts\Generator; |
| 6 | +use Blueprint\Models\Controller; |
| 7 | +use Illuminate\Support\Str; |
| 8 | + |
| 9 | +class RouteGenerator implements Generator |
| 10 | +{ |
| 11 | + /** @var \Illuminate\Contracts\Filesystem\Filesystem */ |
| 12 | + private $files; |
| 13 | + |
| 14 | + private $resourceMethods = ['index', 'create', 'store', 'edit', 'update', 'show', 'destroy']; |
| 15 | + |
| 16 | + public function __construct($files) |
| 17 | + { |
| 18 | + $this->files = $files; |
| 19 | + } |
| 20 | + |
| 21 | + public function output(array $tree): array |
| 22 | + { |
| 23 | + if (empty($tree['controllers'])) { |
| 24 | + return []; |
| 25 | + } |
| 26 | + |
| 27 | + $routes = ''; |
| 28 | + /** @var \Blueprint\Models\Controller $controller */ |
| 29 | + foreach ($tree['controllers'] as $controller) { |
| 30 | + $routes .= PHP_EOL . PHP_EOL . $this->buildRoutes($controller); |
| 31 | + } |
| 32 | + $routes .= PHP_EOL; |
| 33 | + |
| 34 | + $path = 'routes/web.php'; |
| 35 | + $this->files->append($path, $routes); |
| 36 | + |
| 37 | + return ['updated' => [$path]]; |
| 38 | + } |
| 39 | + |
| 40 | + protected function buildRoutes(Controller $controller) |
| 41 | + { |
| 42 | + $routes = ''; |
| 43 | + $methods = array_keys($controller->methods()); |
| 44 | + |
| 45 | + $className = $controller->className(); |
| 46 | + $slug = Str::kebab($controller->prefix()); |
| 47 | + |
| 48 | + $resource_methods = array_intersect($methods, $this->resourceMethods); |
| 49 | + if (count($resource_methods)) { |
| 50 | + $routes .= sprintf("Route::resource('%s', '%s')", $slug, $className); |
| 51 | + |
| 52 | + $missing_methods = array_diff($this->resourceMethods, $resource_methods); |
| 53 | + if (count($missing_methods)) { |
| 54 | + if (count($missing_methods) < 4) { |
| 55 | + $routes .= sprintf("->except('%s')", implode("', '", $missing_methods)); |
| 56 | + } else { |
| 57 | + $routes .= sprintf("->only('%s')", implode("', '", $resource_methods)); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + $routes .= ';' . PHP_EOL; |
| 63 | + } |
| 64 | + |
| 65 | + $methods = array_diff($methods, $this->resourceMethods); |
| 66 | + foreach ($methods as $method) { |
| 67 | + $routes .= sprintf("Route::get('%s/%s', '%s@%s');", $slug, Str::kebab($method), $className, $method); |
| 68 | + $routes .= PHP_EOL; |
| 69 | + } |
| 70 | + |
| 71 | + return trim($routes); |
| 72 | + } |
| 73 | +} |
0 commit comments