Skip to content

Commit

Permalink
Merge pull request #22 from NokaDesign/no-unsafe-invoke
Browse files Browse the repository at this point in the history
Only invoke methods that call Laravel relationship methods.
  • Loading branch information
Naoray authored Aug 9, 2021
2 parents f6010b0 + 5a79919 commit 708a3c6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/Detectors/RelationMethodDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,15 @@ protected function isRelationMethod(ReflectionMethod $method): bool
return false;
}

$relationObject = $this->model->{$method->getName()}();

return $relationObject instanceof Relation;
// Don't try to invoke the method if it doesn't contains "$this->{relationship method}
if (!$this->methodContentCallsRelationshipMethod($method)) {
return false;
}
try {
$relationObject = $this->model->{$method->getName()}();
return $relationObject instanceof Relation;
} catch (\Throwable $e) {
return false;
}
}
}
20 changes: 20 additions & 0 deletions src/Traits/InteractsWithRelationMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,24 @@ protected function getRelationMethodContent(ReflectionMethod $method)
->before('}')
->trim();
}

protected function methodContentCallsRelationshipMethod(ReflectionMethod $method): bool
{
$content = (string) $this->getRelationMethodContent($method);
$relationshipMethodNames = [
'hasMany',
'hasManyThrough',
'hasOneThrough',
'belongsToMany',
'hasOne',
'belongsTo',
'morphOne',
'morphTo',
'morphMany',
'morphToMany',
'morphedByMany',
];
$regex = '#\$this->('.implode('|', $relationshipMethodNames).')\(#';
return (bool) preg_match($regex, $content);
}
}

0 comments on commit 708a3c6

Please sign in to comment.