Completed
Push — master ( b47c2a...b31a90 )
by Drew
02:34
created

Drip::getGlobal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace DrewM\Drip;
4
5
class Drip
6
{
7
    protected static $eventSubscriptions = [];
8
    protected static $receivedWebhook    = false;
9
    protected        $api_endpoint       = 'https://api.getdrip.com/v2';
10
    protected        $token              = false;
11
    protected        $accountID          = false;
12
    protected        $verify_ssl         = true;
13
14
    public function __construct($token, $accountID)
15
    {
16
        $this->token     = $token;
17
        $this->accountID = $accountID;
18
    }
19
20
    public static function subscribeToWebhook($event, callable $callback)
21
    {
22
        if (!isset(self::$eventSubscriptions[$event])) {
23
            self::$eventSubscriptions[$event] = [];
24
        }
25
        self::$eventSubscriptions[$event][] = $callback;
26
27
        self::receiveWebhook();
28
    }
29
30
    public static function receiveWebhook($input = null)
31
    {
32
        if (is_null($input)) {
33
            if (self::$receivedWebhook !== false) {
34
                $input = self::$receivedWebhook;
35
            } else {
36
                $input = file_get_contents("php://input");
37
            }
38
        }
39
40
        if ($input) {
41
            return self::processWebhook($input);
42
        }
43
44
        return false;
45
    }
46
47
    protected static function processWebhook($input)
48
    {
49
        if ($input) {
50
            self::$receivedWebhook = $input;
51
            $result                = json_decode($input, true);
52
            if ($result && isset($result['event'])) {
53
                self::dispatchWebhookEvent($result['event'], $result['data']);
54
                return $result;
55
            }
56
        }
57
58
        return false;
59
    }
60
61
    protected static function dispatchWebhookEvent($event, $data)
62
    {
63
        if (isset(self::$eventSubscriptions[$event])) {
64
            foreach (self::$eventSubscriptions[$event] as $callback) {
65
                $callback($data);
66
            }
67
            // reset subscriptions
68
            self::$eventSubscriptions[$event] = [];
69
        }
70
        return false;
71
    }
72
73
    /**
74
     * Make a GET request
75
     *
76
     * @param string $api_method API method to call
77
     * @param array  $args       API arguments
78
     * @param int    $timeout    Connection timeout (seconds)
79
     *
80
     * @return Response
81
     * @throws DripException
82
     */
83
    public function get($api_method, $args = [], $timeout = 10)
84
    {
85
        return $this->makeRequest('get', $api_method, $args, $timeout);
86
    }
87
88
    /**
89
     * Make the HTTP request
90
     *
91
     * @param string $http_verb  HTTP method used: get, post, delete
92
     * @param string $api_method Drip API method to call
93
     * @param array  $args       Array of arguments to the API method
94
     * @param int    $timeout    Connection timeout (seconds)
95
     * @param string $url        Optional URL to override the constructed one
96
     *
97
     * @return Response
98
     * @throws DripException
99
     */
100
    protected function makeRequest($http_verb, $api_method, $args = [], $timeout = 10, $url = null) : Response
101
    {
102
        if ($url === null) {
103
            $url = $this->api_endpoint . '/' . $this->accountID . '/' . $api_method;
104
        }
105
106
        if (function_exists('curl_init') && function_exists('curl_setopt')) {
107
108
            $ch = curl_init();
109
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
110
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
111
                'Accept: application/vnd.api+json',
112
                'Content-Type: application/vnd.api+json',
113
            ]);
114
            curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/Drip (github.com/drewm/drip)');
115
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
116
            curl_setopt($ch, CURLOPT_USERPWD, $this->token . ': ');
117
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
118
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
119
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
120
            curl_setopt($ch, CURLOPT_URL, $url);
121
122
            switch ($http_verb) {
123
                case 'post':
124
                    curl_setopt($ch, CURLOPT_POST, 1);
125
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
126
                    break;
127
128
                case 'get':
129
                    $query = http_build_query($args);
130
                    curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
131
                    break;
132
133
                case 'delete':
134
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
135
                    break;
136
            }
137
138
            $result = curl_exec($ch);
139
140
            if (!curl_errno($ch)) {
141
                $info = curl_getinfo($ch);
142
                curl_close($ch);
143
                return new Response($info, $result);
144
            }
145
146
            $errno = curl_errno($ch);
147
            $error = curl_error($ch);
148
149
            curl_close($ch);
150
151
            throw new DripException($error, $errno);
152
        } else {
153
            throw new DripException("cURL support is required, but can't be found.", 1);
154
        }
155
    }
156
157
    /**
158
     * Make a GET request to a top-level method outside of this account
159
     *
160
     * @param string $api_method
161
     * @param array  $args
162
     * @param int    $timeout
163
     *
164
     * @return Response
165
     * @throws DripException
166
     */
167
    public function getGlobal($api_method, $args = [], $timeout = 10)
168
    {
169
        $url = $this->api_endpoint . '/' . $api_method;
170
        return $this->makeRequest('get', $api_method, $args, $timeout, $url);
171
    }
172
173
    /**
174
     * Make a POST request
175
     *
176
     * @param string $api_method API method
177
     * @param array  $args       Arguments to API method
178
     * @param int    $timeout    Connection timeout (seconds)
179
     *
180
     * @return Response
181
     * @throws DripException
182
     */
183
    public function post($api_method, $args = [], $timeout = 10)
184
    {
185
        return $this->makeRequest('post', $api_method, $args, $timeout);
186
    }
187
188
    /**
189
     * Make a DELETE request
190
     *
191
     * @param string $api_method API method
192
     * @param array  $args       Arguments to the API method
193
     * @param int    $timeout    Connection timeout (seconds)
194
     *
195
     * @return Response
196
     * @throws DripException
197
     */
198
    public function delete($api_method, $args = [], $timeout = 10)
199
    {
200
        return $this->makeRequest('delete', $api_method, $args, $timeout);
201
    }
202
203
    public function disableSSLVerification()
204
    {
205
        $this->verify_ssl = false;
206
    }
207
}
208