|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Commands\Config; |
| 4 | + |
| 5 | +use App\Concerns\DiscoversConfigurationTrait; |
| 6 | +use App\Concerns\ManagesConfigFileTrait; |
| 7 | +use KDuma\PhpCA\ConfigManager\Adapter\AdapterConfigurationFactory; |
| 8 | +use KDuma\PhpCA\ConfigManager\CaConfigurationLoader; |
| 9 | +use LaravelZero\Framework\Commands\Command; |
| 10 | + |
| 11 | +use function Laravel\Prompts\error; |
| 12 | +use function Laravel\Prompts\info; |
| 13 | +use function Laravel\Prompts\select; |
| 14 | +use function Laravel\Prompts\text; |
| 15 | +use function Laravel\Prompts\warning; |
| 16 | + |
| 17 | +class InitCommand extends Command |
| 18 | +{ |
| 19 | + use ManagesConfigFileTrait { |
| 20 | + ManagesConfigFileTrait::validateConfig as traitValidateConfig; |
| 21 | + } |
| 22 | + use DiscoversConfigurationTrait; |
| 23 | + |
| 24 | + protected $signature = 'config:init {--force : Overwrite existing config file}'; |
| 25 | + |
| 26 | + protected $description = 'Create a new configuration file'; |
| 27 | + |
| 28 | + public function __construct() |
| 29 | + { |
| 30 | + parent::__construct(); |
| 31 | + $this->bootDiscoversConfigurationTrait(); |
| 32 | + } |
| 33 | + |
| 34 | + public function handle(): int |
| 35 | + { |
| 36 | + $path = getcwd() . '/' . self::CONFIG_FILE_NAME; |
| 37 | + |
| 38 | + if (file_exists($path) && ! $this->option('force')) { |
| 39 | + error("Configuration file already exists at {$path}. Use --force to overwrite."); |
| 40 | + |
| 41 | + return self::FAILURE; |
| 42 | + } |
| 43 | + |
| 44 | + $adapterFactory = new AdapterConfigurationFactory(); |
| 45 | + $adapterTypes = array_keys($adapterFactory->getAdapterTypes()); |
| 46 | + |
| 47 | + $type = select( |
| 48 | + label: 'Select adapter type', |
| 49 | + options: $adapterTypes, |
| 50 | + default: 'directory', |
| 51 | + ); |
| 52 | + |
| 53 | + $defaultPath = match ($type) { |
| 54 | + 'directory' => './data', |
| 55 | + 'sqlite' => './data.sqlite', |
| 56 | + 'zip' => './data.zip', |
| 57 | + default => './data', |
| 58 | + }; |
| 59 | + |
| 60 | + $adapterPath = text( |
| 61 | + label: 'Adapter path', |
| 62 | + default: $defaultPath, |
| 63 | + required: true, |
| 64 | + ); |
| 65 | + |
| 66 | + $data = [ |
| 67 | + 'adapter' => [ |
| 68 | + 'type' => $type, |
| 69 | + 'path' => $adapterPath, |
| 70 | + ], |
| 71 | + ]; |
| 72 | + |
| 73 | + $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; |
| 74 | + file_put_contents($path, $json); |
| 75 | + |
| 76 | + info("Configuration file created at {$path}"); |
| 77 | + |
| 78 | + try { |
| 79 | + $loader = new CaConfigurationLoader(); |
| 80 | + $loader->load($data, dirname($path)); |
| 81 | + } catch (\Throwable $e) { |
| 82 | + warning("Warning: {$e->getMessage()}"); |
| 83 | + } |
| 84 | + |
| 85 | + return self::SUCCESS; |
| 86 | + } |
| 87 | +} |
0 commit comments