Completed
Pull Request — master (#11)
by
unknown
02:12
created

TwitchSDK::gamesSearch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
3
namespace ritero\SDK\TwitchTV;
4
5
/**
6
 * TwitchTV API SDK for PHP
7
 *
8
 * PHP SDK for interacting with the TwitchTV API
9
 *
10
 * @author Josef Ohnheiser <[email protected]>
11
 * @license https://github.com/jofner/Twitch-SDK/blob/master/LICENSE.md MIT
12
 * @homepage https://github.com/jofner/Twitch-SDK
13
 * @version 1.0.0
14
 */
15
class TwitchSDK
16
{
17
    /** @var array */
18
    protected $auth_config = false;
19
20
    /** @var integer Set timeout default. */
21
    public $timeout = 30;
22
23
    /** @var integer Set connect timeout */
24
    public $connect_timeout = 30;
25
26
    /** @var boolean Verify SSL Cert */
27
    public $ssl_verifypeer = false;
28
29
    /** @var integer Contains the last HTTP status code returned */
30
    public $http_code = 0;
31
32
    /** @var array Contains the last Server headers returned */
33
    public $http_header = array();
34
35
    /** @var array Contains the last HTTP headers returned */
36
    public $http_info = array();
37
38
    /** @var boolean Throw cURL errors */
39
    public $throw_curl_errors = true;
40
41
    /** @var string Set the useragnet */
42
    private $useragent = 'ritero TwitchSDK dev-0.4.*';
43
44
    /** @var string */
45
    private $clientId;
46
47
    /**
48
     * TwitchAPI URI's
49
     */
50
    const URL_TWITCH = 'https://api.twitch.tv/kraken/';
51
    const URI_USER = 'users/';
52
    const URI_USER_FOLLOWS_CHANNEL = '/users/%s/follows/channels';
53
    const URI_USER_FOLLOW_RELATION = '/users/%s/follows/channels/%s';
54
    const URI_CHANNEL = 'channels/';
55
    const URI_CHANNEL_FOLLOWS = 'channels/%s/follows';
56
    const URI_CHANNEL_SUBSCRIPTIONS = 'channels/%s/subscriptions';
57
    const URI_STREAM = 'streams/';
58
    const URI_STREAM_SUMMARY = 'streams/summary/';
59
    const URI_STREAMS_FEATURED = 'streams/featured/';
60
    const URI_STREAMS_SEARCH = 'search/streams/';
61
    const URI_GAMES_SEARCH = 'search/games/';
62
    const URI_VIDEO = 'videos/';
63
    const URI_CHAT = 'chat/';
64
    const URI_CHAT_EMOTICONS = 'chat/emoticons';
65
    const URI_GAMES_TOP = 'games/top/';
66
    const URI_AUTH = 'oauth2/authorize';
67
    const URI_AUTH_TOKEN = 'oauth2/token';
68
    const URI_USER_AUTH = 'user';
69
    const URI_CHANNEL_AUTH = 'channel';
70
    const URI_CHANNEL_EDITORS_AUTH = 'channels/%s/editors';
71
    const URI_STREAMS_FOLLOWED_AUTH = 'streams/followed';
72
    const URI_TEAMS = 'teams/';
73
74
    /**
75
     * For teams API we have different URI's and
76
     * use HTTP instead of HTTPS
77
     */
78
    const URL_TWITCH_TEAM = "http://api.twitch.tv/api/team/";
79
80
    /**
81
     * @return string
82
     */
83
    public function getClientId()
84
    {
85
        return $this->clientId;
86
    }
87
88
    /**
89
     * @param string $clientId
90
     */
91
    public function setClientId($clientId)
92
    {
93
        $this->clientId = $clientId;
94
    }
95
96
    /**
97
     * SDK constructor
98
     * @param   array
99
     * @throws  \ritero\SDK\TwitchTV\TwitchException
100
     * @throws \InvalidArgumentException
101
     */
102
    public function __construct($config = array())
103
    {
104
        if (!in_array('curl', get_loaded_extensions())) {
105
            throw new TwitchException('cURL extension is not installed and is required');
106
        }
107
108
        if (!array_key_exists('client_id', $config)) {
109
            throw new \InvalidArgumentException('Missing required Client-ID parameter in config
110
                @see https://blog.twitch.tv/client-id-required-for-kraken-api-calls-afbb8e95f843');
111
        }
112
113
        if (!empty($config)) {
114
            if ($this->configValidate($config) === true) {
115
                $this->auth_config = $config;
116
                $this->setClientId($config['client_id']);
117
            } else {
118
                throw new TwitchException('Wrong Twitch API config parameters');
119
            }
120
        }
121
    }
122
123
    /**
124
     * Basic information about the API and authentication status
125
     * @param   string
126
     * @return  stdClass
127
     */
128
    public function status($token = null)
129
    {
130
        $auth = null;
131
132
        if (!is_null($token)) {
133
            if ($this->auth_config === false) {
134
                $this->authConfigException();
135
            } else {
136
                $auth = $this->buildQueryString(array('oauth_token' => $token));
137
            }
138
        }
139
140
        return $this->request($auth);
141
    }
142
143
    /**
144
     * Get the specified user
145
     * @param   string
146
     * @return  stdClass
147
     */
148
    public function userGet($username)
149
    {
150
        return $this->request(self::URI_USER . $username);
151
    }
152
153
    /**
154
     * Get a user's list of followed channels
155
     * @param   integer
156
     * @param   integer
157
     * @param   integer
158
     * @return  stdClass
159
     */
160 View Code Duplication
    public function userFollowChannels($user, $limit = null, $offset = null)
161
    {
162
        $query_string = $this->buildQueryString(array(
163
            'limit' => $limit,
164
            'offset' => $offset,
165
        ));
166
167
        return $this->request(sprintf(self::URI_USER_FOLLOWS_CHANNEL, $user) . $query_string);
168
    }
169
170
    /**
171
     * Get the status of a follow relationship
172
     * @param   string
173
     * @param   string
174
     * @return  stdClass
175
     */
176
    public function userFollowRelationship($user, $channel)
177
    {
178
        return $this->request(sprintf(self::URI_USER_FOLLOW_RELATION, $user, $channel));
179
    }
180
181
    /**
182
     * Set user to follow given channel
183
     * @param   string
184
     * @param   string
185
     * @param   string
186
     * @return  stdClass
187
     */
188 View Code Duplication
    public function userFollowChannel($user, $channel, $userToken)
189
    {
190
        $query_string = $this->buildQueryString(array(
191
            'oauth_token' => $userToken,
192
        ));
193
194
        return $this->request(sprintf(self::URI_USER_FOLLOW_RELATION, $user, $channel) . $query_string, 'PUT');
195
    }
196
197
    /**
198
     * Set user to unfollow given channel
199
     * @param   string
200
     * @param   string
201
     * @param   string
202
     * @return  stdClass
203
     */
204 View Code Duplication
    public function userUnfollowChannel($user, $channel, $userToken)
205
    {
206
        $query_string = $this->buildQueryString(array(
207
            'oauth_token' => $userToken,
208
        ));
209
210
        return $this->request(sprintf(self::URI_USER_FOLLOW_RELATION, $user, $channel) . $query_string, 'DELETE');
211
    }
212
213
    /**
214
     * Get the specified channel
215
     * @param   string
216
     * @return  stdClass
217
     */
218
    public function channelGet($channel)
219
    {
220
        return $this->request(self::URI_CHANNEL . $channel);
221
    }
222
223
    /**
224
     * Get the specified team
225
     * @param   string
226
     * @return  stdClass
227
     */
228
    public function teamGet($teamName)
229
    {
230
        return $this->request(self::URI_TEAMS . $teamName);
231
    }
232
233
    /**
234
     *
235
     */
236
    public function teamMembersAll($teamName)
237
    {
238
        return $this->teamRequest($teamName . '/all_channels')->channels;
239
    }
240
241
    /**
242
     * Returns an array of users who follow the specified channel
243
     * @param   string
244
     * @param   integer
245
     * @param   integer
246
     * @return  stdClass
247
     */
248 View Code Duplication
    public function channelFollows($channel, $limit = null, $offset = null)
249
    {
250
        $query_string = $this->buildQueryString(array(
251
            'limit' => $limit,
252
            'offset' => $offset,
253
        ));
254
255
        return $this->request(sprintf(self::URI_CHANNEL_FOLLOWS, $channel) . $query_string);
256
    }
257
258
    /**
259
     * Get the specified channel's stream
260
     * @param   string
261
     * @return  stdClass
262
     */
263
    public function streamGet($channel)
264
    {
265
        return $this->request(self::URI_STREAM . $channel);
266
    }
267
268
    /**
269
     * Search live streams
270
     * @param   string
271
     * @param   integer
272
     * @param   integer
273
     * @return  stdClass
274
     */
275 View Code Duplication
    public function streamSearch($query, $limit = null, $offset = null)
276
    {
277
        $query_string = $this->buildQueryString(array(
278
            'query' => $query,
279
            'limit' => $limit,
280
            'offset' => $offset,
281
        ));
282
283
        return $this->request(self::URI_STREAMS_SEARCH . $query_string);
284
    }
285
286
    /**
287
     * Search games
288
     * @param   string
289
     * @param   integer
290
     * @param   integer
291
     * @return  stdClass
292
     */
293 View Code Duplication
    public function gamesSearch($query, $live = true)
294
    {
295
        $query_string = $this->buildQueryString(array(
296
          'query' => $query,
297
          'type' => "suggest",
298
          'live' => $live,
299
        ));
300
301
        return $this->request(self::URI_GAMES_SEARCH . $query_string);
302
    }
303
304
    /**
305
     * Summarize streams
306
     * @param   string
307
     * @param   array
308
     * @param   boolean
309
     * @return  stdClass
310
     */
311
    public function streamsSummarize($game = null, array $channels = null, $hls = null)
312
    {
313
        if (!empty($channels)) {
314
            $channels = implode(',', $channels);
315
        }
316
317
        $query_string = $this->buildQueryString(array(
318
            'game' => $game,
319
            'channel' => $channels,
320
            'hls' => $hls,
321
        ));
322
323
        return $this->request(self::URI_STREAM_SUMMARY . $query_string);
324
    }
325
326
    /**
327
     * Get featured streams
328
     * @param   integer
329
     * @param   integer
330
     * @param   boolean
331
     * @return  stdClass
332
     */
333 View Code Duplication
    public function streamsFeatured($limit = null, $offset = null, $hls = null)
334
    {
335
        $query_string = $this->buildQueryString(array(
336
            'limit' => $limit,
337
            'offset' => $offset,
338
            'hls' => $hls,
339
        ));
340
341
        return $this->request(self::URI_STREAMS_FEATURED . $query_string);
342
    }
343
344
    /**
345
     * Get streams by channel
346
     * @param   array
347
     * @param   integer
348
     * @param   integer
349
     * @param   boolean
350
     * @param   boolean
351
     * @return  stdClass
352
     */
353
    public function streamsByChannels($channels, $limit = null, $offset = null, $embeddable = null, $hls = null)
354
    {
355
        $channels_string = implode(',', $channels);
356
357
        return $this->getStreams(null, $limit, $offset, $channels_string, $embeddable, $hls);
358
    }
359
360
    /**
361
     * Get streams by game
362
     * @param   string
363
     * @param   integer
364
     * @param   integer
365
     * @param   boolean
366
     * @param   boolean
367
     * @return  stdClass
368
     */
369
    public function streamsByGame($game, $limit = null, $offset = null, $embeddable = null, $hls = null)
370
    {
371
        return $this->getStreams($game, $limit, $offset, null, $embeddable, $hls);
372
    }
373
374
    /**
375
     * Get video
376
     * @param   integer
377
     * @return  stdClass
378
     */
379
    public function videoGet($video)
380
    {
381
        return $this->request(self::URI_VIDEO . $video);
382
    }
383
384
    /**
385
     * Get videos for a channel
386
     * @param   string
387
     * @param   integer
388
     * @param   integer
389
     * @return  stdClass
390
     */
391
    public function videosByChannel($channel, $limit = null, $offset = null)
392
    {
393
        $query_string = $this->buildQueryString(array(
394
            'limit' => $limit,
395
            'offset' => $offset,
396
        ));
397
398
        return $this->request(self::URI_CHANNEL . $channel . '/' . self::URI_VIDEO . $query_string);
399
    }
400
401
    /**
402
     * Get the specified channel's chat
403
     * @param   string
404
     * @return  stdClass
405
     */
406
    public function chatGet($channel)
407
    {
408
        return $this->request(self::URI_CHAT . $channel);
409
    }
410
411
    /**
412
     * Get a chat's emoticons
413
     * @return  stdClass
414
     */
415
    public function chatEmoticons()
416
    {
417
        return $this->request(self::URI_CHAT_EMOTICONS);
418
    }
419
420
    /**
421
     * Get top games
422
     * @param   integer
423
     * @param   integer
424
     * @return  stdClass
425
     */
426 View Code Duplication
    public function gamesTop($limit = null, $offset = null)
427
    {
428
        $query_string = $this->buildQueryString(array(
429
            'limit' => $limit,
430
            'offset' => $offset,
431
        ));
432
433
        return $this->request(self::URI_GAMES_TOP . $query_string);
434
    }
435
436
    /**
437
     * Get HTML code for stream embedding
438
     * @param   string
439
     * @param   integer
440
     * @param   integer
441
     * @param   integer
442
     * @return  string
443
     */
444 View Code Duplication
    public function embedStream($channel, $width = 620, $height = 378, $volume = 25)
445
    {
446
        return '<object type="application/x-shockwave-flash"
447
                height="' . $height . '"
448
                width="' . $width . '"
449
                id="live_embed_player_flash"
450
                data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=' . $channel . '"
451
                bgcolor="#000000">
452
                <param  name="allowFullScreen"
453
                    value="true" />
454
                <param  name="allowScriptAccess"
455
                    value="always" />
456
                <param  name="allowNetworking"
457
                    value="all" />
458
                <param  name="movie"
459
                    value="http://www.twitch.tv/widgets/live_embed_player.swf" />
460
                <param  name="flashvars"
461
                    value="hostname=www.twitch.tv&channel=' . $channel . '&auto_play=true&start_volume=' . $volume . '" />
462
                </object>';
463
    }
464
465
    /**
466
     * Get HTML code for video embedding
467
     * @param   string
468
     * @param   integer
469
     * @param   integer
470
     * @param   integer
471
     * @param   integer
472
     * @return  string
473
     */
474 View Code Duplication
    public function embedVideo($channel, $chapterid, $width = 400, $height = 300, $volume = 25)
475
    {
476
        return '<object bgcolor="#000000"
477
                    data="http://www.twitch.tv/widgets/archive_embed_player.swf"
478
                    width="' . $width . '"
479
                    height="' . $height . '"
480
                    id="clip_embed_player_flash"
481
                    type="application/x-shockwave-flash">
482
                <param  name="movie"
483
                    value="http://www.twitch.tv/widgets/archive_embed_player.swf" />
484
                <param  name="allowScriptAccess"
485
                    value="always" />
486
                <param  name="allowNetworking"
487
                    value="all" />
488
                <param name="allowFullScreen"
489
                    value="true" />
490
                <param  name="flashvars"
491
                    value="channel=' . $channel . '&start_volume=' . $volume . '&auto_play=false&chapter_id=' . $chapterid . '" />
492
                </object>';
493
    }
494
495
    /**
496
     * Get HTML code for chat embedding
497
     * @param   string
498
     * @param   integer
499
     * @param   integer
500
     * @return  string
501
     */
502
    public function embedChat($channel, $width = 400, $height = 300)
503
    {
504
        return '<iframe frameborder="0"
505
                    scrolling="no"
506
                    id="chat_embed"
507
                    src="http://twitch.tv/chat/embed?channel=' . $channel . '&amp;popout_chat=true"
508
                    height="' . $height . '"
509
                    width="' . $width . '">
510
                </iframe>';
511
    }
512
513
    /**
514
     * Get login URL for authentication
515
     * @param   string $scope Specify which permissions your app requires (space separated list)
516
     * @return  string
517
     */
518
    public function authLoginURL($scope)
519
    {
520
        if ($this->auth_config === false) {
521
            $this->authConfigException();
522
        }
523
524
        $query_string = $this->buildQueryString(array(
525
            'response_type' => 'code',
526
            'client_id' => $this->auth_config['client_id'],
527
            'redirect_uri' => $this->auth_config['redirect_uri'],
528
            'scope' => $scope,
529
        ));
530
531
        return self::URL_TWITCH . self::URI_AUTH . $query_string;
532
    }
533
534
    /**
535
     * Get authentication access token
536
     * @param   string code returned after app authorization by user
537
     * @return  stdClass
538
     */
539
    public function authAccessTokenGet($code)
540
    {
541
        if ($this->auth_config === false) {
542
            $this->authConfigException();
543
        }
544
545
        $query_string = $this->buildQueryString(array(
546
            'client_id' => $this->auth_config['client_id'],
547
            'client_secret' => $this->auth_config['client_secret'],
548
            'grant_type' => 'authorization_code',
549
            'redirect_uri' => $this->auth_config['redirect_uri'],
550
            'code' => $code,
551
        ));
552
553
        return $this->request(self::URI_AUTH_TOKEN, 'POST', $query_string);
554
    }
555
556
    /**
557
     * Get the authenticated user
558
     *  - requires scope 'user_read'
559
     * @param   string
560
     * @return  stdClass
561
     */
562 View Code Duplication
    public function authUserGet($token)
563
    {
564
        if ($this->auth_config === false) {
565
            $this->authConfigException();
566
        }
567
568
        $query_string = $this->buildQueryString(array(
569
            'oauth_token' => $token,
570
            'client_id' => $this->auth_config['client_id'],
571
        ));
572
573
        return $this->request(self::URI_USER_AUTH . $query_string);
574
    }
575
576
    /**
577
     * Get the authenticated channel
578
     *  - requires scope 'channel_read'
579
     * @param   string
580
     * @return  stdClass
581
     */
582 View Code Duplication
    public function authChannelGet($token)
583
    {
584
        if ($this->auth_config === false) {
585
            $this->authConfigException();
586
        }
587
588
        $query_string = $this->buildQueryString(array(
589
            'oauth_token' => $token,
590
            'client_id' => $this->auth_config['client_id'],
591
        ));
592
593
        return $this->request(self::URI_CHANNEL_AUTH . $query_string);
594
    }
595
596
    /**
597
     * Returns an array of users who are editors of specified channel
598
     *  - requires scope 'channel_read'
599
     * @param   string
600
     * @param   string
601
     * @return  stdClass
602
     */
603 View Code Duplication
    public function authChannelEditors($token, $channel)
604
    {
605
        if ($this->auth_config === false) {
606
            $this->authConfigException();
607
        }
608
609
        $query_string = $this->buildQueryString(array(
610
            'oauth_token' => $token,
611
            'client_id' => $this->auth_config['client_id'],
612
        ));
613
614
        return $this->request(sprintf(self::URI_CHANNEL_EDITORS_AUTH, $channel) . $query_string);
615
    }
616
617
    /**
618
     * @description Returns an array of subscriptions who are subscribed to specified channel
619
     *  - requires scope 'channel_subscriptions'
620
     * @param   string $token - user's access token
621
     * @param   string $channel
622
     * @param   integer $limit - can be up to 100
623
     * @param   integer $offset
624
     * @param   string $direction can be DESC|ASC, if DESC - lasts will be showed first
625
     * @return  stdClass
626
     */
627
    public function authChannelSubscriptions($token, $channel, $limit = 25, $offset = 0, $direction = 'DESC')
628
    {
629
        if ($this->auth_config === false) {
630
            $this->authConfigException();
631
        }
632
633
        $query_string = $this->buildQueryString(array(
634
            'oauth_token' => $token,
635
            'client_id' => $this->auth_config['client_id'],
636
            'direction' => $direction,
637
            'limit' => $limit,
638
            'offset' => $offset
639
        ));
640
641
        return $this->request(sprintf(self::URI_CHANNEL_SUBSCRIPTIONS, $channel) . $query_string);
642
    }
643
644
    /**
645
     * List the live streams that the authenticated user is following
646
     *  - requires scope 'user_read'
647
     *
648
     * @param string  $token  API access token of an authenticated user
649
     * @param integer $limit  Maximum number of objects in streams array
650
     *                        Default => 25
651
     *                        Maximum => 100
652
     * @param integer $offset Object offset for pagination
653
     *                        Default => 0
654
     * @param boolean $hls    Limit the results to only the streams using HLS
655
     *
656
     * @return stdClass
657
     */
658
    public function authStreamsFollowed($token, $limit = null, $offset = null, $hls = null)
659
    {
660
        if ($this->auth_config === false) {
661
            $this->authConfigException();
662
        }
663
664
        $query = array(
665
            'oauth_token' => $token,
666
            'client_id' => $this->auth_config['client_id']
667
        );
668
669
        foreach (array('limit', 'offset', 'hls') as $param) {
670
            if (!is_null($$param)) {
671
                $query[$param] = $$param;
672
            }
673
        }
674
675
        $query_string = $this->buildQueryString($query);
676
677
        return $this->request(self::URI_STREAMS_FOLLOWED_AUTH . $query_string);
678
    }
679
680
    /**
681
     * Get streams helper
682
     * @param   string
683
     * @param   integer
684
     * @param   integer
685
     * @param   string
686
     * @param   boolean
687
     * @param   boolean
688
     * @return  stdClass
689
     */
690
    public function getStreams($game = null, $limit = null, $offset = null, $channels = null, $embeddable = null, $hls = null)
691
    {
692
        $params = array(
693
            'game' => $game,
694
            'limit' => $limit,
695
            'offset' => $offset,
696
            'channel' => !empty($channels) ? $channels : null,
697
            'embeddable' => $embeddable,
698
            'hls' => $hls,
699
        );
700
701
        $query_string = $this->buildQueryString($params);
702
703
        return $this->request(self::URI_STREAM . $query_string);
704
    }
705
706
    /**
707
     * Validate parameters for authentication
708
     * @param   array
709
     * @return  boolean
710
     */
711
    private function configValidate($config)
712
    {
713
        $check = array('client_id', 'client_secret', 'redirect_uri');
714
715
        foreach ($check AS $val) {
716
            if (!array_key_exists($val, $config) ||
717
                (empty($config[$val]) ||
718
                    !is_string($config[$val]))
719
            ) {
720
                return false;
721
            }
722
        }
723
724
        return true;
725
    }
726
727
    /**
728
     * Build query string
729
     * @param   array
730
     * @return  string
731
     */
732
    private function buildQueryString($params)
733
    {
734
        $param = array();
735
        $query_string = null;
736
737
        foreach ($params as $key => $value) {
738
            if (!empty($value)) {
739
                $param[$key] = $value;
740
            }
741
        }
742
743
        if (!empty($param)) {
744
            $query_string = '?' . http_build_query($param);
745
        }
746
747
        return $query_string;
748
    }
749
750
    /**
751
     * TwitchAPI request
752
     * @param   string
753
     * @param   string
754
     * @param   string
755
     * @return  stdClass
756
     * @throws  \ritero\SDK\TwitchTV\TwitchException
757
     */
758
    private function request($uri, $method = 'GET', $postfields = null)
759
    {
760
        $params = ['CURLOPT_SSL_VERIFYPEER'];
761
        return $this->generalRequest($params, self::URL_TWITCH . $uri, $method, $postfields);
762
    }
763
764
    /**
765
     * Twitch Team API request
766
     * @param   string
767
     * @param   string
768
     * @param   string
769
     * @return  stdClass
770
     * @throws  \ritero\SDK\TwitchTV\TwitchException
771
     */
772
    private function teamRequest($uri, $method = 'GET', $postfields = null)
773
    {
774
        return $this->generalRequest([], self::URL_TWITCH_TEAM . $uri . '.json', $method, $postfields);
775
    }
776
777
    /**
778
     * TwitchAPI request
779
     * method used by teamRequest && request methods
780
     * because there are two different Twitch APIs
781
     * don't call it directly
782
     * @param   array
783
     * @param   string
784
     * @param   string
785
     * @param   string
786
     * @return  stdClass
787
     * @throws  \ritero\SDK\TwitchTV\TwitchException
788
     */
789
    private function generalRequest($params, $uri, $method = 'GET', $postfields = null)
790
    {
791
        $this->http_info = array();
792
793
        $crl = curl_init();
794
        curl_setopt($crl, CURLOPT_USERAGENT, $this->useragent);
795
        curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);
796
        curl_setopt($crl, CURLOPT_TIMEOUT, $this->timeout);
797
        curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
798
        curl_setopt($crl, CURLOPT_HTTPHEADER, array('Expect:', 'Client-ID: ' . $this->getClientId()));
799
        if (isset($params['CURLOPT_SSL_VERIFYPEER'])) {
800
            curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
801
        }
802
        curl_setopt($crl, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
803
        curl_setopt($crl, CURLOPT_HEADER, false);
804
805
        switch ($method) {
806
            case 'POST':
807
                curl_setopt($crl, CURLOPT_POST, true);
808
                if (!is_null($postfields)) {
809
                    curl_setopt($crl, CURLOPT_POSTFIELDS, ltrim($postfields, '?'));
810
                }
811
                break;
812 View Code Duplication
            case 'PUT':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
813
                curl_setopt($crl, CURLOPT_CUSTOMREQUEST, 'PUT');
814
                curl_setopt($crl, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($postfields)));
815
                if (!is_null($postfields)) {
816
                    curl_setopt($crl, CURLOPT_POSTFIELDS, ltrim($postfields, '?'));
817
                }
818
                break;
819 View Code Duplication
            case 'DELETE':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
820
                curl_setopt($crl, CURLOPT_CUSTOMREQUEST, 'DELETE');
821
                curl_setopt($crl, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($postfields)));
822
                if (!is_null($postfields)) {
823
                    curl_setopt($crl, CURLOPT_POSTFIELDS, ltrim($postfields, '?'));
824
                }
825
        }
826
827
        curl_setopt($crl, CURLOPT_URL, $uri);
828
829
        $response = curl_exec($crl);
830
831
        $this->http_code = curl_getinfo($crl, CURLINFO_HTTP_CODE);
832
        $this->http_info = array_merge($this->http_info, curl_getinfo($crl));
833
834
        if (curl_errno($crl) && $this->throw_curl_errors === true) {
835
            throw new TwitchException(curl_error($crl), curl_errno($crl));
836
        }
837
838
        curl_close($crl);
839
840
        return json_decode($response);
841
    }
842
843
    /**
844
     * Get the header info to store
845
     */
846
    private function getHeader($ch, $header)
847
    {
848
        $i = strpos($header, ':');
849
        if (!empty($i)) {
850
            $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
851
            $value = trim(substr($header, $i + 2));
852
            $this->http_header[$key] = $value;
853
        }
854
855
        return strlen($header);
856
    }
857
858
    /**
859
     * Configuration exception
860
     * @throws  \ritero\SDK\TwitchTV\TwitchException
861
     */
862
    private function authConfigException()
863
    {
864
        throw new TwitchException('Cannot call authenticate functions without valid API configuration');
865
    }
866
}
867