From 72a9bded5e63d44254fc829805ea743cc336d5ad Mon Sep 17 00:00:00 2001 From: Josh Cirre Date: Fri, 31 May 2024 12:06:45 -0700 Subject: [PATCH] Make class component if project uses Volt Class components (#106) * Update Make Command, add functional option * change nested ternary to if statement * formatting --------- Co-authored-by: Josh Cirre Co-authored-by: Taylor Otwell --- src/Console/MakeCommand.php | 40 ++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Console/MakeCommand.php b/src/Console/MakeCommand.php index b616300..744b1f3 100644 --- a/src/Console/MakeCommand.php +++ b/src/Console/MakeCommand.php @@ -56,13 +56,50 @@ protected function getPath($name): string */ protected function getStub(): string { - $stubName = $this->option('class') ? 'volt-component-class.stub' : 'volt-component.stub'; + if ($this->option('class')) { + $stubName = 'volt-component-class.stub'; + } elseif ($this->option('functional')) { + $stubName = 'volt-component.stub'; + } elseif ($this->alreadyUsingClasses()) { + $stubName = 'volt-component-class.stub'; + } else { + $stubName = 'volt-component.stub'; + } return file_exists($customPath = $this->laravel->basePath('stubs/'.$stubName)) ? $customPath : __DIR__.'/../../stubs/'.$stubName; } + /** + * Determine if the project is currently using class-based components. + * + * @return bool + */ + protected function alreadyUsingClasses(): bool + { + $paths = Volt::paths(); + + $mountPath = isset($paths[0]) + ? $paths[0]->path + : config('livewire.view_path', resource_path('views/livewire')); + + $files = collect(File::allFiles($mountPath)); + + foreach ($files as $file) { + if ($file->getExtension() === 'php' && str_ends_with($file->getFilename(), '.blade.php')) { + $content = File::get($file->getPathname()); + + if (str_contains($content, 'use Livewire\Volt\Component') || + str_contains($content, 'new class extends Component')) { + return true; + } + } + } + + return false; + } + /** * Create the matching test case if requested. * @@ -173,6 +210,7 @@ protected function getOptions(): array { return [ ['class', null, InputOption::VALUE_NONE, 'Create a class based component'], + ['functional', null, InputOption::VALUE_NONE, 'Create a functional component'], ['force', 'f', InputOption::VALUE_NONE, 'Create the Volt component even if the component already exists'], ]; }