Issues (36)

src/Module.php (1 issue)

Labels
Severity
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
This use statement conflicts with another class in this namespace, BEAR\Package\AppMetaModule. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are 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.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
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 20
use function is_subclass_of;
18
use function ucwords;
19 20
20 20
class Module
21 20
{
22 20
    /**
23 20
     * Return module from $appMeta and $context
24 14
     */
25
    public function __invoke(AbstractAppMeta $appMeta, string $context): AbstractModule
26 20
    {
27 2
        $contextsArray = array_reverse(explode('-', $context));
28
        $module = new AssistedModule();
29
        foreach ($contextsArray as $contextItem) {
30 18
            $module = $this->installContextModule($appMeta, $contextItem, $module);
31
        }
32 18
33
        $module->override(new AppMetaModule($appMeta));
34
35 18
        return $module;
36
    }
37 18
38
    private function installContextModule(AbstractAppMeta $appMeta, string $contextItem, AbstractModule $module): AbstractModule
39
    {
40
        $class = $appMeta->name . '\Module\\' . ucwords($contextItem) . 'Module';
41
        if (! class_exists($class)) {
42
            $class = 'BEAR\Package\Context\\' . ucwords($contextItem) . 'Module';
43
        }
44
45
        if (! is_a($class, AbstractModule::class, true)) {
46
            throw new InvalidContextException($contextItem);
47
        }
48
49
        /** @psalm-suppress UnsafeInstantiation */
50
        $module = is_subclass_of($class, AbstractAppModule::class) ? new $class($appMeta, $module) : new $class($module);
51
52
        return $module;
53
    }
54
}
55