Skip to content

Commit

Permalink
Force int cast on ModelsLoader count (#2646)
Browse files Browse the repository at this point in the history
When dealing with **legacy databases**  the count for this related model returns a string like `"88"`, not `88`.

```
comments: [Comment] @hasmany(type: PAGINATOR)
```

After upgrading to PHP 8.4 this does not work anymore. And it throws a error 

_"Nuwave\Lighthouse\Execution\ModelsLoader\CountModelsLoader::extractCount(): Return value must be of type int, string returned"_
  • Loading branch information
robsontenorio authored Jan 8, 2025
1 parent 426307f commit cb5b81a
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Execution/ModelsLoader/CountModelsLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Nuwave\Lighthouse\Execution\ModelsLoader;

use GraphQL\Utils\Utils;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -33,8 +34,11 @@ public static function extractCount(Model $model, string $relationName): int
$countAttributeName = Str::snake("{$relationName}_count");

$count = $model->getAttribute($countAttributeName);
assert(is_int($count), 'avoid runtime check in production since the return type validates this anyway');
if (! is_numeric($count)) {
$nonNumericCount = Utils::printSafe($count);
throw new \Exception("Expected numeric count, got: {$nonNumericCount}.");
}

return $count;
return (int) $count;
}
}

0 comments on commit cb5b81a

Please sign in to comment.