PHP code example of phpstan / phpstan-symfony

1. Go to this page and download the library: Download phpstan/phpstan-symfony library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpstan / phpstan-symfony example snippets


if ($this->has('service')) {
    // ...
}

// tests/console-application.php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;


// tests/console-application.php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Dotenv\Dotenv;

n($kernel);

// tests/console-application.php

use App\Application; // where Application extends Symfony\Component\Console\SingleCommandApplication
use Symfony\Component\Console;


$kernel = new \App\Kernel('phpstan_env', (bool) $_SERVER['APP_DEBUG']);

use Symfony\Component\Messenger\Attribute\AsMessageHandler;

// Product handler that returns Product
#[AsMessageHandler]
class GetProductQueryHandler
{
    public function __invoke(GetProductQuery $query): Product
    {
        return $this->productRepository->get($query->productId);
    }
}

use Symfony\Component\Messenger\HandleTrait;
use Symfony\Component\Messenger\MessageBusInterface;

// Basic query bus implementation
class QueryBus
{
    use HandleTrait;

    public function __construct(MessageBusInterface $messageBus)
    {
        $this->messageBus = $messageBus;
    }

    public function dispatch(object $query): mixed
    {
        return $this->handle($query); // Return type will be inferred in calling code as query result
    }

    // Multiple methods per class example
    public function execute(object $message): mixed
    {
        return $this->handle($message); // Return type will be inferred in calling code as query result
    }
}

// Interface-based configuration example
interface QueryBusInterface
{
    public function dispatch(object $query): mixed; // Return type will be inferred in calling code as query result
}

class QueryBusWithInterface implements QueryBusInterface
{
    use HandleTrait;

    public function __construct(MessageBusInterface $queryBus)
    {
        $this->messageBus = $queryBus;
    }

    public function dispatch(object $query): mixed
    {
        return $this->handle($query);
    }
}

// Examples of use with proper type inference
$query = new GetProductQuery($productId);
$queryBus = new QueryBus($messageBus);
$queryBusWithInterface = new QueryBusWithInterface($messageBus);

$product = $queryBus->dispatch($query); // Returns: Product
$product2 = $queryBus->execute($query); // Returns: Product
$product3 = $queryBusWithInterface->dispatch($query); // Returns: Product
// Without the feature all above query bus results would be default 'mixed'.