Completed
Push — master ( 66e423...45459e )
by Joel
08:39
created

MatchWithResponseCommand::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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 implements CommandInterface
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
            'host' => $this->request->getHost(),
29
            'request_uri' => $this->request->getPath(),
30
            'user_agent' => $this->request->getUserAgent(),
31
            'referer' => $this->request->getReferer(),
32
            'scheme' => $this->request->getScheme(),
33
            'use_json' => true,
34
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
35
    }
36
37
    public function hasResponse()
38
    {
39
        return true;
40
    }
41
42
    public function parseResponse($response)
43
    {
44
        $json = json_decode($response, true);
45
46
        if (null === $json) {
47
            throw new \ErrorException(sprintf('Impossible to decode the JSON (%s). Content: "%s"', json_last_error_msg(), $response));
48
        }
49
50
        $ruleId = null;
51
        $location = null;
52
        $matchOnResponseStatus = 0;
53
54
        if (isset($json['matched_rule'], $json['matched_rule']['id'])) {
55
            $ruleId = $json['matched_rule']['id'];
56
        }
57
58
        if (isset($json['location'])) {
59
            $location = $json['location'];
60
        }
61
62
        if (isset($json['match_on_response_status'])) {
63
            $matchOnResponseStatus = $json['match_on_response_status'];
64
        }
65
66
        if ((int) $json['status_code'] === 0) {
67
            return null;
68
        }
69
70
        return new Response((int) $json['status_code'], $ruleId, $location, $matchOnResponseStatus);
71
    }
72
73
}
74