Passed
Push — master ( 9ff61e...68c176 )
by Francis
01:55
created

LiveStream::updateEventLogo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 18
rs 9.9332
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
     * Undocumented function
125
     *
126
     * @param  integer $accountId
127
     * @param  integer $eventId
128
     * @param  string  $filePath
129
     * @return boolean
130
     */
131
    public function updateEventLogo(int $accountId, int $eventId, string $filePath): Event
132
    {
133
        if (!in_array(mime_content_type($filePath), [
134
            'image/png',
135
            'image/jpg',
136
            'image/jpeg',
137
            'image/gif'
138
        ])) {
139
            throw new InValidResourceException('Logo', 'poster (MIME Type must be one of image/png, image/jpg, image/gif)');
140
        }
141
142
        $response = $this->request("accounts/$accountId/events/$eventId/logo", 'put', null, null, [
143
            'logo' => new CURLFile($filePath, mime_content_type($filePath), basename($filePath))
144
        ]);
145
146
        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...
147
148
        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...
149
    }
150
151
    /**
152
     * Get RTMP Key.
153
     *
154
     * @param  integer $accountId
155
     * @param  integer $eventId
156
     * 
157
     * @return \LiveStream\Resources\RTMPKey|null
158
     */
159
    public function getRtmpKey(
160
        int $accountId,
161
        int $eventId,
162
        bool $notifyFollowers = false,
163
        bool $publishVideo = false,
164
        bool $saveVideo = false
165
    ): ?RTMPKey {
166
167
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'get', null, [
168
            'notifyFollowers' => $notifyFollowers,
169
            'publishVideo'    => $publishVideo,
170
            'saveVideo'       => $saveVideo
171
        ]);
172
173
        if ($response === null) return null;
174
175
        return RTMPKey::fromObject(json_decode($response));
176
    }
177
178
    /**
179
     * Reset RTMPKey
180
     *
181
     * @param  integer $accountId
182
     * @param  integer $eventId
183
     * @return \LiveStream\Resources\RTMPKey|null
184
     */
185
    public function resetRtmpKey(int $accountId, int $eventId): ?RTMPKey
186
    {
187
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'put');
188
189
        if ($response === null) return null;
190
191
        return RTMPKey::fromObject(json_decode($response));
192
    }
193
194
    /**
195
     * CURL Request
196
     *
197
     * @param  string $endpoint
198
     * @return 
199
     */
200
    private function request(
201
        string $endpoint,
202
        string $verb = 'get',
203
        ?Resource $body = null,
204
        ?array $query = null,
205
        ?array $multipartFormData = null
206
    ): ?string {
207
        $ch = curl_init();
208
209
        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...
210
211
        curl_setopt(
212
            $ch,
213
            CURLOPT_URL,
214
            $this->get_base_url() . $endpoint . ($query ? '?' . http_build_query($query) : '')
215
        );
216
217
        curl_setopt($ch, CURLOPT_USERPWD, $this->apiKey . ':');
218
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
219
220
        if ($verb != 'get') {
221
            if ($verb == 'post') curl_setopt($ch, CURLOPT_POST, true);
222
            if ($verb == 'put') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
223
            if ($body) {
224
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
225
                    'Content-Type: ' . $body->getContentType()
226
                ]);
227
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body->getResourceBody());
228
            } elseif ($multipartFormData) {
229
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
230
                    'Content-Type: multipart/form-data'
231
                ]);
232
                curl_setopt($ch, CURLOPT_POSTFIELDS, $multipartFormData);
233
            }
234
        }
235
236
        $response = curl_exec($ch);
237
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
238
239
        curl_close($ch);
240
241
        if ($code == 200 || $code == 201) return $response;
242
243
        if ($code == 404) return null;
244
245
        if ($code <= 199) throw new Exception("A CURL erorr with code '$code', has occurred.");
246
247
        if ($code == 403) throw new LiveStreamException(self::ERROR_CODES[$code] . ' ' . json_decode($response)->message);
248
249
        throw new LiveStreamException(self::ERROR_CODES[$code]);
250
    }
251
252
    /**
253
     * Get Base URL.
254
     *
255
     * @return string
256
     */
257
    private function get_base_url(): string
258
    {
259
        return getenv('LIB_ENV') == 'testing' ? 'http://127.0.0.1:3067/' : self::BASE_URL;
260
    }
261
}
262