From 5a79919b073afec7940d8f9d75a1eb6e30466a2f Mon Sep 17 00:00:00 2001 From: Morten Scheel Date: Mon, 9 Aug 2021 12:44:53 +0200 Subject: [PATCH] Only invoke methods that call Laravel relationship methods. --- src/Detectors/RelationMethodDetector.php | 13 ++++++++++--- src/Traits/InteractsWithRelationMethods.php | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/Detectors/RelationMethodDetector.php b/src/Detectors/RelationMethodDetector.php index 9c00e8a..c6ce398 100644 --- a/src/Detectors/RelationMethodDetector.php +++ b/src/Detectors/RelationMethodDetector.php @@ -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; + } } } diff --git a/src/Traits/InteractsWithRelationMethods.php b/src/Traits/InteractsWithRelationMethods.php index 9d68ad1..2667990 100644 --- a/src/Traits/InteractsWithRelationMethods.php +++ b/src/Traits/InteractsWithRelationMethods.php @@ -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); + } }