Asset Versioning: Complete Artisan Command

1<?php
2
3namespace App\Console\Commands;
4
5use App\Utilities\Str;
6use Illuminate\Console\Command;
7use Illuminate\Console\ConfirmableTrait;
8
9class AssetVersioningCommand extends Command
10{
11 use ConfirmableTrait;
12
13 /**
14 * The name and signature of the console command.
15 *
16 * @var string
17 */
18 protected $signature = 'assets:version {--force : Force the operation to run when in production}';
19
20 /**
21 * The console command description.
22 *
23 * @var string
24 */
25 protected $description = 'Generate an asset version identifier';
26
27 /**
28 * Execute the console command.
29 *
30 * @return int
31 */
32 public function handle()
33 {
34 $key = $this->generateRandomKey();
35
36 if (! $this->setKeyInEnvironmentFile($key)) {
37 return;
38 }
39
40 $this->info('Asset version key set successfully.');
41 }
42
43 /**
44 * Generate a random string for our version key.
45 *
46 * @return string
47 */
48 protected function generateRandomKey(): string
49 {
50 return Str::random(16);
51 }
52
53 /**
54 * Set the asset version key in the environment file.
55 *
56 * @see \Illuminate\Foundation\Console\KeyGenerateCommand::setKeyInEnvironmentFile()
57 * @param string $key
58 * @return bool
59 */
60 protected function setKeyInEnvironmentFile($key)
61 {
62 $currentKey = $this->laravel['config']['assets.key'];
63
64 if (strlen($currentKey) !== 0 && (! $this->confirmToProceed())) {
65 return false;
66 }
67
68 $this->writeNewEnvironmentFileWith($key);
69
70 return true;
71 }
72
73 /**
74 * Write a new environment file with the given key.
75 *
76 * @see \Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith()
77 * @param string $key
78 * @return void
79 */
80 protected function writeNewEnvironmentFileWith($key)
81 {
82 file_put_contents($this->laravel->environmentFilePath(), preg_replace(
83 $this->keyReplacementPattern(),
84 'ASSETS_VERSION='.$key,
85 file_get_contents($this->laravel->environmentFilePath())
86 ));
87 }
88
89 /**
90 * Get a regex pattern that will match env ASSETS_VERSION with any random key.
91 *
92 * @see \Illuminate\Foundation\Console\KeyGenerateCommand::keyReplacementPattern()
93 * @return string
94 */
95 protected function keyReplacementPattern()
96 {
97 $escaped = preg_quote('='.$this->laravel['config']['assets.version'], '/');
98
99 return "/^ASSETS_VERSION{$escaped}/m";
100 }
101}
102
app/Console/Commands/AssetVersioningCommand.php