From d5eb19f218a213fd30c75c5a59530fdd9aa023e6 Mon Sep 17 00:00:00 2001 From: Mathieu TUDISCO Date: Wed, 2 Aug 2017 09:32:38 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20a=20service=20which=20find=20?= =?UTF-8?q?automatically=20all=20the=20Has*Relations=20in=20Model.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Helpers/RelationsInModelFinder.php | 65 ++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/Helpers/RelationsInModelFinder.php diff --git a/src/Helpers/RelationsInModelFinder.php b/src/Helpers/RelationsInModelFinder.php new file mode 100644 index 0000000..51f8ceb --- /dev/null +++ b/src/Helpers/RelationsInModelFinder.php @@ -0,0 +1,65 @@ +model = $model; + $this->relationsType = $relationsType; + } + + public static function children(Model $model) + { + return (new static($model, ['hasMany', 'hasManyThrough', 'hasOne']))->find(); + } + + protected function find() + { + return collect(get_class_methods($this->model))->sort() + ->reject(function ($method) { + $this->isAnEloquentMethod($method); + })->filter(function ($method) { + $code = $this->getMethodCode($method); + collect($this->relationsType)->contains(function ($relation) use ($code) { + return Str::contains($code, '$this->' . $relation . '('); + }); + }); + } + + protected function isAnEloquentMethod($method): bool + { + return Str::startsWith($method, 'get') || + Str::startsWith($method, 'set') || + Str::startsWith($method, 'scope') || + method_exists(Model::class, $method); + } + + protected function getMethodCode($method): string + { + $reflection = new \ReflectionMethod($this->model, $method); + + $file = new \SplFileObject($reflection->getFileName()); + $file->seek($reflection->getStartLine() - 1); + + $code = ''; + while ($file->key() < $reflection->getEndLine()) { + $code .= $file->current(); + $file->next(); + } + $code = trim(preg_replace('/\s\s+/', '', $code)); + + return $code; + } + +}