Completed
Push — master ( b31a90...d6fa8b )
by Drew
01:32
created

Drip::setAccountId()   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 1
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
    /**
15
     * Drip constructor.
16
     *
17
     * @param string      $token     API Token
18
     * @param string|null $accountID Drip account ID to operate on
19
     */
20
    public function __construct($token, $accountID = null)
21
    {
22
        $this->token = $token;
0 ignored issues
show
Documentation Bug introduced by
The property $token was declared of type boolean, but $token is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
23
24
        if ($accountID !== null) {
25
            $this->accountID = $accountID;
0 ignored issues
show
Documentation Bug introduced by
The property $accountID was declared of type boolean, but $accountID is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
26
        }
27
    }
28
29
    public static function subscribeToWebhook($event, callable $callback)
30
    {
31
        if (!isset(self::$eventSubscriptions[$event])) {
32
            self::$eventSubscriptions[$event] = [];
33
        }
34
        self::$eventSubscriptions[$event][] = $callback;
35
36
        self::receiveWebhook();
37
    }
38
39
    public static function receiveWebhook($input = null)
40
    {
41
        if (is_null($input)) {
42
            if (self::$receivedWebhook !== false) {
43
                $input = self::$receivedWebhook;
44
            } else {
45
                $input = file_get_contents("php://input");
46
            }
47
        }
48
49
        if ($input) {
50
            return self::processWebhook($input);
51
        }
52
53
        return false;
54
    }
55
56
    protected static function processWebhook($input)
57
    {
58
        if ($input) {
59
            self::$receivedWebhook = $input;
60
            $result                = json_decode($input, true);
61
            if ($result && isset($result['event'])) {
62
                self::dispatchWebhookEvent($result['event'], $result['data']);
63
                return $result;
64
            }
65
        }
66
67
        return false;
68
    }
69
70
    protected static function dispatchWebhookEvent($event, $data)
71
    {
72
        if (isset(self::$eventSubscriptions[$event])) {
73
            foreach (self::$eventSubscriptions[$event] as $callback) {
74
                $callback($data);
75
            }
76
            // reset subscriptions
77
            self::$eventSubscriptions[$event] = [];
78
        }
79
        return false;
80
    }
81
82
    /**
83
     * Set account ID if it was not passed into the constructor
84
     *
85
     * @param string $accountID
86
     *
87
     * @return bool
88
     */
89
    public function setAccountId($accountID) : bool
90
    {
91
        $this->accountID = $accountID;
0 ignored issues
show
Documentation Bug introduced by
The property $accountID was declared of type boolean, but $accountID is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
92
        return true;
93
    }
94
95
    /**
96
     * Make a GET request
97
     *
98
     * @param string $api_method API method to call
99
     * @param array  $args       API arguments
100
     * @param int    $timeout    Connection timeout (seconds)
101
     *
102
     * @return Response
103
     * @throws DripException
104
     */
105
    public function get($api_method, $args = [], $timeout = 10)
106
    {
107
        return $this->makeRequest('get', $api_method, $args, $timeout);
108
    }
109
110
    /**
111
     * Make the HTTP request
112
     *
113
     * @param string $http_verb  HTTP method used: get, post, delete
114
     * @param string $api_method Drip API method to call
115
     * @param array  $args       Array of arguments to the API method
116
     * @param int    $timeout    Connection timeout (seconds)
117
     * @param string $url        Optional URL to override the constructed one
118
     *
119
     * @return Response
120
     * @throws DripException
121
     */
122
    protected function makeRequest($http_verb, $api_method, $args = [], $timeout = 10, $url = null) : Response
123
    {
124
        if ($url === null) {
125
            $url = $this->api_endpoint . '/' . $this->accountID . '/' . $api_method;
126
        }
127
128
        if (function_exists('curl_init') && function_exists('curl_setopt')) {
129
130
            $ch = curl_init();
131
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
132
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
133
                'Accept: application/vnd.api+json',
134
                'Content-Type: application/vnd.api+json',
135
            ]);
136
            curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/Drip (github.com/drewm/drip)');
137
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
138
            curl_setopt($ch, CURLOPT_USERPWD, $this->token . ': ');
139
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
140
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
141
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
142
            curl_setopt($ch, CURLOPT_URL, $url);
143
144
            switch ($http_verb) {
145
                case 'post':
146
                    curl_setopt($ch, CURLOPT_POST, 1);
147
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
148
                    break;
149
150
                case 'get':
151
                    $query = http_build_query($args);
152
                    curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
153
                    break;
154
155
                case 'delete':
156
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
157
                    break;
158
            }
159
160
            $result = curl_exec($ch);
161
162
            if (!curl_errno($ch)) {
163
                $info = curl_getinfo($ch);
164
                curl_close($ch);
165
                return new Response($info, $result);
166
            }
167
168
            $errno = curl_errno($ch);
169
            $error = curl_error($ch);
170
171
            curl_close($ch);
172
173
            throw new DripException($error, $errno);
174
        } else {
175
            throw new DripException("cURL support is required, but can't be found.", 1);
176
        }
177
    }
178
179
    /**
180
     * Make a GET request to a top-level method outside of this account
181
     *
182
     * @param string $api_method
183
     * @param array  $args
184
     * @param int    $timeout
185
     *
186
     * @return Response
187
     * @throws DripException
188
     */
189
    public function getGlobal($api_method, $args = [], $timeout = 10)
190
    {
191
        $url = $this->api_endpoint . '/' . $api_method;
192
        return $this->makeRequest('get', $api_method, $args, $timeout, $url);
193
    }
194
195
    /**
196
     * Make a POST request
197
     *
198
     * @param string $api_method API method
199
     * @param array  $args       Arguments to API method
200
     * @param int    $timeout    Connection timeout (seconds)
201
     *
202
     * @return Response
203
     * @throws DripException
204
     */
205
    public function post($api_method, $args = [], $timeout = 10)
206
    {
207
        return $this->makeRequest('post', $api_method, $args, $timeout);
208
    }
209
210
    /**
211
     * Make a DELETE request
212
     *
213
     * @param string $api_method API method
214
     * @param array  $args       Arguments to the API method
215
     * @param int    $timeout    Connection timeout (seconds)
216
     *
217
     * @return Response
218
     * @throws DripException
219
     */
220
    public function delete($api_method, $args = [], $timeout = 10)
221
    {
222
        return $this->makeRequest('delete', $api_method, $args, $timeout);
223
    }
224
225
    public function disableSSLVerification()
226
    {
227
        $this->verify_ssl = false;
228
    }
229
}
230