53 lines
1.4 KiB
PHP
53 lines
1.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Core\Commands;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* KeyGenerateCommand
|
||
|
|
* Generate and set APP_KEY in .env
|
||
|
|
*/
|
||
|
|
class KeyGenerateCommand
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Execute the command
|
||
|
|
*/
|
||
|
|
public function execute(bool $showOnly = false): void
|
||
|
|
{
|
||
|
|
$key = bin2hex(random_bytes(32)); // 64 hex chars
|
||
|
|
|
||
|
|
if ($showOnly) {
|
||
|
|
echo $key . "\n";
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
$envPath = __DIR__ . '/../../../.env';
|
||
|
|
$examplePath = __DIR__ . '/../../../env.example';
|
||
|
|
|
||
|
|
// If .env doesn't exist, try to copy from example
|
||
|
|
if (!file_exists($envPath)) {
|
||
|
|
if (file_exists($examplePath)) {
|
||
|
|
copy($examplePath, $envPath);
|
||
|
|
} else {
|
||
|
|
// Create minimal .env
|
||
|
|
file_put_contents($envPath, "APP_NAME=NovaCore Framework\nAPP_ENV=production\nAPP_DEBUG=false\n");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
$content = file_get_contents($envPath) ?: '';
|
||
|
|
|
||
|
|
// Replace or append APP_KEY
|
||
|
|
if (preg_match('/^APP_KEY=.*/m', $content)) {
|
||
|
|
$content = preg_replace('/^APP_KEY=.*/m', 'APP_KEY=' . $key, $content);
|
||
|
|
} else {
|
||
|
|
$content .= (str_ends_with($content, "\n") ? '' : "\n") . 'APP_KEY=' . $key . "\n";
|
||
|
|
}
|
||
|
|
|
||
|
|
// Backup and write
|
||
|
|
@copy($envPath, $envPath . '.bak');
|
||
|
|
file_put_contents($envPath, $content);
|
||
|
|
|
||
|
|
echo "Application key set successfully.\n";
|
||
|
|
echo "APP_KEY=" . $key . "\n";
|
||
|
|
}
|
||
|
|
}
|