Completed
Push — master ( 11f33f...14005b )
by Tim
10:31 queued 07:40
created

ApiCallService::makeCall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * Class ApiCallService
4
 */
5
6
namespace HDNET\OnpageIntegration\Service;
7
8
use HDNET\OnpageIntegration\Exception\UnavailableException;
9
10
/**
11
 * Class ApiCallService
12
 */
13
class ApiCallService
14
{
15
16
    private $url = 'https://api.onpage.org/zoom/json';
17
18
    /**
19
     * Start the api call
20
     *
21
     * @param string $json
22
     * @return string
23
     */
24
    public function makeCall($json)
25
    {
26
        $this->checkForCurl();
27
28
        return $this->send($json);
29
    }
30
31
    /**
32
     * Check if curl is loaded
33
     *
34
     * @throws \Exception
35
     */
36
    protected function checkForCurl()
37
    {
38
        if (!extension_loaded('curl')) {
39
            throw new \Exception('The curl extension needs to be enabled.');
40
        }
41
    }
42
43
    /**
44
     * Send the api request
45
     *
46
     * @param string $data
47
     * @return string
48
     * @throws UnavailableException
49
     */
50
    protected function send($data)
51
    {
52
        $ch = curl_init();
53
        curl_setopt($ch, CURLOPT_URL, $this->url);
54
        curl_setopt($ch, CURLOPT_HEADER, 0);
55
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
56
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
57
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
58
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
59
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
60
        curl_setopt(
61
            $ch,
62
            CURLOPT_HTTPHEADER,
63
            array(
64
                'Content-Type: application/json',
65
                'Content-Length: ' . strlen($data)
66
            )
67
        );
68
        $return = curl_exec($ch);
69
        $code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
70
71
        if ($code >= 500) {
72
            throw new UnavailableException('The API could not be reached.');
73
        }
74
        if ($code >= 400) {
75
            throw new UnavailableException('There has been an error reaching the API.');
76
        }
77
78
        return $return;
79
    }
80
}
81