<?php

namespace Velis\Db\QueryBuilder;

use Velis\Db\QueryBuilder\Exceptions\InvalidMapperException;
use Velis\Model\DataObject;

/**
 * Class used to map query results to a given $mapperClass objects
 * @author Jakub Szczugieł <jakub.szczugiel@velistech.com>
 */
class QueryBuilderMapper
{
    public function __construct(private string $mapperClass)
    {
        if (!class_exists($this->mapperClass)) {
            throw new InvalidMapperException($this->mapperClass);
        }
    }

    public function map(array $items): array
    {
        $result = [];
        $mapperClass = $this->mapperClass;

        foreach ($items as $item) {
            $item = new $mapperClass($item);

            if ($item instanceof DataObject) {
                $id = $item->id();
                if (!is_array($id)) {
                    $result[$id] = $item;
                } else {
                    $result[] = $item;
                }
            } else {
                $result[] = $item;
            }
        }

        return $result;
    }
}
