Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Container;
- use Container\Exception\AlreadyExistsException;
- use Container\Exception\NotFoundException;
- use Psr\Container\ContainerInterface;
- final class Container implements ContainerInterface
- {
- /**
- * @var array
- */
- private $entries;
- /**
- * @var array
- */
- private $lazyEntries;
- public function __construct()
- {
- $this->entries = [];
- $this->lazyEntries = [];
- }
- /**
- * @inheritdoc
- */
- public function get($id)
- {
- if (!$this->has($id)) {
- throw new NotFoundException(sprintf('No entry was found for "%s" identifier.', $id));
- }
- if (array_key_exists($id, $this->lazyEntries)) {
- $factory = $this->lazyEntries[$id];
- unset($this->lazyEntries[$id]);
- $this->entries[$id] = $factory($this);
- }
- return $this->entries[$id];
- }
- /**
- * @inheritdoc
- */
- public function has($id)
- {
- return array_key_exists($id, $this->entries) || array_key_exists($id, $this->lazyEntries);
- }
- /**
- * Add entry to container
- *
- * @param string $id
- * @param mixed $entry
- *
- * @throws AlreadyExistsException Entry for **this** identifier already exists
- */
- public function add($id, $entry)
- {
- if ($this->has($id)) {
- throw new AlreadyExistsException(sprintf('Entry for "%s" identifier already exists', $id));
- }
- $this->entries[$id] = $entry;
- }
- /**
- * Add lazy entry to container
- *
- * @param string $id
- * @param callable $factory
- *
- * @throws AlreadyExistsException Entry for **this** identifier already exists
- */
- public function addLazy($id, callable $factory)
- {
- if ($this->has($id)) {
- throw new AlreadyExistsException(sprintf('Entry for "%s" identifier already exists', $id));
- }
- $this->lazyEntries[$id] = $factory;
- }
- /**
- * Remove entry
- *
- * @param string $id
- *
- * @throws NotFoundException No entry was found for **this** identifier
- */
- public function remove($id)
- {
- if (!$this->has($id)) {
- throw new NotFoundException(sprintf('No entry was found for "%s" identifier', $id));
- }
- unset($this->entries[$id], $this->lazyEntries[$id]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement