Skip to content

Commit

Permalink
Improve IDE helper model hook
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir committed Dec 19, 2023
1 parent 08575b7 commit 0643033
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/IdeHelper/DeepRelationsHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str;
use ReflectionClass;
use ReflectionMethod;
Expand All @@ -27,42 +28,41 @@ public function run(ModelsCommand $command, Model $model): void
$methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC);

foreach ($methods as $method) {
if ($method->isStatic() || $method->getNumberOfParameters() > 0) {
if ($method->isAbstract() || $method->isStatic() || !$method->isPublic()
|| $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) {
continue;
}

try {
$relation = $method->invoke($model);
$relationship = $method->invoke($model);
} catch (Throwable) {
continue;
}

if (!$relation instanceof HasManyDeep) {
continue;
if ($relationship instanceof HasManyDeep) {
$this->addRelationship($command, $method, $relationship);
}

$this->addRelation($command, $method, $relation);
}
}

protected function addRelation(ModelsCommand $command, ReflectionMethod $method, HasManyDeep $relation): void
protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void
{
$isHasOneDeep = $relation instanceof HasOneDeep;
$manyRelation = !$relationship instanceof HasOneDeep;

$type = $isHasOneDeep
? '\\' . $relation->getRelated()::class
: '\\' . Collection::class . '|\\' . $relation->getRelated()::class . '[]';
$type = $manyRelation
? '\\' . Collection::class . '|\\' . $relationship->getRelated()::class . '[]'
: '\\' . $relationship->getRelated()::class;

$command->setProperty(
$method->getName(),
$type,
true,
false,
'',
$isHasOneDeep
!$manyRelation
);

if (!$isHasOneDeep) {
if ($manyRelation) {
$command->setProperty(
Str::snake($method->getName()) . '_count',
'int',
Expand Down

0 comments on commit 0643033

Please sign in to comment.