Skip to content

Commit

Permalink
Replace ReflectionParameter::getClass for php 8
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexVanderbist committed Nov 26, 2020
1 parent 1278d04 commit 41bbacc
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions src/Filters/FiltersScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
use ReflectionParameter;
use ReflectionUnionType;
use Spatie\QueryBuilder\Exceptions\InvalidFilterValue;

class FiltersScope implements Filter
Expand All @@ -24,7 +27,10 @@ public function __invoke(Builder $query, $values, string $property): Builder
$relation = $propertyParts->implode('.');

if ($relation) {
return $query->whereHas($relation, function (Builder $query) use ($scope, $values) {
return $query->whereHas($relation, function (Builder $query) use (
$scope,
$values
) {
return $query->$scope(...$values);
});
}
Expand All @@ -36,18 +42,18 @@ protected function resolveParameters(Builder $query, $values, string $scope): ar
{
try {
$parameters = (new ReflectionObject($query->getModel()))
->getMethod('scope'.ucfirst($scope))
->getMethod('scope' . ucfirst($scope))
->getParameters();
} catch (ReflectionException $e) {
return $values;
}

foreach ($parameters as $parameter) {
if (! optional($parameter->getClass())->isSubclassOf(Model::class)) {
if (!optional($this->getClass($parameter))->isSubclassOf(Model::class)) {
continue;
}

$model = $parameter->getClass()->newInstance();
$model = $this->getClass($parameter)->newInstance();
$index = $parameter->getPosition() - 1;
$value = $values[$index];

Expand All @@ -62,4 +68,31 @@ protected function resolveParameters(Builder $query, $values, string $scope): ar

return $values;
}

protected function getClass(ReflectionParameter $parameter): ?ReflectionClass
{
if (version_compare(PHP_VERSION, '8.0', '<')) {
return $parameter->getClass();
}

$type = $parameter->getType();

if (is_null($type)) {
return null;
}

if ($type instanceof ReflectionUnionType) {
return null;
}

if ($type->isBuiltin()) {
return null;
}

if ($type->getName() === 'self') {
return $parameter->getDeclaringClass();
}

return new ReflectionClass($type->getName());
}
}

0 comments on commit 41bbacc

Please sign in to comment.