Skip to content

Commit

Permalink
feat: Support for loading a component from a route.
Browse files Browse the repository at this point in the history
  • Loading branch information
joserick committed Feb 15, 2024
1 parent 2c54cf4 commit 69844e8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/LaravelLivewireDiscover.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Joserick\LaravelLivewireDiscover;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Livewire\Mechanisms\ComponentRegistry;

class LaravelLivewireDiscover extends ComponentRegistry
Expand Down Expand Up @@ -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;
}
}
9 changes: 9 additions & 0 deletions src/LaravelLivewireDiscoverComponentRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 17 additions & 1 deletion src/LaravelLivewireDiscoverServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Joserick\LaravelLivewireDiscover;

use Livewire\Component;
use Livewire\LivewireManager;
use Livewire\Mechanisms\ComponentRegistry;
use Spatie\LaravelPackageTools\Package;
Expand Down Expand Up @@ -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());
}
});
}
}

0 comments on commit 69844e8

Please sign in to comment.