Site icon SEREK DEV

PHPSTAN – cheat sheet

This article contains explanations of common PHP Stan issues or copy & paste ready code snippets.

Generic type for “Collection”

Let’s say we want to create a custom Collection of type T that will be iterable and will contain method getItems. We want to PHP Stan do ensure a provided item is of type T e.g. T = SomeEntity:

Collection.php
<?php

use IteratorAggregate;
use Traversable;

/**
 * @template T
 */
abstract class Collection implements IteratorAggregate
{
    /**
     * @var array<int, T> $items
     */
    private array $items;

    /**
     * @return array<int, T>
     */
    abstract public function getItems(): array;
    
    /**
     * @return Traversable<int, T>
     */
    abstract public function getIterator(): Traversable;
}

Then we can create new Collection like the following:

PHP
$collection = new Collection([new SomeEntity(1), new SomeEntity(2)]);

foreach ($collection as $entity) {
  // $entity - of type SomeEntity
}


foreach ($collection->getItems() as $entity) {
  // $entity - of type SomeEntity
}
PHP

Returning T by class-string

This is common scenario when we want to pass class-string param and return this type T object.

PHP
abstract class IntegrationTestCase extends KernelTestCase
{
    /**
     * @template T
     * @param class-string<T> $name
     * @return T
     */
    public static function getService(string $name)
    {
        return self::getContainer()->get($name);
    }
}
PHP

Limiting string to N values (like ENUM)

Assuming we have a function argument of type string but we want only to accept value1 or value2

PHP
    /**
     * @param 'time'|'notTime'|null $unitTypeKind
     */
    private function validateCommon(?string $unitTypeKind): void
    {
        //
    }
PHP
Exit mobile version