normalizeContext()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the SymfonyExtension package.
7
 *
8
 * (c) Kamil Kokot <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace FriendsOfBehat\SymfonyExtension\Context\Environment\Handler;
15
16
use Behat\Behat\Context\Context;
17
use Behat\Behat\Context\Environment\ContextEnvironment;
18
use Behat\Behat\Context\Environment\InitializedContextEnvironment;
19
use Behat\Behat\Context\Initializer\ContextInitializer;
20
use Behat\Testwork\Environment\Environment;
21
use Behat\Testwork\Environment\Exception\EnvironmentIsolationException;
22
use Behat\Testwork\Environment\Handler\EnvironmentHandler;
23
use Behat\Testwork\Suite\Exception\SuiteConfigurationException;
24
use Behat\Testwork\Suite\GenericSuite;
25
use Behat\Testwork\Suite\Suite;
26
use FriendsOfBehat\SymfonyExtension\Bundle\FriendsOfBehatSymfonyExtensionBundle;
27
use FriendsOfBehat\SymfonyExtension\Context\Environment\InitializedSymfonyExtensionEnvironment;
28
use FriendsOfBehat\SymfonyExtension\Context\Environment\UninitializedSymfonyExtensionEnvironment;
29
use Symfony\Component\DependencyInjection\ContainerInterface;
30
use Symfony\Component\HttpKernel\KernelInterface;
31
32
final class ContextServiceEnvironmentHandler implements EnvironmentHandler
33
{
34
    /** @var KernelInterface */
35
    private $symfonyKernel;
36
37
    /** @var EnvironmentHandler */
38
    private $decoratedEnvironmentHandler;
39
40
    /** @var ContextInitializer[] */
41
    private $contextInitializers = [];
42
43
    public function __construct(KernelInterface $symfonyKernel, EnvironmentHandler $decoratedEnvironmentHandler)
44
    {
45
        $this->symfonyKernel = $symfonyKernel;
46
        $this->decoratedEnvironmentHandler = $decoratedEnvironmentHandler;
47
    }
48
49
    public function registerContextInitializer(ContextInitializer $contextInitializer): void
50
    {
51
        $this->contextInitializers[] = $contextInitializer;
52
    }
53
54
    public function supportsSuite(Suite $suite): bool
55
    {
56
        return $suite->hasSetting('contexts');
57
    }
58
59
    public function buildEnvironment(Suite $suite): Environment
60
    {
61
        $symfonyContexts = [];
62
63
        foreach ($this->getSuiteContextsServices($suite) as $serviceId) {
64
            if (!$this->getContainer()->has($serviceId)) {
65
                continue;
66
            }
67
68
            /** @var object $service */
69
            $service = $this->getContainer()->get($serviceId);
70
71
            $symfonyContexts[$serviceId] = get_class($service);
72
        }
73
74
        $delegatedSuite = $this->cloneSuiteWithoutContexts($suite, array_keys($symfonyContexts));
75
76
        /** @var ContextEnvironment $delegatedEnvironment */
77
        $delegatedEnvironment = $this->decoratedEnvironmentHandler->buildEnvironment($delegatedSuite);
78
79
        return new UninitializedSymfonyExtensionEnvironment($suite, $symfonyContexts, $delegatedEnvironment);
80
    }
81
82
    public function supportsEnvironmentAndSubject(Environment $environment, $testSubject = null): bool
83
    {
84
        return $environment instanceof UninitializedSymfonyExtensionEnvironment;
85
    }
86
87
    /**
88
     * @throws EnvironmentIsolationException
89
     */
90
    public function isolateEnvironment(Environment $uninitializedEnvironment, $testSubject = null): Environment
91
    {
92
        $this->assertEnvironmentCanBeIsolated($uninitializedEnvironment, $testSubject);
93
94
        $environment = new InitializedSymfonyExtensionEnvironment($uninitializedEnvironment->getSuite());
95
96
        foreach ($uninitializedEnvironment->getServices() as $serviceId) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Testwork\Environment\Environment as the method getServices() does only exist in the following implementations of said interface: FriendsOfBehat\SymfonyEx...onyExtensionEnvironment.

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...
97
            /** @var Context $context */
98
            $context = $this->getContainer()->get($serviceId);
99
100
            $this->initializeContext($context);
101
102
            $environment->registerContext($context);
103
        }
104
105
        /** @var InitializedContextEnvironment $delegatedEnvironment */
106
        $delegatedEnvironment = $this->decoratedEnvironmentHandler->isolateEnvironment($uninitializedEnvironment->getDelegatedEnvironment());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Testwork\Environment\Environment as the method getDelegatedEnvironment() does only exist in the following implementations of said interface: FriendsOfBehat\SymfonyEx...onyExtensionEnvironment.

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...
107
108
        foreach ($delegatedEnvironment->getContexts() as $context) {
109
            $environment->registerContext($context);
110
        }
111
112
        return $environment;
113
    }
114
115
    private function initializeContext(Context $context): void
116
    {
117
        foreach ($this->contextInitializers as $contextInitializer) {
118
            $contextInitializer->initializeContext($context);
119
        }
120
    }
121
122
    /**
123
     * @return string[]
124
     *
125
     * @throws SuiteConfigurationException If "contexts" setting is not an array
126
     */
127
    private function getSuiteContextsServices(Suite $suite): array
128
    {
129
        $contexts = $suite->getSetting('contexts');
130
131 View Code Duplication
        if (!is_array($contexts)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
            throw new SuiteConfigurationException(sprintf(
133
                '"contexts" setting of the "%s" suite is expected to be an array, %s given.',
134
                $suite->getName(),
135
                gettype($contexts)
136
            ), $suite->getName());
137
        }
138
139
        return array_map([$this, 'normalizeContext'], $contexts);
140
    }
141
142
    private function cloneSuiteWithoutContexts(Suite $suite, array $contextsToRemove): Suite
143
    {
144
        $contexts = $suite->getSetting('contexts');
145
146 View Code Duplication
        if (!is_array($contexts)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
            throw new SuiteConfigurationException(sprintf(
148
                '"contexts" setting of the "%s" suite is expected to be an array, %s given.',
149
                $suite->getName(),
150
                gettype($contexts)
151
            ), $suite->getName());
152
        }
153
154
        $contexts = array_filter($contexts, function ($context) use ($contextsToRemove): bool {
155
            return !in_array($this->normalizeContext($context), $contextsToRemove, true);
156
        });
157
158
        return new GenericSuite($suite->getName(), array_merge($suite->getSettings(), ['contexts' => $contexts]));
159
    }
160
161
    private function normalizeContext($context): string
162
    {
163
        if (is_array($context)) {
164
            return current(array_keys($context));
165
        }
166
167
        if (is_string($context)) {
168
            return $context;
169
        }
170
171
        throw new \Exception();
172
    }
173
174
    /**
175
     * @psalm-assert UninitializedSymfonyExtensionEnvironment $uninitializedEnvironment
176
     *
177
     * @throws EnvironmentIsolationException
178
     */
179
    private function assertEnvironmentCanBeIsolated(Environment $uninitializedEnvironment, $testSubject): void
180
    {
181
        if (!$this->supportsEnvironmentAndSubject($uninitializedEnvironment, $testSubject)) {
182
            throw new EnvironmentIsolationException(sprintf(
183
                '"%s" does not support isolation of "%s" environment.',
184
                static::class,
185
                get_class($uninitializedEnvironment)
186
            ), $uninitializedEnvironment);
187
        }
188
    }
189
190
    private function getContainer(): ContainerInterface
191
    {
192
        try {
193
            $this->symfonyKernel->getBundle('FriendsOfBehatSymfonyExtensionBundle');
194
        } catch (\InvalidArgumentException $exception) {
195
            throw new \RuntimeException(sprintf(
196
                'Kernel "%s" used by Behat with "%s" environment and debug %s needs to have "%s" bundle registered.',
197
                get_class($this->symfonyKernel),
198
                $this->symfonyKernel->getEnvironment(),
199
                $this->symfonyKernel->isDebug() ? 'enabled' : 'disabled',
200
                FriendsOfBehatSymfonyExtensionBundle::class
201
            ));
202
        }
203
204
        return $this->symfonyKernel->getContainer();
205
    }
206
}
207