<?php

namespace common\logic;

use yii\base\ErrorException;

abstract class AbstractManager extends AbstractSingleton implements ManagerInterface
{
    protected ContainerInterface $container;

    public function __call($method, $args)
    {
        foreach($this->getContainer()->getServices() as $serviceClass) {
            if(method_exists($serviceClass, $method)) {
                return call_user_func_array(
                    [$serviceClass::getInstance(), $method],
                    $args
                );
            }
        }

        throw new ErrorException('La méthode '.$method.' est introuvable dans les services du container '.get_class($this->container));
    }

    protected function setContainer(ContainerInterface $container): void
    {
        $this->container = $container;
    }

    public function getContainer(): ContainerInterface
    {
        return $this->container;
    }

    public function initContainer(): void
    {
        $containerFqcn = $this->getContainerFqcn();
        $this->setContainer($containerFqcn::getInstance());
    }
}