Completed
Push — master ( 356b0e...69e8fc )
by Cees-Jan
06:37
created

Factory   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 15
dl 0
loc 89
rs 9.1666
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 22 2
A createContainer() 0 11 2
A createCommandBus() 0 20 1
A mapCommandsToHandlers() 0 4 1
A locateServices() 0 4 1
A createTransport() 0 7 1
A createHydrator() 0 12 4
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Foundation;
4
5
use ApiClients\Foundation\Events\CommandLocatorEvent;
6
use ApiClients\Foundation\Events\ServiceLocatorEvent;
7
use ApiClients\Foundation\Hydrator\Factory as HydratorFactory;
8
use ApiClients\Foundation\Hydrator\Hydrator;
9
use ApiClients\Foundation\Transport\Client as TransportClient;
10
use ApiClients\Foundation\Transport\Factory as TransportFactory;
11
use ApiClients\Tools\CommandBus\CommandBus;
12
use Generator;
13
use Interop\Container\ContainerInterface;
14
use League\Container\Container;
15
use League\Container\ReflectionContainer;
16
use League\Event\Emitter;
17
use League\Event\EmitterInterface;
18
use League\Tactician\Container\ContainerLocator;
19
use League\Tactician\Handler\CommandHandlerMiddleware;
20
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
21
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
22
use React\EventLoop\LoopInterface;
23
24
final class Factory
25
{
26
    public static function create(
27
        LoopInterface $loop = null,
28
        ContainerInterface $wrappedContainer = null,
29
        array $options = []
30
    ): Client {
31
        $container = self::createContainer($wrappedContainer);
32
33
        $container->share(EmitterInterface::class, new Emitter());
34
        $container->share(TransportClient::class, self::createTransport($container, $loop, $options));
35
        $container->share(Hydrator::class, self::createHydrator($container, $options));
36
        $container->share(CommandBus::class, function () use ($container) {
37
            return self::createCommandBus($container);
38
        });
39
40
        foreach (self::locateServices($container->get(EmitterInterface::class)) as $service) {
41
            $container->share($service);
42
        }
43
44
        return new Client(
45
            $container
46
        );
47
    }
48
49
    private static function createContainer(ContainerInterface $wrappedContainer = null): Container
50
    {
51
        $container = new Container();
52
        $container->delegate(new ReflectionContainer());
53
54
        if ($wrappedContainer instanceof ContainerInterface) {
55
            $container->delegate($wrappedContainer);
56
        }
57
58
        return $container;
59
    }
60
61
    private static function createCommandBus(ContainerInterface $container): CommandBus
62
    {
63
        $commandToHandlerMap = self::mapCommandsToHandlers($container->get(EmitterInterface::class));
64
65
        $containerLocator = new ContainerLocator(
66
            $container,
67
            $commandToHandlerMap
68
        );
69
70
        $commandHandlerMiddleware = new CommandHandlerMiddleware(
71
            new ClassNameExtractor(),
72
            $containerLocator,
73
            new HandleInflector()
74
        );
75
76
        return new CommandBus(
77
            $container->get(LoopInterface::class),
78
            $commandHandlerMiddleware
79
        );
80
    }
81
82
    private static function mapCommandsToHandlers(EmitterInterface $emitter): array
83
    {
84
        return $emitter->emit(CommandLocatorEvent::create())->getMap();
0 ignored issues
show
Bug introduced by Cees-Jan Kiewiet
It seems like you code against a concrete implementation and not the interface League\Event\EventInterface as the method getMap() does only exist in the following implementations of said interface: ApiClients\Foundation\Events\CommandLocatorEvent, ApiClients\Foundation\Events\ServiceLocatorEvent.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
85
    }
86
87
    private static function locateServices(EmitterInterface $emitter): Generator
88
    {
89
        return $emitter->emit(ServiceLocatorEvent::create())->getMap();
0 ignored issues
show
Bug introduced by Cees-Jan Kiewiet
It seems like you code against a concrete implementation and not the interface League\Event\EventInterface as the method getMap() does only exist in the following implementations of said interface: ApiClients\Foundation\Events\CommandLocatorEvent, ApiClients\Foundation\Events\ServiceLocatorEvent.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
90
    }
91
92
    private static function createTransport(
93
        ContainerInterface $container,
94
        LoopInterface $loop = null,
95
        array $options = []
96
    ): TransportClient {
97
        return TransportFactory::create($container, $loop, $options[Options::TRANSPORT_OPTIONS]);
0 ignored issues
show
Compatibility introduced by Cees-Jan Kiewiet
$container of type object<Interop\Container\ContainerInterface> is not a sub-type of object<League\Container\ContainerInterface>. It seems like you assume a child interface of the interface Interop\Container\ContainerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
98
    }
99
100
    private static function createHydrator(ContainerInterface $container, array $options = [])
101
    {
102
        if (isset($options[Options::HYDRATOR]) && $options[Options::HYDRATOR] instanceof Hydrator) {
103
            return $options[Options::HYDRATOR];
104
        }
105
106
        if (!isset($options[Options::HYDRATOR_OPTIONS])) {
107
            throw new \Exception('Missing Hydrator options');
108
        }
109
110
        return HydratorFactory::create($container, $options[Options::HYDRATOR_OPTIONS]);
111
    }
112
}
113