Passed
Pull Request — master (#3)
by Mariano
01:32
created

Phiremock::setExpectationsPathConfiguration()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
c 0
b 0
f 0
nc 6
nop 0
dl 0
loc 18
rs 9.2222

2 Methods

Rating   Name   Duplication   Size   Complexity  
A Phiremock::didNotReceiveRequestsInRemoteService() 0 3 1
A Phiremock::dontHaveLoggedRequestsToRemoteService() 0 3 1
1
<?php
2
/**
3
 * This file is part of phiremock-codeception-module.
4
 *
5
 * phiremock-codeception-module is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * phiremock-codeception-module is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with phiremock-codeception-module.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace Codeception\Module;
20
21
use Codeception\Exception\ConfigurationException;
22
use Codeception\Exception\ModuleException;
23
use Codeception\Exception\ParseException;
24
use Codeception\Lib\ModuleContainer;
25
use Codeception\Module as CodeceptionModule;
26
use Codeception\TestInterface;
27
use Exception;
28
use InvalidArgumentException;
29
use Mcustiel\Phiremock\Client\Connection\Scheme;
30
use Mcustiel\Phiremock\Client\Utils\ConditionsBuilder;
31
use Mcustiel\Phiremock\Codeception\Util\Config;
32
use Mcustiel\Phiremock\Codeception\Util\ExpectationAnnotationParser;
33
use Mcustiel\Phiremock\Domain\Expectation;
34
use Psr\Http\Client\ClientExceptionInterface;
35
36
class Phiremock extends CodeceptionModule
37
{
38
    /** @var array */
39
    protected $config = Config::DEFAULT_CONFIG;
40
41
    /** @var \Mcustiel\Phiremock\Client\Phiremock */
42
    private $phiremock;
43
44
    /** @var ExpectationAnnotationParser */
45
    private $expectationsParser;
46
47
    /** @var Config */
48
    private $moduleConfig;
49
50
    /** @var Phiremock[] */
51
    private $extraConnections = [];
52
53
    /** @var bool */
54
    private $isExtraConfig;
55
56
    /** @throws ModuleException */
57
    public function __construct(ModuleContainer $moduleContainer, $config = null, bool $isExtra = false)
58
    {
59
        parent::__construct($moduleContainer, $config);
60
        $this->isExtraConfig = $isExtra;
61
        $this->moduleConfig = new Config($this->config, $this->createDebugMethod());
62
        if (!$this->isExtraConfig) {
63
            foreach ($this->moduleConfig->getExtraConnectionsConfigs() as $name => $connectionConfig) {
64
                if ($name === 'default') {
65
                    throw new ModuleException($this, 'The connection name "default" is reserved and can not be used for an extra connection');
66
                }
67
                $this->extraConnections[$name] = new self($this->moduleContainer, $connectionConfig->asArray(), true);
68
            }
69
        }
70
    }
71
72
    /**
73
     * @throws ConfigurationException
74
     * @throws Exception
75
     */
76
    public function _beforeSuite($settings = [])
77
    {
78
        $this->config = array_merge($this->moduleConfig->asArray(), $settings);
79
        $this->moduleConfig = new Config($this->config, $this->createDebugMethod());
80
81
        $this->phiremock = $this->moduleConfig->getClientFactory()->createPhiremockClient(
82
            $this->moduleConfig->getHost(),
83
            $this->moduleConfig->getPort(),
84
            new Scheme($this->moduleConfig->isSecure() ? Scheme::HTTPS: Scheme::HTTP)
85
        );
86
        $this->expectationsParser = new ExpectationAnnotationParser(
87
            $this->moduleConfig->getExpectationsPath()
88
        );
89
        if (!$this->isExtraConfig) {
90
            foreach ($this->extraConnections as $module) {
91
                $module->_beforeSuite($settings);
92
            }
93
        }
94
    }
95
96
    /** @throws ClientExceptionInterface */
97
    public function _before(TestInterface $test)
98
    {
99
        if ($this->moduleConfig->isResetBeforeEachTest()) {
100
            $this->haveACleanSetupInRemoteService();
101
        }
102
        try {
103
            $expectations = $this->expectationsParser->getExpectations($test);
104
            if (!empty($expectations)) {
105
                foreach ($expectations as $expectation) {
106
                    $this->phiremock->createExpectationFromJson(
107
                        file_get_contents($expectation)
108
                    );
109
                }
110
            }
111
        } catch (ParseException $exception) {
112
            $this->debug('Error parsing expectation annotations: ' . $exception->getMessage());
113
        }
114
        parent::_before($test);
115
        if (!$this->isExtraConfig) {
116
            foreach ($this->extraConnections as $connection) {
117
                $connection->_before($test);
118
            }
119
        }
120
    }
121
122
    /** @throws ModuleException */
123
    public function takeConnection(string $name): Phiremock
124
    {
125
        if ($this->isExtraConfig) {
126
            throw new ModuleException($this, 'Trying to take a connection from an extra connection');
127
        }
128
        if ($name === 'default') {
129
            return $this;
130
        }
131
        if (!isset($this->extraConnections[$name])) {
132
            throw new InvalidArgumentException(
133
                sprintf('Connection %s does not exist', $name)
134
            );
135
        }
136
        return $this->extraConnections[$name];
137
    }
138
139
    /** @throws ClientExceptionInterface */
140
    public function expectARequestToRemoteServiceWithAResponse(Expectation $expectation): void
141
    {
142
        $this->phiremock->createExpectation($expectation);
143
    }
144
145
    /** @throws ClientExceptionInterface */
146
    public function haveACleanSetupInRemoteService(): void
147
    {
148
        $this->phiremock->reset();
149
    }
150
151
    /** @throws ClientExceptionInterface */
152
    public function dontExpectRequestsInRemoteService(): void
153
    {
154
        $this->phiremock->clearExpectations();
155
        $this->phiremock->resetRequestsCounter();
156
    }
157
158
    /** @throws ClientExceptionInterface */
159
    public function haveCleanScenariosInRemoteService(): void
160
    {
161
        $this->phiremock->resetScenarios();
162
    }
163
164
    /** @deprecated Name is confusing, sounds like an assertion */
165
    public function didNotReceiveRequestsInRemoteService(): void
166
    {
167
        $this->dontHaveLoggedRequestsToRemoteService();
168
    }
169
170
    /** @throws ClientExceptionInterface */
171
    public function dontHaveLoggedRequestsToRemoteService(): void
172
    {
173
        $this->phiremock->resetRequestsCounter();
174
    }
175
176
    /**
177
     * @throws ClientExceptionInterface
178
     * @throws Exception
179
     */
180
    public function seeRemoteServiceReceived(int $times, ConditionsBuilder $builder): void
181
    {
182
        $requests = $this->phiremock->countExecutions($builder);
183
        if ($times !== $requests) {
184
            throw new Exception(
185
                "Request expected to be executed $times times, called $requests times instead"
186
            );
187
        }
188
    }
189
190
    /** @throws ClientExceptionInterface */
191
    public function grabRequestsMadeToRemoteService(ConditionsBuilder $builder): array
192
    {
193
        return $this->phiremock->listExecutions($builder);
194
    }
195
196
    /** @throws ClientExceptionInterface */
197
    public function setScenarioState(string $name, string $state): void
198
    {
199
        $this->phiremock->setScenarioState($name, $state);
200
    }
201
202
    private function createDebugMethod(): callable
203
    {
204
        return function (string $msg) : void {
205
            $this->debug($msg);
206
        };
207
    }
208
}
209