Passed
Push — master ( e135ef...71dd4a )
by Francis
01:43
created

LiveStream   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 60
dl 0
loc 193
rs 10
c 2
b 0
f 0
wmc 28

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getAccounts() 0 11 2
A getAccount() 0 6 2
A __construct() 0 3 1
A resetRtmpKey() 0 7 2
A createEvent() 0 15 5
A getRtmpKey() 0 17 2
A get_base_url() 0 3 2
C request() 0 44 12
1
<?php
2
3
namespace LiveStream;
4
5
use Exception;
6
7
use LiveStream\Resources\Event;
8
use LiveStream\Resources\RTMPKey;
9
use LiveStream\Resources\Account;
10
use LiveStream\Interfaces\Resource;
11
12
use LiveStream\Exceptions\LiveStreamException;
13
use LiveStream\Exceptions\InValidResourceException;
14
15
class LiveStream
16
{
17
    /**
18
     * Live Stream API Base URL.
19
     */
20
    const BASE_URL = 'https://livestreamapis.com/v3/';
21
22
    const ERROR_CODES = [
23
        400 => 'Bad Request: Your request is not properly constructed.',
24
        401 => 'Unauthorized: Your API key is incorrect.',
25
        403 => 'Forbidden:',
26
        405 => 'Method Not Allowed: You tried to access a resource with an invalid method.',
27
        406 => 'Not Acceptable: You requested a format that is not JSON.',
28
        500 => 'Internal Server Error: We had a problem with our server. Please try again later.',
29
        503 => 'Service Unavailable: We are temporarily offline for maintanance. Please try again later.'
30
    ];
31
32
    /**
33
     * API_KEY.
34
     *
35
     * @var string
36
     */
37
    private $apiKey;
38
39
    /**
40
     * Class Constructor
41
     *
42
     * @param string $apiKey
43
     */
44
    public function __construct(string $apiKey)
45
    {
46
        $this->apiKey = $apiKey;
47
    }
48
49
    /**
50
     * Get Linked LiveStream Accounts
51
     *
52
     * @return array Array of LiveStream Accounts 
53
     */
54
    public function getAccounts(): array
55
    {
56
        $response = $this->request('accounts');
57
58
        $accounts = [];
59
60
        foreach (json_decode($response) as $account) {
61
            $accounts[] = Account::fromObject($account);
62
        }
63
64
        return $accounts;
65
    }
66
67
    /**
68
     * Get Specific Account
69
     *
70
     * @param  integer $accountId
71
     * @return Account|null
72
     */
73
    public function getAccount(int $accountId): ?Account
74
    {
75
        $response = $this->request("accounts/$accountId");
76
        if ($response === null) return null;
77
78
        return Account::fromObject(json_decode($response));
79
    }
80
81
    /**
82
     * Create New Event
83
     *
84
     * @param  integer $accountId
85
     * @param  Event $event
86
     * @return boolean
87
     */
88
    public function createEvent(int $accountId, Event &$event): bool
89
    {
90
        if (!$event->fullName) throw new InValidResourceException('Event', 'fullName');
91
92
        if ($event->isPasswordProtected && !$event->password) {
0 ignored issues
show
Bug Best Practice introduced by
The property isPasswordProtected does not exist on LiveStream\Resources\Event. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property password does not exist on LiveStream\Resources\Event. Since you implemented __get, consider adding a @property annotation.
Loading history...
93
            throw new InValidResourceException('Event', 'password (password must be present for a password protected event)');
94
        }
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
     * Get RTMP Key.
107
     *
108
     * @param  integer $accountId
109
     * @param  integer $eventId
110
     * 
111
     * @return \LiveStream\Resources\RTMPKey|null
112
     */
113
    public function getRtmpKey(
114
        int $accountId,
115
        int $eventId,
116
        bool $notifyFollowers = false,
117
        bool $publishVideo = false,
118
        bool $saveVideo = false
119
    ): ?RTMPKey {
120
121
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'get', null, [
122
            'notifyFollowers' => $notifyFollowers,
123
            'publishVideo'    => $publishVideo,
124
            'saveVideo'       => $saveVideo
125
        ]);
126
127
        if ($response === null) return null;
128
129
        return RTMPKey::fromObject(json_decode($response));
130
    }
131
132
    /**
133
     * Reset RTMPKey
134
     *
135
     * @param  integer $accountId
136
     * @param  integer $eventId
137
     * @return \LiveStream\Resources\RTMPKey|null
138
     */
139
    public function resetRtmpKey(int $accountId, int $eventId): ?RTMPKey
140
    {
141
        $response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'put');
142
143
        if ($response === null) return null;
144
145
        return RTMPKey::fromObject(json_decode($response));
146
    }
147
148
    /**
149
     * CURL Request
150
     *
151
     * @param  string $endpoint
152
     * @return 
153
     */
154
    private function request(
155
        string $endpoint,
156
        string $verb = 'get',
157
        ?Resource $body = null,
158
        ?array $query = null
159
    ): ?string {
160
        $ch = curl_init();
161
162
        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...
163
164
        curl_setopt(
165
            $ch,
166
            CURLOPT_URL,
167
            $this->get_base_url() . $endpoint . ($query ? '?' . http_build_query($query) : '')
168
        );
169
170
        curl_setopt($ch, CURLOPT_USERPWD, $this->apiKey . ':');
171
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
172
173
        if ($verb != 'get') {
174
            if ($verb == 'post') curl_setopt($ch, CURLOPT_POST, true);
175
            if ($verb == 'put') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
176
            if ($body) {
177
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
178
                    'Content-Type: ' . $body->getContentType()
179
                ]);
180
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body->getResourceBody());
181
            }
182
        }
183
184
        $response = curl_exec($ch);
185
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
186
187
        curl_close($ch);
188
189
        if ($code == 200 || $code == 201) return $response;
190
191
        if ($code == 404) return null;
192
193
        if ($code <= 199) throw new Exception("A CURL erorr with code '$code', has occurred.");
194
195
        if ($code == 403) throw new LiveStreamException(self::ERROR_CODES[$code] . ' ' . json_decode($response)->message);
196
197
        throw new LiveStreamException(self::ERROR_CODES[$code]);
198
    }
199
200
    /**
201
     * Get Base URL.
202
     *
203
     * @return string
204
     */
205
    private function get_base_url(): string
206
    {
207
        return getenv('LIB_ENV') == 'testing' ? 'http://127.0.0.1:3067/' : self::BASE_URL;
208
    }
209
}
210