bearsunday /
BEAR.Package
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace BEAR\Package; |
||
| 6 | |||
| 7 | use BEAR\AppMeta\AbstractAppMeta; |
||
| 8 | use BEAR\Package\Exception\InvalidContextException; |
||
| 9 | use BEAR\Package\Module\AppMetaModule; |
||
|
0 ignored issues
–
show
|
|||
| 10 | use Ray\Di\AbstractModule; |
||
| 11 | use Ray\Di\AssistedModule; |
||
| 12 | |||
| 13 | use function array_reverse; |
||
| 14 | use function class_exists; |
||
| 15 | use function explode; |
||
| 16 | use function is_a; |
||
| 17 | use function is_subclass_of; |
||
| 18 | use function ucwords; |
||
| 19 | |||
| 20 | /** @psalm-import-type Context from Types */ |
||
| 21 | final class Module |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * Return module from $appMeta and $context |
||
| 25 | * |
||
| 26 | * @param Context $context |
||
| 27 | */ |
||
| 28 | public function __invoke(AbstractAppMeta $appMeta, string $context): AbstractModule |
||
| 29 | { |
||
| 30 | $contextsArray = array_reverse(explode('-', $context)); |
||
| 31 | $module = new AssistedModule(); |
||
| 32 | foreach ($contextsArray as $contextItem) { |
||
| 33 | $module = $this->installContextModule($appMeta, $contextItem, $module); |
||
| 34 | } |
||
| 35 | |||
| 36 | $module->override(new AppMetaModule($appMeta)); |
||
| 37 | |||
| 38 | return $module; |
||
| 39 | } |
||
| 40 | |||
| 41 | private function installContextModule(AbstractAppMeta $appMeta, string $contextItem, AbstractModule $module): AbstractModule |
||
| 42 | { |
||
| 43 | $class = $appMeta->name . '\Module\\' . ucwords($contextItem) . 'Module'; |
||
| 44 | if (! class_exists($class)) { |
||
| 45 | $class = 'BEAR\Package\Context\\' . ucwords($contextItem) . 'Module'; |
||
| 46 | } |
||
| 47 | |||
| 48 | if (! is_a($class, AbstractModule::class, true)) { |
||
| 49 | throw new InvalidContextException($contextItem); |
||
| 50 | } |
||
| 51 | |||
| 52 | /** @psalm-suppress UnsafeInstantiation */ |
||
| 53 | $module = is_subclass_of($class, AbstractAppModule::class) ? new $class($appMeta, $module) : new $class($module); |
||
| 54 | |||
| 55 | return $module; |
||
| 56 | } |
||
| 57 | } |
||
| 58 |
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: