php-vivace/di

View on GitHub
src/Package.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php
namespace vivace\di;

use Psr\Container\ContainerInterface;
use vivace\di\Container\Proxy;
use vivace\di\Scope\Branch;
use vivace\di\Scope\Node;

trait Package
{
    /** @var callable[] */
    private $factories = [];
    /** @var ContainerInterface */
    private $used = [];

    final protected function export(string $id, callable $factory)
    {
        if (isset($this->factories[$id])) {
            throw new BadDefinitionError("Factory $id has been defined");
        }
        $this->factories[$id] = $factory;
    }

    final protected function use(ContainerInterface $container): Proxiable
    {
        if (!$container instanceof Proxiable) {
            $container = new Proxy($container);
        }
        return $this->used[] = $container;
    }

    public function getScope(): Scope
    {
        $self = new Branch($this->factories);
        if (empty($this->used)) {
            return $self;
        }
        return new Node($self, ...$this->used);
    }
}