Completed
Push — master ( cf3940...ba149d )
by Cees-Jan
11:47
created

Factory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 1
eloc 13
nc 1
nop 3
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Foundation;
4
5
use ApiClients\Foundation\Hydrator\Factory as HydratorFactory;
6
use ApiClients\Foundation\Hydrator\Hydrator;
7
use ApiClients\Foundation\Hydrator\Options as HydratorOptions;
8
use ApiClients\Foundation\Transport\Client as TransportClient;
9
use ApiClients\Foundation\Transport\Factory as TransportFactory;
10
use ApiClients\Foundation\Transport\Options as TransportOptions;
11
use Interop\Container\ContainerInterface;
12
use League\Container\Container;
13
use League\Container\ReflectionContainer;
14
use League\Event\Emitter;
15
use League\Event\EmitterInterface;
16
use League\Tactician\CommandBus;
17
use League\Tactician\Container\ContainerLocator;
18
use League\Tactician\Handler\CommandHandlerMiddleware;
19
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
20
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
21
use React\EventLoop\LoopInterface;
22
23
final class Factory
24
{
25
    public static function create(
26
        LoopInterface $loop = null,
27
        ContainerInterface $wrappedContainer = null,
28
        array $options = []
29
    ): Client {
30
        $container = self::createContainer($wrappedContainer);
31
32
        $container->share(EmitterInterface::class, new Emitter());
33
        $container->share(TransportClient::class, self::createTransport($container, $loop, $options));
34
        $container->share(Hydrator::class, self::createHydrator($container, $options));
35
        $container->share(CommandBus::class, function () use ($container) {
36
            return self::createCommandBus($container);
37
        });
38
39
        return new Client(
40
            $container
41
        );
42
    }
43
44
    private static function createContainer(ContainerInterface $wrappedContainer = null): Container
45
    {
46
        $container = new Container();
47
        $container->delegate(new ReflectionContainer());
48
49
        if ($wrappedContainer instanceof ContainerInterface) {
50
            $container->delegate($wrappedContainer);
51
        }
52
53
        return $container;
54
    }
55
56
    private static function createCommandBus(ContainerInterface $container): CommandBus
57
    {
58
        $commandToHandlerMap = self::mapCommandsToHandlers($container->get(EmitterInterface::class));
59
60
        $containerLocator = new ContainerLocator(
61
            $container,
62
            $commandToHandlerMap
63
        );
64
65
        $commandHandlerMiddleware = new CommandHandlerMiddleware(
66
            new ClassNameExtractor(),
67
            $containerLocator,
68
            new HandleInflector()
69
        );
70
71
        return new CommandBus([
72
            $commandHandlerMiddleware,
73
        ]);
74
    }
75
76
    private static function mapCommandsToHandlers(Emitter $emitter): array
77
    {
78
        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\CommandLocatorEvent.

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...
79
    }
80
81
    private static function createTransport(
82
        ContainerInterface $container,
83
        LoopInterface $loop = null,
84
        array $options = []
85
    ): TransportClient {
86
        $transport = TransportFactory::create($loop, $options);
87
        $container->share(LoopInterface::class, $transport->getLoop());
0 ignored issues
show
Bug introduced by Cees-Jan Kiewiet
It seems like you code against a concrete implementation and not the interface Interop\Container\ContainerInterface as the method share() does only exist in the following implementations of said interface: League\Container\Container.

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...
88
        return $transport;
89
    }
90
91
    private static function createHydrator(ContainerInterface $container, array $options = [])
0 ignored issues
show
Unused Code introduced by Cees-Jan Kiewiet
The parameter $container is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
92
    {
93
        if (isset($options[TransportOptions::HYDRATOR]) && $options[TransportOptions::HYDRATOR] instanceof Hydrator) {
94
            return $options[TransportOptions::HYDRATOR];
95
        }
96
97
        if (!isset($options[TransportOptions::HYDRATOR_OPTIONS])) {
98
            throw new \Exception('Missing Hydrator options');
99
        }
100
101
        return HydratorFactory::create($options[TransportOptions::HYDRATOR_OPTIONS]);
102
    }
103
}
104