|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Nette; |
| 4 | + |
| 5 | +use Nette\DI\Container; |
| 6 | +use PHPStan\ShouldNotHappenException; |
| 7 | +use function is_file; |
| 8 | +use function is_readable; |
| 9 | +use function sprintf; |
| 10 | + |
| 11 | +class ContainerResolver |
| 12 | +{ |
| 13 | + |
| 14 | + /** @var string|null */ |
| 15 | + private $containerLoader; |
| 16 | + |
| 17 | + /** @var Container|false|null */ |
| 18 | + private $container; |
| 19 | + |
| 20 | + public function __construct(?string $containerLoader) |
| 21 | + { |
| 22 | + $this->containerLoader = $containerLoader; |
| 23 | + } |
| 24 | + |
| 25 | + public function getContainer(): ?Container |
| 26 | + { |
| 27 | + if ($this->container === false) { |
| 28 | + return null; |
| 29 | + } |
| 30 | + |
| 31 | + if ($this->container !== null) { |
| 32 | + return $this->container; |
| 33 | + } |
| 34 | + |
| 35 | + if ($this->containerLoader === null) { |
| 36 | + $this->container = false; |
| 37 | + |
| 38 | + return null; |
| 39 | + } |
| 40 | + |
| 41 | + $this->container = $this->loadContainer($this->containerLoader); |
| 42 | + |
| 43 | + return $this->container; |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + private function loadContainer(string $containerLoader): ?Container |
| 48 | + { |
| 49 | + if (!is_file($containerLoader)) { |
| 50 | + throw new ShouldNotHappenException(sprintf( |
| 51 | + 'Nette container could not be loaded: file "%s" does not exist', |
| 52 | + $containerLoader |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + if (!is_readable($containerLoader)) { |
| 57 | + throw new ShouldNotHappenException(sprintf( |
| 58 | + 'Nette container could not be loaded: file "%s" is not readable', |
| 59 | + $containerLoader |
| 60 | + )); |
| 61 | + } |
| 62 | + |
| 63 | + return require $containerLoader; |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments