Completed
Push — master ( e8addc...8eae9f )
by Brian
27s queued 11s
created

GenerateJsRoutesCommand   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 69
ccs 14
cts 14
cp 1
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 17 1
1
<?php
2
3
namespace Bmatovu\JsRoutes\Console;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Filesystem\Filesystem;
7
use Illuminate\Routing\Router;
8
use Illuminate\Support\Facades\File;
9
10
/**
11
 * @see https://ideas.hexbridge.com/how-to-use-laravel-routes-in-javascript-4d9c484a0d97
12
 * @see https://medium.com/@jonan.pineda/thank-you-for-this-post-d1d32c991757
13
 */
14
class GenerateJsRoutesCommand extends Command
15
{
16
    /**
17
     * The name and signature of the console command.
18
     *
19
     * @var string
20
     */
21
    protected $signature = 'js-routes:generate
22
                                {--p|path=resources/js/routes.json : Path for JS routes file.}';
23
24
    /**
25
     * The console command description.
26
     *
27
     * @var string
28
     */
29
    protected $description = 'Generate routes for Javascript.
30
    > Run `npm run dev` to update routes cache.';
31
32
    /**
33
     * Application router.
34
     *
35
     * @var \Illuminate\Routing\Router
36
     */
37
    protected $router;
38
39
    /**
40
     * File system.
41
     *
42
     * @var \Illuminate\Filesystem\Filesystem
43
     */
44
    protected $file;
45
46
    /**
47
     * Create a new command instance.
48
     *
49
     * @param \Illuminate\Routing\Router        $router
50
     * @param \Illuminate\Filesystem\Filesystem $file
51
     *
52
     * @return void
53
     */
54 1
    public function __construct(Router $router, Filesystem $file)
55
    {
56 1
        parent::__construct();
57 1
        $this->router = $router;
58 1
        $this->file = $file;
59 1
    }
60
61
    /**
62
     * Execute the console command.
63
     *
64
     * @return mixed
65
     */
66 1
    public function handle()
67
    {
68 1
        $this->line('Generating routes for Javascript.');
69
70 1
        $routes = collect($this->router->getRoutes());
71
72
        $jsRoutes = $routes->reduce(function ($jsRoutes, $route) {
73 1
            $jsRoutes[$route->getName()] = $route->uri;
74
75 1
            return $jsRoutes;
76 1
        }, []);
77
78 1
        $path = $this->option('path');
79
80 1
        $this->file->put($path, json_encode($jsRoutes, JSON_PRETTY_PRINT));
81
82 1
        $this->line("Routes saved to '{$path}'.");
83 1
    }
84
}
85