TomasVotruba / bladestan

PHPStan analysis for Blade templates
https://tomasvotruba.com/blog/introducing-bladestan-phpstan-analysis-of-blade-templates/
MIT License
280 stars 13 forks source link

View composer data not recognized ("might not be defined" warning) #100

Open johnbacon opened 1 month ago

johnbacon commented 1 month ago

When using a view composer to bind data to a view each time it is rendered, the data being passed to the view is not recognized by Bladestan. A "might not be defined" warning occurs as a result.

Here's a basic example of the issue:

app/View/Composers/ProfileComposer.php:

<?php

namespace App\View\Composers;

use Illuminate\View\View;

class ProfileComposer
{
    public function compose(View $view): void
    {
       $data['example'] = 'Example data';

       $view->with('data', $data);
    }

app/Providers/ViewServiceProvider.php:

<?php

namespace App\Providers;

use App\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    public function register(): void
    {
    }

    public function boot(): void
    {
        View::composer('profile.show', ProfileComposer::class);
    }
}

app/Http/Controllers/ProfileController.php:

<?php

namespace App\Http\Controllers;

use App\Models\Profile;
use Illuminate\Routing\Controller;
use Illuminate\View\View;

class ProfileController extends Controller
{
    public function show(Profile $profile): View
    {
        return view('profile.show', ['profile' => $profile]); // "Variable $data might not be defined." error here without `--error-format=blade`
    }

resources/views/profile/show.blade.php:

<x-app-layout>
    @dump($profile)
    @dump('data: ', $data) {{-- "Variable $data might not be defined." error here with `--error-format=blade` --}}
</x-app-layout>