Passed
Push — master ( 4c0885...a98b66 )
by Francis
01:35
created

LiveStream::deleteEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LiveStream;
4
5
use CURLFile;
6
use Exception;
7
8
use LiveStream\Resources\Event;
9
use LiveStream\Resources\RTMPKey;
10
use LiveStream\Resources\Account;
11
use LiveStream\Interfaces\Resource;
12
13
use LiveStream\Exceptions\LiveStreamException;
14
use LiveStream\Exceptions\InValidResourceException;
15
16
class LiveStream
17
{
18
    /**
19
     * Live Stream API Base URL.
20
     */
21
    const BASE_URL = 'https://livestreamapis.com/v3/';
22
23
    /**
24
     * LiveStream API HTTP Codes.
25
     */
26
    const ERROR_CODES = [
27
        400 => 'Bad Request: Your request is not properly constructed.',
28
        401 => 'Unauthorized: Your API key is incorrect.',
29
        403 => 'Forbidden:',
30
        405 => 'Method Not Allowed: You tried to access a resource with an invalid method.',
31
        406 => 'Not Acceptable: You requested a format that is not JSON.',
32
        500 => 'Internal Server Error: We had a problem with our server. Please try again later.',
33
        503 => 'Service Unavailable: We are temporarily offline for maintanance. Please try again later.'
34
    ];
35
36
    /**
37
     * API_KEY.
38
     *
39
     * @var string
40
     */
41
    private $apiKey;
42
43
    /**
44
     * Class Constructor
45
     *
46
     * @param string $apiKey
47
     */
48
    public function __construct(string $apiKey)
49
    {
50
        $this->apiKey = $apiKey;
51
    }
52
53
    /**
54
     * Get Linked LiveStream Accounts
55
     *
56
     * @return array Array of LiveStream Accounts 
57
     */
58
    public function getAccounts(): array
59
    {
60
        $response = $this->request('accounts');
61
62
        $accounts = [];
63
64
        foreach (json_decode($response) as $account) {
65
            $accounts[] = Account::fromObject($account);
66
        }
67
68
        return $accounts;
69
    }
70
71
    /**
72
     * Get Specific Account
73
     *
74
     * @param  integer $accountId
75
     * @return Account|null
76
     */
77
    public function getAccount(int $accountId): ?Account
78
    {
79
        $response = $this->request("accounts/$accountId");
80
        if ($response === null) return null;
81
82
        return Account::fromObject(json_decode($response));
83
    }
84
85
    /**
86
     * Create New Event
87
     *
88
     * @param  integer $accountId
89
     * @param  Event $event
90
     * @return boolean
91
     */
92
    public function createEvent(int $accountId, Event &$event): bool
93
    {
94
        $event->validate();
95
96
        $response = $this->request("accounts/$accountId/events", 'post', $event);
97
98
        if ($response === null) return false;
99
100
        $event = Event::fromObject(json_decode($response));
101
102
        return true;
103
    }
104
105
    /**
106
     * Update Event.
107
     *
108
     * @param  integer $accountId
109
     * @param  LiveStream\Resources\Event $event
0 ignored issues
show
Bug introduced by
The type LiveStream\LiveStream\Resources\Event was not found. Did you mean LiveStream\Resources\Event? If so, make sure to prefix the type with \.
Loading history...
110
     * @return boolean
111
     */
112
    public function updateEvent(int $accountId, Event $event): bool
113
    {
114
        $event->validate(true);
115
116
        $response = $this->request("accounts/$accountId/events/$event->id", 'put', $event);
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on LiveStream\Resources\Event. Since you implemented __get, consider adding a @property annotation.
Loading history...
117
118
        if ($response === null) return false;
119
120
        return true;
121
    }
122
123
    /**
124
     * Delete Event
125
     *
126
     * @param  integer $accountId
127
     * @param  integer $eventId
128
     * 
129
     * @return boolean
130
     */
131
    public function deleteEvent(int $accountId, int $eventId): ?Event
132
    {
133
        $response = $this->request("accounts/$accountId/events/$eventId", 'delete');
134
135
        if ($response === null) return null;
136
137
        return Event::fromObject(json_decode($response));
0 ignored issues
show
Bug Best Practice introduced by
The expression return LiveStream\Resour...json_decode($response)) returns the type LiveStream\Resources\Event which is incompatible with the documented return type boolean.
Loading history...
138
    }
139
140
    /**
141
     * Update Event Logo.
142
     *
143
     * @param  integer $accountId
144
     * @param  integer $eventId
145
     * @param  string  $filePath
146
     * @return boolean
147
     */
148
    public function updateEventLogo(int $accountId, int $eventId, string $filePath): Event
149
    {
150
        if (!in_array(mime_content_type($filePath), [
151
            'image/png',
152
            'image/jpg',
153
            'image/jpeg',
154
            'image/gif'
155
        ])) {
156
            throw new InValidResourceException('Logo', 'poster (MIME Type must be one of image/png, image/jpg, image/gif)');
157
        }
158
159
        $response = $this->request("accounts/$accountId/events/$eventId/logo", 'put', null, null, [
160
            'logo' => new CURLFile($filePath, mime_content_type($filePath), basename($filePath))
161
        ]);
162
163
        if ($response == null) return null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return null returns the type null which is incompatible with the type-hinted return LiveStream\Resources\Event.
Loading history...
164
165
        return Event::fromObject(json_decode($response));
0 ignored issues
show
Bug Best Practice introduced by
The expression return LiveStream\Resour...json_decode($response)) returns the type LiveStream\Resources\Event which is incompatible with the documented return type boolean.
Loading history...
166
    }
167
168
    /**
169
     * Get Draft Events
170
     *
171
     * @param integer $accountId
172
     * @param integer $page
173
     * @param integer $maxItems
174
     * @param string  $order
175
     * 
176
     * @return array
177
     */
178
    public function getDraftEvents(
179
        int $accountId,
180
        int $page = 1,
181
        int $maxItems = 10,
182
        string $order = 'desc'
183
    ): array {
184
        $response = $this->request("accounts/$accountId/draft_events", 'get', null, [
185
            'page'     => $page,
186
            'maxItems' => $maxItems,
187
            'order'    => $order
188
        ]);
189
190
        if ($response === null) return null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return null returns the type null which is incompatible with the type-hinted return array.
Loading history...
191
192
        $events = [];
193
194
        foreach (json_decode($response)->data as $event) {
195
            $events[] = Event::fromObject($event);
196
        }
197
198
        return $events;
199
    }
200
201
    /**
202
     * Get RTMP Key.
203
     *
204
     * @param  integer $accountId
205
     * @param  integer $eventId
206
     * 
207
     * @return \LiveStream\Resources\RTMPKey|null
208
     */
209
    public function getRtmpKey(
210
        int $accountId,
211
        int $eventId,
212
        bool $notifyFollowers = false,
213
        bool $publishVideo = false,
214
        bool $saveVideo = false
215
    ): ?RTMPKey {
216
217
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'get', null, [
218
            'notifyFollowers' => $notifyFollowers,
219
            'publishVideo'    => $publishVideo,
220
            'saveVideo'       => $saveVideo
221
        ]);
222
223
        if ($response === null) return null;
224
225
        return RTMPKey::fromObject(json_decode($response));
226
    }
227
228
    /**
229
     * Reset RTMPKey
230
     *
231
     * @param  integer $accountId
232
     * @param  integer $eventId
233
     * @return \LiveStream\Resources\RTMPKey|null
234
     */
235
    public function resetRtmpKey(int $accountId, int $eventId): ?RTMPKey
236
    {
237
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'put');
238
239
        if ($response === null) return null;
240
241
        return RTMPKey::fromObject(json_decode($response));
242
    }
243
244
    /**
245
     * CURL Request
246
     *
247
     * @param  string $endpoint
248
     * @return 
249
     */
250
    private function request(
251
        string $endpoint,
252
        string $verb = 'get',
253
        ?Resource $body = null,
254
        ?array $query = null,
255
        ?array $multipartFormData = null
256
    ): ?string {
257
        $ch = curl_init();
258
259
        if (!$ch) throw new Exception("Could not initialize CURL.");
0 ignored issues
show
introduced by
$ch is of type false|resource, thus it always evaluated to false.
Loading history...
260
261
        curl_setopt(
262
            $ch,
263
            CURLOPT_URL,
264
            $this->get_base_url() . $endpoint . ($query ? '?' . http_build_query($query) : '')
265
        );
266
267
        curl_setopt($ch, CURLOPT_USERPWD, $this->apiKey . ':');
268
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
269
270
        if ($verb != 'get') {
271
            if ($verb == 'post') curl_setopt($ch, CURLOPT_POST, true);
272
            if ($verb == 'put') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
273
            if ($verb == 'delete') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
274
            if ($body) {
275
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
276
                    'Content-Type: ' . $body->getContentType()
277
                ]);
278
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body->getResourceBody());
279
            } elseif ($multipartFormData) {
280
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
281
                    'Content-Type: multipart/form-data'
282
                ]);
283
                curl_setopt($ch, CURLOPT_POSTFIELDS, $multipartFormData);
284
            }
285
        }
286
287
        $response = curl_exec($ch);
288
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
289
290
        curl_close($ch);
291
292
        if ($code == 200 || $code == 201) return $response;
293
294
        if ($code == 404) return null;
295
296
        if ($code <= 199) throw new Exception("A CURL erorr with code '$code', has occurred.");
297
298
        if ($code == 403) throw new LiveStreamException(self::ERROR_CODES[$code] . ' ' . json_decode($response)->message);
299
300
        throw new LiveStreamException(self::ERROR_CODES[$code]);
301
    }
302
303
    /**
304
     * Get Base URL.
305
     *
306
     * @return string
307
     */
308
    private function get_base_url(): string
309
    {
310
        return getenv('LIB_ENV') == 'testing' ? 'http://127.0.0.1:3067/' : self::BASE_URL;
311
    }
312
}
313