diff --git a/README.md b/README.md index 91589cfb..c8e6e432 100644 --- a/README.md +++ b/README.md @@ -314,6 +314,39 @@ App\MyModel::searchRaw([ This query will return raw response. + +## Usage scopes model + +When you have written a series of scope methods for your model and you want to use it in elastic, do it easily by adding a trait class. + +Basic usage example: + +```php +where('has_published', true); + } + +} +``` + ## Console commands Available artisan commands are listed below: diff --git a/src/ScopesModelHandleable.php b/src/ScopesModelHandleable.php new file mode 100644 index 00000000..05fc239d --- /dev/null +++ b/src/ScopesModelHandleable.php @@ -0,0 +1,39 @@ +handleScopeMethods(); + } + + private function handleScopeMethods() + { + $context = $this; + $reflectionClass = new ReflectionClass(self::class); + + if ($reflectionClass->hasProperty('scopesElastic')) { + foreach ($this->scopesElastic as $method) { + if ($reflectionClass->hasMethod($method)) { + $refMethod = $reflectionClass->getMethod($method); + $method = Str::of($method)->replaceFirst('scope', '')->camel()->__toString(); + + Builder::macro($method, function (...$args) use ($context, $refMethod) { + if (Str::is('scope*', $refMethod->getName())) { + $args[] = $this; + $args = array_reverse($args); + + call_user_func_array([$context, $refMethod->getName()], $args); + } + }); + } + } + } + } +}