MakeRoute.php 11.9 KB
Newer Older
jhon committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
<?php

namespace Acacha\AdminLTETemplateLaravel\Console;

use Acacha\AdminLTETemplateLaravel\Compiler\StubFileCompiler;
use Acacha\AdminLTETemplateLaravel\Console\Routes\Controller;
use Acacha\AdminLTETemplateLaravel\Console\Routes\ControllerResourceRoute;
use Acacha\AdminLTETemplateLaravel\Console\Routes\ControllerRoute;
use Acacha\AdminLTETemplateLaravel\Console\Routes\GeneratesCode;
use Acacha\AdminLTETemplateLaravel\Console\Routes\RegularRoute;
use Acacha\AdminLTETemplateLaravel\Exceptions\RouteTypeNotValid;
use Acacha\AdminLTETemplateLaravel\Exceptions\SpatieMenuDoesNotExists;
use Acacha\AdminLTETemplateLaravel\Filesystem\Filesystem;
use Illuminate\Console\Command;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Artisan;
use Route;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;

/**
 * Class MakeRoute.
 */
class MakeRoute extends Command
{
    use Controller, CreatesModels;

    /**
     * Path to web routes file.
     *
     * @var string
     */
    protected $web_routes_path = 'routes/web.php';

    /**
     * Path to api routes file.
     *
     * @var string
     */
    protected $api_routes_path = 'routes/api.php';

    /**
     * Compiler for stub file.
     *
     * @var StubFileCompiler
     */
    protected $compiler;

    /**
     * Compiler for stub file.
     *
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * @var array
     */
    protected static $lookup = [
        'regular' => RegularRoute::class,
        'controller' => ControllerRoute::class,
        'resource' => ControllerResourceRoute::class,
    ];

    /**
     * The name and signature of the console command.
     */
    protected $signature = 'make:route {link : The route link} {action? : View or controller to create} 
    {--t|type=regular : Type of route to create (regular,controller,resource)} {--m|method=get : HTTP method} 
    {--api : Route is an api route} {--a|createaction : Create view or controller after route}
    {--menu : Create also menu entry using make:menu command} {--model : Create also a model using command make:model}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Insert a route to routes/web.php file';

    /**
     * AdminLTERoute constructor.
     *
     * @param StubFileCompiler $compiler
     * @param Filesystem $filesystem
     */
    public function __construct(StubFileCompiler $compiler, Filesystem $filesystem)
    {
        parent::__construct();
        $this->compiler = $compiler;
        $this->filesystem = $filesystem;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->processInput();
        $this->warnIfRouteAlreadyExists($link = $this->argument('link'));
        $tmpfile = $this->createTmpFileWithRoute();
        $path = $this->getPath($tmpfile);
        add_file_into_file($this->mountpoint(), $path, $dstFile = $this->destinationFile());
        $this->info('Route ' . undot_path($link) . ' added to ' .  $dstFile . '.');
        $this->postActions();
    }

    /**
     * Get mountpoint.
     *
     * @return string
     */
    protected function mountpoint()
    {
        if ($this->option('api')) {
            return '#adminlte_api_routes';
        }
        return '#adminlte_routes';
    }

    /**
     * Destination route file.
     *
     * @return string
     */
    protected function destinationFile()
    {
        if ($this->option('api')) {
            return base_path($this->api_routes_path);
        }
        return base_path($this->web_routes_path);
    }

    /**
     * Warn if route already exists.
     *
     * @param $link
     */
    protected function warnIfRouteAlreadyExists($link)
    {
        if ($this->routeExists($link)) {
            if ($this->confirm('Route already exists. Do you wish to continue?')) {
                return;
            }
            die();
        }
    }

    /**
     * Check if route exists.
     *
     * @param $link
     * @return mixed
     */
    protected function routeExists($link)
    {
        if ($this->option('api')) {
            return $this->apiRouteExists($link);
        }
        return $this->webRouteExists($link);
    }

    /**
     * Check if web route exists.
     *
     * @param $link
     * @return mixed
     */
    protected function webRouteExists($link)
    {
        $link = $this->removeTrailingSlashIfExists($link);
        $link = $this->removeDuplicatedTrailingSlashes($link);
        foreach (Route::getRoutes() as $value) {
            if (in_array(strtoupper($this->option('method')), array_merge($value->getMethods(), ['ANY'])) &&
                $value->getPath() === $link) {
                return true;
            }
        }
        return false;
    }

    /**
     * Remove (if exists) trailing slash from link.
     *
     * @param $link
     * @return string
     */
    protected function removeTrailingSlashIfExists($link)
    {
        if (starts_with($link, '/')) {
            return substr($link, 1);
        }
        return $link;
    }

    /**
     * Remove duplicated trailing slashes.
     *
     * @param $link
     * @return mixed
     */
    protected function removeDuplicatedTrailingSlashes($link)
    {
        return preg_replace('/(\/+)/', '/', $link);
    }

    /**
     * Check if api route exists.
     *
     * @param $link
     * @return mixed
     */
    protected function apiRouteExists($link)
    {
        return $this->webRouteExists('api/v1/' . $link);
    }

    /**
     * Crete tmp file with route to add.
     *
     * @return mixed
     */
    protected function createTmpFileWithRoute()
    {
        $temp = tmpfile();
        fwrite($temp, $this->getRouteCode());
        return $temp;
    }

    /**
     * Get path from file resource.
     *
     * @param $tmpfile
     * @return mixed
     */
    protected function getPath($tmpfile)
    {
        return stream_get_meta_data($tmpfile)['uri'];
    }

    /**
     * Get route code to insert depending on type.
     *
     * @return mixed
     */
    protected function getRouteCode()
    {
        $type = $this->option('type');
        $class = isset(static::$lookup[$type])
            ? static::$lookup[$type]
            : RegularRoute::class;
        /** @var GeneratesCode $route */
        $route = new $class($this->compiler, $this->filesystem);
        $route->setReplacements([
            undot_path($this->argument('link')),
            $this->action(),
            $this->method()
        ]);
        return $route->code();
    }

    /**
     * Get method.
     *
     * @return string
     */
    protected function method()
    {
        if (strtolower($this->option('method')) == 'head') {
            return 'get';
        }
        return strtolower($this->option('method'));
    }

    /**
     * Get the action replacement.
     *
     * @return array|string
     */
    protected function action()
    {
        if ($this->argument('action') != null) {
            return $this->argument('action');
        }
        if (strtolower($this->option('type')) != 'regular') {
            return $this->argument('link') . 'Controller';
        }
        return $this->argument('link');
    }

    /**
     * Process input.
     */
    protected function processInput()
    {
        $this->validateMethod();
        $this->validateType();
    }

    /**
     * Validate option method.
     */
    protected function validateMethod()
    {
        if (! in_array(strtoupper($this->option('method')), $methods = array_merge(Router::$verbs, ['ANY']))) {
            throw new MethodNotAllowedException($methods);
        }
    }

    /**
     * Validate option type.
     */
    protected function validateType()
    {
        if (! in_array(strtolower($this->option('type')), ['regular','controller','resource'])) {
            throw new RouteTypeNotValid();
        }
    }

    /**
     * Execute post actions (if exists)
     */
    protected function postActions()
    {
        if ($this->option('createaction') != null) {
            $this->createAction();
        }
        if ($this->option('menu') != null) {
            $this->createMenu();
        }
        if ($this->option('model') != null) {
            $this->createModel($this->argument('link'));
        }
    }

    /**
     * Create menu.
     */
    protected function createMenu()
    {
        try {
            $this->warnIfSpatieMenuIsNotInstalled();
        } catch (\Exception $e) {
            //Skip installation of menu
            $this->error($e->getMessage());
            return;
        }
        Artisan::call('make:menu', [
            'link' => $link = undot_path($this->argument('link')),
            'name' => ucfirst($link),
        ]);
        $this->info('Menu entry ' . $link .' added to config/menu.php file.');
    }

    /**
     * Warn if spatie menu ins not installed.
     *
     * @throws SpatieMenuDoesNotExists
     */
    protected function warnIfSpatieMenuIsNotInstalled()
    {
        if (!(app()->getProvider('Spatie\Menu\Laravel\MenuServiceProvider'))) {
            throw new SpatieMenuDoesNotExists();
        }
    }

    /**
     * Create action (view|controller).
     */
    protected function createAction()
    {
        if (strtolower($this->option('type')) == 'regular' || $this->option('type') == null) {
            return $this->createView();
        }
        if (strtolower($this->option('type')) == 'controller') {
            return $this->createController();
        }
        return $this->createResourceController();
    }

    /**
     * Create View.
     *
     * @param null $name
     */
    protected function createView($name = null)
    {
        if ($name == null) {
            $name = $this->action();
        }
        Artisan::call('make:view', [
            'name' => $name
        ]);
        $this->info('View ' . undot_path($name) .'.blade.php created.');
    }

    /**
     * Create regular controller.
     */
    protected function createController()
    {
        Artisan::call('make:controller', [
            'name' => $controller = $this->controllerWithoutMethod($this->action())
        ]);
        $this->addMethodToController($controller, $this->controllerMethod($this->action()));
        $this->info('Controller ' . $controller .' created.');
        $this->createView($this->argument('link'));
    }

    /**
     * Create resource controller.
     */
    protected function createResourceController()
    {
        Artisan::call('make:controller', [
            'name' => $controller = $this->controllerWithoutMethod($this->action()),
            '--resource' => true
        ]);
        $this->info('Resource Controller ' . $controller .' created.');
        $this->createView($this->argument('link'));
    }

    /**
     * Add method to controller.
     *
     * @param $controller
     * @param $controllerMethod     *
     */
    protected function addMethodToController($controller, $controllerMethod)
    {
        $tmpfile = $this->createTmpFileWithMethod($controllerMethod);
        $path = $this->getPath($tmpfile);
        add_file_into_file('\/\/', $path, app_path('Http/Controllers/' . $controller . '.php'));
    }

    /**
     * Crete tmp file with route to add.
     *
     * @param $controllerMethod
     * @return mixed
     */
    protected function createTmpFileWithMethod($controllerMethod)
    {
        $temp = tmpfile();
        fwrite($temp, $this->getMethodCode($controllerMethod));
        return $temp;
    }

    /**
     * Get method code.
     *
     * @param $controllerMethod
     * @return mixed
     */
    protected function getMethodCode($controllerMethod)
    {
        return $this->compiler->compile(
            $this->filesystem->get($this->getMethodStubPath()),
            [
                'METHOD' => $controllerMethod,
                'VIEW' => $this->argument('link')
            ]
        );
    }

    /**
     * Get method stub path.
     *
     * @return string
     */
    protected function getMethodStubPath()
    {
        return __DIR__ . '/stubs/method.stub';
    }
}