Back to Course |
Larastan: Catch Bugs with Static Analysis

Example 3: Correct Data to Functions

Have you ever encountered an issue where you accidentally passed the wrong data to your function?

This can happen not only with arrays but with any other data. And Larastan is here to help you catch those cases:

For this example we'll run it on level 5:

includes:
- ./vendor/nunomaduro/larastan/extension.neon
 
parameters:
paths:
- app/
# Level 9 is the highest level
level: 5

After running ./vendor/bin/phpstan analyze we'll see an error too:

------ ------------------------------------------------------------------------------------------------------------------------------
Line Http/Controllers/Admin/ClientReportController.php
------ ------------------------------------------------------------------------------------------------------------------------------
18 Parameter #1 $request of method App\Services\ClientReportsService::getReport() expects Illuminate\Http\Request, array given.
------ ------------------------------------------------------------------------------------------------------------------------------

The fix is quite simple, and we can actually see from the error message that our function expects the Illuminate\Http\Request class, but we've passed an array in our Http/Controllers/Admin/ClientReportController.php.

Let's fit it by looking at where we are calling the service and adjusting the call parameters.

app/Http/Controllers/Admin/ClientReportController.php

use App\Services\ClientReportsService;
use Illuminate\Http\Request;
 
// ...
 
public function __construct(private readonly ClientReportsService $clientReportsService)
{
}
 
public function report(Request $request){
 
$entries = $this->clientReportsService->getReport(['project' => 1]);
 
// Change to:
 
$entries = $this->clientReportsService->getReport($request);
 
// ...
}

Now when we run ./vendor/bin/phpstan analyze we'll see that the error is gone:

[OK] No errors

While this is not a difficult fix - it is actually great to have this kind of check-in place. Especially if you integrate Larastan into your editor - you'll instantly get even more feedback on your code.