diff --git a/src/LaravelLivewireDiscover.php b/src/LaravelLivewireDiscover.php index 40f19e2..66eb06b 100644 --- a/src/LaravelLivewireDiscover.php +++ b/src/LaravelLivewireDiscover.php @@ -3,6 +3,7 @@ namespace Joserick\LaravelLivewireDiscover; use Illuminate\Support\Collection; +use Illuminate\Support\Str; use Livewire\Mechanisms\ComponentRegistry; class LaravelLivewireDiscover extends ComponentRegistry @@ -43,10 +44,27 @@ public function getClassNamespace() : string /** * Get the collection of class namespaces to discover. * - * @return string + * @return Collection */ public function getClassNamespaces() : Collection { return $this->class_namespaces; } + + /** + * Get the prefix from the class. + * + * @param string $class + * @return string|bool + */ + function getPrefixFromClass(string $class) : string|bool + { + foreach ($this->class_namespaces as $prefix => $namespace) { + if (Str::startsWith($class, $namespace)) { + return $prefix; + } + } + + return false; + } } diff --git a/src/LaravelLivewireDiscoverComponentRegistry.php b/src/LaravelLivewireDiscoverComponentRegistry.php index afe9d20..f45261d 100644 --- a/src/LaravelLivewireDiscoverComponentRegistry.php +++ b/src/LaravelLivewireDiscoverComponentRegistry.php @@ -10,6 +10,15 @@ class LaravelLivewireDiscoverComponentRegistry extends ComponentRegistry { + function new($nameOrClass, $id = null) + { + $component = parent::new($nameOrClass, $id); + + $component->updateNameFromPrefix(); + + return $component; + } + protected function getNameAndClass($nameComponentOrClass) { $name_class = $this->getNameAndClassDiscovered($nameComponentOrClass, diff --git a/src/LaravelLivewireDiscoverServiceProvider.php b/src/LaravelLivewireDiscoverServiceProvider.php index 40379bf..91a16f6 100644 --- a/src/LaravelLivewireDiscoverServiceProvider.php +++ b/src/LaravelLivewireDiscoverServiceProvider.php @@ -2,6 +2,7 @@ namespace Joserick\LaravelLivewireDiscover; +use Livewire\Component; use Livewire\LivewireManager; use Livewire\Mechanisms\ComponentRegistry; use Spatie\LaravelPackageTools\Package; @@ -29,7 +30,22 @@ public function configurePackage(Package $package): void return new LaravelLivewireDiscoverManager(); }); - // Load the Livewire components of xposbox. $this->app->instance(ComponentRegistry::class, new LaravelLivewireDiscoverComponentRegistry()); } + + /** + * Booting the package. + * + * @return void + */ + public function bootingPackage(): void + { + Component::macro('updateNameFromPrefix', function () { + $prefix = app(LaravelLivewireDiscover::class)->getPrefixFromClass(get_class($this)); + + if ($prefix) { + $this->setName($prefix.'-'.str(substr(strrchr(get_class($this), '\\'), 1))->kebab()); + } + }); + } }