r/PHPhelp • • 23d ago

PHPStan and array of dynamic objects

Hello everybody,

I need your help. Let's say I have a Mapper that receive data from a database. For eg.

class Mapper { ...
    public string $table;
    public string $targetClass;

    public function getArrayOfObjects($conditions) {
        $PDOStatement = $this->Database->select($this->table, $conditions);
        $array = $this->Database->fetchAll(PDO:FETCH_ASSOC);

        $returnArray = array();

        // Now I populate the object property, for eg.
        foreach ($array as $database_row) {
            $object = new $this->targetClass;

            $object->id = $database_row['id'];
            $object->publishedDate = new DateTime($database_row['published_date']);

            ....

            $returnArray[] = $object;
        }

        return $returnArray;
     }
}

class BooksMapper extends Mapper {
    function __construct() {
      $this->table "books";
      $this->targetClass = "\Books";
    }
}

This mapper aims to be a generic one, not only for Books. I know that "publishedDate" is a "book concept" but let's consider that the Mapper reads from a JSON file the structure of the object that it is going to map with database fields.
Now let's say that I use it like that.

$Database = new \Database($someDatabaseConfiguration);
$BooksMapper = new \BooksMapper($Database);
$BookArray = $BooksMapper->getArrayOfObjects(["activeBook" => true]);

foreach ($BookArray as $Book) {
print "Book ID: " . $Book->id;
}

The problem here is that PHPStan seems not to understand that $BookArray is an array of \Book, and so at level 8 it gives me an error on $Book->id.

How can I solve that?

Thank you for your help, and excuse me for my ignorance.

3 Upvotes

5 comments sorted by

5

u/MRSLgthr 23d ago edited 23d ago

Something like this should work:

<?php

class Books
{
    public int $id;
    public \DateTimeInterface $publishedDate;
}

class Helper
{
    /**
     *  @return array<array<string, mixed>>
     */
    public static function getSomeBooks(): array
    {
        return [
            [
                'id' => 1,
                'published_at' => '2026-10-23 11:12:13',
            ],
            [
                'id' => 2,
                'published_at' => '2026-10-23 12:13:14',
            ],
            [
                'id' => 3,
                'published_at' => '2026-10-23 13:14:15',
            ],
        ];
    }
}

/**
 *  @template T
 */
class Mapper
{
    public string $table;

    /**  @class-string<T> */
    public string $targetClass;

    /**
     *  @param array<string, boolean> $conditions
     *  @param array<int, T>
     */
    public function getArrayOfObjects(array $conditions): array
    {
        $array = Helper::getSomeBooks();

        $returnArray = array();

        // Now I populate the object property, for eg.
        foreach ($array as $database_row) {
            $object = new $this->targetClass;

            $object->id = $database_row['id'];
            $object->publishedDate = new DateTime($database_row['published_date']);

            $returnArray[] = $object;
        }

        return $returnArray;
    }
}

/**
 * @extends Mapper<Books>
 */
class BooksMapper extends Mapper
{
    function __construct()
    {
      $this->table = "books";
      $this->targetClass = Books::class;
    }
}

$BooksMapper = new \BooksMapper();
$BookArray = $BooksMapper->getArrayOfObjects(["activeBook" => true]);

foreach ($BookArray as $Book) {
    print "Book ID: " . $Book->id;
}

You probably could do without the mapper and just using the PDO::FETCH_CLASS mode.

1

u/pabaczek 18d ago edited 18d ago

What you're looking for are ORM's and topic called hydration.

<?php

namespace App\Models;

abstract class AbstractModel
{
    /**
     *  @return string
     */
    abstract public static function getDbTableName(): string;

    /**
     * @return array<string, string|int|bool>
     */
    abstract public static function getDbFetchConditions(): array;

    /**
     * @param string $name
     * @return mixed
     */
    public function __get(string $name)
    {
        return $this->$name;
    }

    /**
     * @param string $name
     * @param mixed $value
     * @return void
     */
    public function __set(string $name, mixed $value): void
    {
        $this->$name = $value;
    }
}

class Book extends AbstractModel
{
    public static function getDbTableName(): string
    {
        return 'books';
    }

    public static function getDbFetchConditions(): array
    {
        return [
            'active' => true
        ];
    }
}

final readonly class DatabaseFetcher
{
    public function __construct(/*private PDO $pdo*/)
    {

    }

    /**
     * @param string $tableName
     * @param array<string, string|int|bool> $conditions
     * @return array<array<string, string|int|bool>>
     */
    public function fetchWithConditions(string $tableName, array $conditions): array
    {
        // Here we should use PDO, but for testing sake let's use regular array;
        // but normally return $this->pdo->...->fetchAll();
        return [
            [
                'id' => 1,
                'name' => 'Moby Dick'
            ],
            [
                'id' => 2,
                'name' => 'Human Animal'
            ]
        ];
    }
}

readonly class Mapper
{
    public function __construct(private DatabaseFetcher $databaseFetcher)
    {

    }

    /**
     * @param string $modelClass
     * @return AbstractModel[]
     */
    public function fetch(string $modelClass): array
    {
        assert(is_subclass_of($modelClass, AbstractModel::class));

        $dbResult = $this->databaseFetcher->fetchWithConditions(
            $modelClass::getDbTableName(),
            $modelClass::getDbFetchConditions()
        );

        return array_map(function ($dbRow) use ($modelClass) {
            $object = new $modelClass();

            foreach ($dbRow as $key => $value) {
                $object->$key = $value;
            }

            return $object;

        }, $dbResult);
    }
}

$mapper = new Mapper(new DatabaseFetcher());

$books = $mapper->fetch(Book::class);

var_dump($books);

pbaczek@HPWHITE-PBACZEK:~/mapper$ php index.php 
array(2) {
  [0]=>
  object(App\Models\Book)#6 (2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(9) "Moby Dick"
  }
  [1]=>
  object(App\Models\Book)#7 (2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(12) "Human Animal"
  }
}

pbaczek@HPWHITE-PBACZEK:~/mapper$ ./vendor/bin/phpstan analyse src --level 8
 5/5 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
[OK] No errors

0

u/Special_Bit4460 23d ago

Disclaimer: I am not familiar with PHPStan and have limited experience with PHP in general.

I am missing a return Type at your getArrayOfObjects method and your targetClass.
The languages I usually work with allow me to do sth like:

abstract class Mapper<T> {

getArrayOfObjects():T[] {

}

}

class BookMapper extends Mapper<Book> {

}

So calling getArrayOfObjects() of a BookMapper will always Return an Array of Books. Your targetClass is currently of the Type string. And your $Book will be mixed So you need a way to add the type to the methods return and/or the targetClass.