Completed
Pull Request — master (#30)
by
unknown
05:39
created

AzineMailgunHetrixtoolsService   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 42.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 76
ccs 11
cts 26
cp 0.4231
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B checkIpAddressInBlacklist() 0 24 2
A prepareBlacklistIpCheckUrl() 0 17 4
1
<?php
2
3
namespace Azine\MailgunWebhooksBundle\Services\HetrixtoolsService;
4
5
/**
6
 * AzineMailgunHetrixtoolsService
7
 *
8
 * This service is a wrapper for using Hetrixtools blacklist check functionality https://hetrixtools.com/.
9
 */
10
class AzineMailgunHetrixtoolsService
11
{
12
    /**
13
     * @var string
14
     */
15
    private $apiKey;
16
17
    /**
18
     * @var string
19
     */
20
    private $blacklistIpCheckUrl;
21
22
    /**
23
     * AzineMailgunHetrixtoolsService constructor.
24
     *
25
     * @param string $apiKey
26
     * @param string $url
27
     */
28 2
    public function __construct($apiKey, $url)
29
    {
30 2
        $this->apiKey = $apiKey;
31 2
        $this->blacklistIpCheckUrl = $url;
32 2
    }
33
34
    /**
35
     * @param string $ip
36
     * @return HetrixtoolsServiceResponse $response
37
     */
38 2
    public function checkIpAddressInBlacklist($ip)
39
    {
40 2
        $url = $this->prepareBlacklistIpCheckUrl($ip);
41
        $ch = curl_init($url);
42
43
        curl_setopt($ch, CURLOPT_HEADER, true);
44
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
45
46
        $server_output = curl_exec($ch);
47
        $info = curl_getinfo($ch);
48
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
49
        curl_close($ch);
50
51
        $response = substr($server_output, $header_size);
52
53
        if($info['http_code'] != 200){
54
55
            return null;
56
        }
57
58
        $response = HetrixtoolsServiceResponse::fromJson($response);
59
60
        return $response;
61
    }
62
63
    /**
64
     * @param string $ip
65
     * @throws \InvalidArgumentException
66
     * @return string $url
67
     */
68 2
    private function prepareBlacklistIpCheckUrl($ip)
69
    {
70 2
        if ($ip == null || !filter_var($ip, FILTER_VALIDATE_IP)) {
71
72 1
            throw new \InvalidArgumentException('Given Ip address is invalid');
73
        }
74
75 1
        if($this->apiKey == null){
76
77 1
            throw new \InvalidArgumentException('Api key for Hetrixtools blacklist check service is not set');
78
        }
79
80
        $url = str_replace('<API_TOKEN>', $this->apiKey, $this->blacklistIpCheckUrl);
81
        $url = str_replace('<IP_ADDRESS>', $ip, $url);
82
83
        return $url;
84
    }
85
}