MatchWithResponseCommand::parseResponse()   A
last analyzed

Complexity

Conditions 6
Paths 17

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 15
c 1
b 0
f 1
nc 17
nop 1
dl 0
loc 29
rs 9.2222
1
<?php
2
3
namespace RedirectionIO\Client\Sdk\Command;
4
5
use RedirectionIO\Client\Sdk\HttpMessage\Request;
6
use RedirectionIO\Client\Sdk\HttpMessage\Response;
7
8
/**
9
 * Find matching rule for a specific request.
10
 */
11
class MatchWithResponseCommand extends Command
12
{
13
    private $request;
14
15
    public function __construct(Request $request)
16
    {
17
        $this->request = $request;
18
    }
19
20
    public function getName()
21
    {
22
        return 'MATCH_WITH_RESPONSE';
23
    }
24
25
    public function getRequest()
26
    {
27
        return json_encode([
28
            'project_id' => $this->projectKey,
29
            'host' => $this->request->getHost(),
30
            'request_uri' => $this->request->getPath(),
31
            'user_agent' => $this->request->getUserAgent(),
32
            'referer' => $this->request->getReferer(),
33
            'scheme' => $this->request->getScheme(),
34
            'use_json' => true,
35
        ], \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES);
36
    }
37
38
    public function hasResponse()
39
    {
40
        return true;
41
    }
42
43
    public function parseResponse($response)
44
    {
45
        $json = json_decode($response, true);
46
47
        if (null === $json) {
48
            throw new \ErrorException(sprintf('Impossible to decode the JSON (%s). Content: "%s"', json_last_error_msg(), $response));
49
        }
50
51
        $ruleId = null;
52
        $location = null;
53
        $matchOnResponseStatus = 0;
54
55
        if (isset($json['matched_rule'], $json['matched_rule']['id'])) {
56
            $ruleId = $json['matched_rule']['id'];
57
        }
58
59
        if (isset($json['location'])) {
60
            $location = $json['location'];
61
        }
62
63
        if (isset($json['match_on_response_status'])) {
64
            $matchOnResponseStatus = $json['match_on_response_status'];
65
        }
66
67
        if (0 === (int) $json['status_code']) {
68
            return null;
69
        }
70
71
        return new Response((int) $json['status_code'], $ruleId, $location, $matchOnResponseStatus);
72
    }
73
}
74