Laravel AT Protocol Client (alpha & unstable)
at main 3.2 kB view raw
1<?php 2 3namespace SocialDept\AtpClient\Console; 4 5use Illuminate\Console\Command; 6use Illuminate\Filesystem\Filesystem; 7use Illuminate\Support\Str; 8 9class MakeAtpClientCommand extends Command 10{ 11 protected $signature = 'make:atp-client 12 {name : The name of the client class} 13 {--force : Overwrite existing file}'; 14 15 protected $description = 'Create a new ATP domain client extension'; 16 17 public function __construct(protected Filesystem $files) 18 { 19 parent::__construct(); 20 } 21 22 public function handle(): int 23 { 24 $name = $this->argument('name'); 25 26 if (! Str::endsWith($name, 'Client')) { 27 $name .= 'Client'; 28 } 29 30 $path = $this->getPath($name); 31 32 if ($this->files->exists($path) && ! $this->option('force')) { 33 $this->components->error("Client [{$name}] already exists!"); 34 35 return self::FAILURE; 36 } 37 38 $this->makeDirectory($path); 39 40 $content = $this->populateStub($this->getStub(), $name); 41 42 $this->files->put($path, $content); 43 44 $this->components->info("Client [{$path}] created successfully."); 45 46 $this->outputRegistrationHint($name); 47 48 return self::SUCCESS; 49 } 50 51 protected function getPath(string $name): string 52 { 53 $basePath = config('client.generators.client_path', 'app/Services/Clients'); 54 55 return base_path($basePath.'/'.$name.'.php'); 56 } 57 58 protected function makeDirectory(string $path): void 59 { 60 if (! $this->files->isDirectory(dirname($path))) { 61 $this->files->makeDirectory(dirname($path), 0755, true); 62 } 63 } 64 65 protected function getNamespace(): string 66 { 67 $basePath = config('client.generators.client_path', 'app/Services/Clients'); 68 69 return Str::of($basePath) 70 ->replace('/', '\\') 71 ->ucfirst() 72 ->replace('App', 'App') 73 ->toString(); 74 } 75 76 protected function populateStub(string $stub, string $name): string 77 { 78 return str_replace( 79 ['{{ namespace }}', '{{ class }}'], 80 [$this->getNamespace(), $name], 81 $stub 82 ); 83 } 84 85 protected function outputRegistrationHint(string $name): void 86 { 87 $this->newLine(); 88 $this->components->info('Register the extension in your AppServiceProvider:'); 89 $this->newLine(); 90 91 $namespace = $this->getNamespace(); 92 $extensionName = Str::of($name)->before('Client')->camel()->toString(); 93 94 $this->line("use {$namespace}\\{$name};"); 95 $this->line("use SocialDept\\AtpClient\\AtpClient;"); 96 $this->newLine(); 97 $this->line("// In boot() method:"); 98 $this->line("AtpClient::extend('{$extensionName}', fn(AtpClient \$atp) => new {$name}(\$atp));"); 99 } 100 101 protected function getStub(): string 102 { 103 return <<<'STUB' 104<?php 105 106namespace {{ namespace }}; 107 108use SocialDept\AtpClient\AtpClient; 109 110class {{ class }} 111{ 112 protected AtpClient $atp; 113 114 public function __construct(AtpClient $parent) 115 { 116 $this->atp = $parent; 117 } 118 119 // 120} 121STUB; 122 } 123}