Passed
Push — master ( 923da3...a8671e )
by Mariano
15:37
created

requestJsonMatchesExpectation()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 17
nc 8
nop 2
dl 0
loc 34
rs 8.4444
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of Phiremock.
4
 *
5
 * Phiremock 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 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.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace Mcustiel\Phiremock\Server\Utils;
20
21
use InvalidArgumentException;
22
use Mcustiel\Phiremock\Domain\Conditions;
23
use Mcustiel\Phiremock\Domain\Expectation;
24
use Mcustiel\Phiremock\Server\Model\ScenarioStorage;
25
use Psr\Http\Message\ServerRequestInterface;
26
use Psr\Log\LoggerInterface;
27
28
class RequestExpectationComparator
29
{
30
    /** @var ScenarioStorage */
31
    private $scenarioStorage;
32
    /** @var LoggerInterface */
33
    private $logger;
34
35
    public function __construct(
36
        ScenarioStorage $scenarioStorage,
37
        LoggerInterface $logger
38
    ) {
39
        $this->scenarioStorage = $scenarioStorage;
40
        $this->logger = $logger;
41
    }
42
43
    public function equals(ServerRequestInterface $httpRequest, Expectation $expectation): bool
44
    {
45
        $this->logger->debug('Checking if request matches an expectation');
46
47
        if (!$this->isExpectedScenarioState($expectation)) {
48
            return false;
49
        }
50
51
        $expectedRequest = $expectation->getRequest();
52
53
        $foundMatch = $this->compareRequestParts($httpRequest, $expectedRequest);
54
        $this->logger->debug('Matches? ' . ((bool) $foundMatch ? 'yes' : 'no'));
55
56
        return $foundMatch;
57
    }
58
59
    private function compareRequestParts(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
60
    {
61
        return $this->requestMethodMatchesExpectation($httpRequest, $expectedRequest)
62
            && $this->requestUrlMatchesExpectation($httpRequest, $expectedRequest)
63
            && $this->requestBodyMatchesExpectation($httpRequest, $expectedRequest)
64
            && $this->requestHeadersMatchExpectation($httpRequest, $expectedRequest)
65
            && $this->requestFormDataMatchExpectation($httpRequest, $expectedRequest)
66
            && $this->requestJsonMatchesExpectation($httpRequest, $expectedRequest);
67
    }
68
69
    private function isExpectedScenarioState(Expectation $expectation): bool
70
    {
71
        if ($expectation->getRequest()->hasScenarioState()) {
72
            $this->checkScenarioNameOrThrowException($expectation);
73
            $this->logger->debug('Checking scenario state again expectation');
74
            $scenarioState = $this->scenarioStorage->getScenarioState(
75
                $expectation->getScenarioName()
76
            );
77
            if (!$expectation->getRequest()->getScenarioState()->equals($scenarioState)) {
78
                return false;
79
            }
80
        }
81
82
        return true;
83
    }
84
85
    /** @throws InvalidArgumentException */
86
    private function checkScenarioNameOrThrowException(Expectation $expectation)
87
    {
88
        if (!$expectation->hasScenarioName()) {
89
            throw new InvalidArgumentException('Expecting scenario state without specifying scenario name');
90
        }
91
    }
92
93
    private function requestMethodMatchesExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
94
    {
95
        $method = $expectedRequest->getMethod();
96
        if (!$method) {
97
            return true;
98
        }
99
        $this->logger->debug('Checking METHOD against expectation');
100
101
        return $method->getMatcher()->matches($httpRequest->getMethod());
102
    }
103
104
    private function requestUrlMatchesExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
105
    {
106
        $url = $expectedRequest->getUrl();
107
        if (!$url) {
108
            return true;
109
        }
110
        $this->logger->debug('Checking URL against expectation');
111
112
        $requestUrl = $this->getComparableRequestUrl($httpRequest);
113
114
        return $url->getMatcher()->matches($requestUrl);
115
    }
116
117
    private function getComparableRequestUrl($httpRequest)
118
    {
119
        $requestUrl = $httpRequest->getUri()->getPath();
120
        if ($httpRequest->getUri()->getQuery()) {
121
            $requestUrl .= '?' . $httpRequest->getUri()->getQuery();
122
        }
123
        if ($httpRequest->getUri()->getFragment()) {
124
            $requestUrl .= '#' . $httpRequest->getUri()->getFragment();
125
        }
126
127
        return $requestUrl;
128
    }
129
130
    private function requestBodyMatchesExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
131
    {
132
        $bodycondition = $expectedRequest->getBody();
133
        if (!$bodycondition) {
134
            return true;
135
        }
136
        $this->logger->debug('Checking BODY against expectation');
137
138
        return $bodycondition->getMatcher()->matches($httpRequest->getBody()->__toString());
139
    }
140
141
    private function requestHeadersMatchExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
142
    {
143
        $headerConditions = $expectedRequest->getHeaders();
144
        if (!$headerConditions) {
145
            return true;
146
        }
147
        $this->logger->debug('Checking HEADERS against expectation');
148
        foreach ($headerConditions as $header => $headerCondition) {
149
            $headerName = $header->asString();
150
            $this->logger->debug("Checking $headerName against expectation");
151
152
            $matches = $headerCondition->getMatcher()->matches(
153
                $httpRequest->getHeaderLine($headerName)
154
            );
155
            if (!$matches) {
156
                return false;
157
            }
158
        }
159
160
        return true;
161
    }
162
163
    private function requestFormDataMatchExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
164
    {
165
        $formDataConditions = $expectedRequest->getFormFields();
166
        if (!$formDataConditions) {
167
            return true;
168
        }
169
        $this->logger->debug('Checking FORM DATA against expectation');
170
        foreach ($formDataConditions as $field => $fieldCondition) {
171
            $fieldName = $field->asString();
172
            $this->logger->debug("Checking $fieldName against expectation");
173
174
            if (!isset($httpRequest->getParsedBody()[$fieldName])) {
175
                return false;
176
            }
177
178
            $matches = $fieldCondition->getMatcher()->matches(
179
                $httpRequest->getParsedBody()[$fieldName]
180
            );
181
            if (!$matches) {
182
                return false;
183
            }
184
        }
185
186
        return true;
187
    }
188
189
    private function requestJsonMatchesExpectation(ServerRequestInterface $httpRequest, Conditions $expectedRequest): bool
190
    {
191
        if (!$expectedRequest->hasJsonPath()) {
192
            return true;
193
        }
194
        
195
        $this->logger->debug('Checking JSON PATH against expectation');
196
        
197
        $requestBody = $httpRequest->getBody()->__toString();
198
        $requestData = json_decode($requestBody, true);
199
        
200
        if (json_last_error() !== JSON_ERROR_NONE) {
201
            return false;
202
        }
203
        
204
        /** @var JsonPathName $pathName */
205
        /** @var JsonPathCondition $jsonCondition */
206
        foreach ($expectedRequest->getJsonPath() as $pathName => $jsonCondition) {
207
            $path = explode('.', $pathName->asString());
208
            $value = $requestData;
209
            
210
            foreach ($path as $key) {
211
                if (!is_array($value) || !isset($value[$key])) {
212
                    return false;
213
                }
214
                $value = $value[$key];
215
            }
216
            
217
            if (!$jsonCondition->getMatcher()->matches($value)) {
218
                return false;
219
            }
220
        }
221
        
222
        return true;
223
    }
224
}
225