phplaravelidephpstorm

How to let PhpStorm know that the first occurrence of a variable in Blade template is defined and comes from View Composer?


I have a sidebar.blade.php where I display various things, pulled from DB.

@php
    $syncLogsCountPending = $sidebarCounters['sync_logs']['pending'];
    $syncLogsCountCompleted = $sidebarCounters['sync_logs']['completed'];
@endphp

<nav id="sidebar" class="col-md-3 col-lg-2">
   cut
</nav>

My IDE highlights $sidebarCounters in red as it thinks that the variable is undefined.

enter image description here

I kind of understand the behavior as this is the very first occurrence of this variable in the template, but obviously the variable does exist, but comes from:

<?php

namespace App\Http\Composers\Backend;

use App\Repositories\Sync\SyncLogRepository;
use Illuminate\View\View;

class SidebarComposer
{
    public function __construct(
        private readonly SyncLogRepository $syncLogRepository
    ) {}

    public function compose(View $view): void
    {
        $view->with('sidebarCounters', $this->getSidebarCounters()); // <---- 👋
    }

    private function getSidebarCounters(): array
    {
        return [
            'sync_logs' => [
                'pending' => 0,
                'completed' => $this->syncLogRepository->getFinishedCount(),
            ],
        ];
    }
}

How can I make me IDE smarter? Any annotation I can add within @php and @endphp tags?


Solution

  • You can use array shape docblock to achieve what you want:

    @php
        /** @var array{sync_logs: array{pending: int, completed: int}} $sidebarCounters */
    
        $syncLogsCountPending = $sidebarCounters['sync_logs']['pending'];
        $syncLogsCountCompleted = $sidebarCounters['sync_logs']['completed'];
    @endphp
    
    <nav id="sidebar" class="col-md-3 col-lg-2">
       cut
    </nav>