MatchCommand   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 26
c 1
b 0
f 1
dl 0
loc 56
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A hasResponse() 0 3 1
A getRequest() 0 11 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 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';
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
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 (0 === (int) $json['status_code']) {
63
            return null;
64
        }
65
66
        return new Response((int) $json['status_code'], $ruleId, $location);
67
    }
68
}
69