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

MatchCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A hasResponse() 0 3 1
A getRequest() 0 10 1
A parseResponse() 0 24 5
A __construct() 0 3 1
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, does not match if the rule should be run on a response status code
10
 */
11
class MatchCommand 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';
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
53
        if (isset($json['matched_rule'], $json['matched_rule']['id'])) {
54
            $ruleId = $json['matched_rule']['id'];
55
        }
56
57
        if (isset($json['location'])) {
58
            $location = $json['location'];
59
        }
60
61
        if ((int) $json['status_code'] === 0) {
62
            return null;
63
        }
64
65
        return new Response((int) $json['status_code'], $ruleId, $location);
66
    }
67
68
}
69