Skip to content

Commit

Permalink
Auto-discover core models
Browse files Browse the repository at this point in the history
  • Loading branch information
glennjacobs committed Dec 21, 2023
1 parent ef4a4c0 commit 2b449a6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
3 changes: 2 additions & 1 deletion packages/core/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"kalnoy/nestedset": "^6.0",
"doctrine/dbal": "^3.6",
"spatie/laravel-blink": "^1.6",
"lukascivil/treewalker": "0.9.1"
"lukascivil/treewalker": "0.9.1",
"spatie/php-structure-discoverer": "^2.0"
}
}
24 changes: 18 additions & 6 deletions packages/core/src/Base/ModelManifest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,29 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Lunar\Models;
use Lunar\Models\Contracts;
use Spatie\StructureDiscoverer\Discover;

class ModelManifest implements ModelManifestInterface
{
/**
* The collection of models to register to this manifest.
*/
protected array $models = [
Contracts\ProductType::class => Models\ProductType::class,
];
protected array $models = [];

/**
* Bind initial models in container and set explicit model binding.
*/
public function register(): void
{
foreach ($this->models as $interfaceClass => $modelClass) {
// Discover models
$modelClasses = Discover::in(__DIR__ . '/../Models')
->classes()
->extending(BaseModel::class)
->get();

foreach ($modelClasses as $modelClass) {
$interfaceClass = $this->guessContractClass($modelClass);
$this->models[$interfaceClass] = $modelClass;
$this->bindModel($interfaceClass, $modelClass);
}
}
Expand Down Expand Up @@ -82,4 +87,11 @@ protected function bindingName(string $modelClass): string

return Str::camel($shortName);
}

public function guessContractClass(string $modelClass)
{
$shortName = (new \ReflectionClass($modelClass))->getShortName();

return 'Lunar\\Models\\Contracts\\'.$shortName;
}
}

0 comments on commit 2b449a6

Please sign in to comment.