RouteCacheCommand.php
2.6 KB
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
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\RouteCollection;
class RouteCacheCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'route:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a route cache file for faster route registration';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new route command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->call('route:clear');
$routes = $this->getFreshApplicationRoutes();
if (count($routes) === 0) {
return $this->error("Your application doesn't have any routes.");
}
foreach ($routes as $route) {
$route->prepareForSerialization();
}
$this->files->put(
$this->laravel->getCachedRoutesPath(), $this->buildRouteCacheFile($routes)
);
$this->info('Routes cached successfully!');
}
/**
* Boot a fresh copy of the application and get the routes.
*
* @return \Illuminate\Routing\RouteCollection
*/
protected function getFreshApplicationRoutes()
{
return tap($this->getFreshApplication()['router']->getRoutes(), function ($routes) {
$routes->refreshNameLookups();
$routes->refreshActionLookups();
});
}
/**
* Get a fresh application instance.
*
* @return \Illuminate\Contracts\Foundation\Application
*/
protected function getFreshApplication()
{
return tap(require $this->laravel->bootstrapPath().'/app.php', function ($app) {
$app->make(ConsoleKernelContract::class)->bootstrap();
});
}
/**
* Build the route cache file.
*
* @param \Illuminate\Routing\RouteCollection $routes
* @return string
*/
protected function buildRouteCacheFile(RouteCollection $routes)
{
$stub = $this->files->get(__DIR__.'/stubs/routes.stub');
return str_replace('{{routes}}', var_export($routes->compile(), true), $stub);
}
}