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

AzineMailgunHetrixtoolsService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
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
}