Facebook::sendBatchRequest()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 1
nop 3
dl 0
loc 12
ccs 0
cts 9
cp 0
crap 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright 2017 Facebook, Inc.
4
 *
5
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
6
 * use, copy, modify, and distribute this software in source code or binary
7
 * form for use in connection with the web services and APIs provided by
8
 * Facebook.
9
 *
10
 * As with any software that integrates with the Facebook platform, your use
11
 * of this software is subject to the Facebook Developer Principles and
12
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
13
 * shall be included in all copies or substantial portions of the software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
 * DEALINGS IN THE SOFTWARE.
22
 */
23
namespace Facebook;
24
25
use Facebook\Authentication\AccessToken;
26
use Facebook\Authentication\OAuth2Client;
27
use Facebook\FileUpload\File;
28
use Facebook\FileUpload\ResumableUploader;
29
use Facebook\FileUpload\TransferChunk;
30
use Facebook\FileUpload\Video;
31
use Facebook\GraphNode\GraphEdge;
32
use Facebook\Url\UrlDetectionInterface;
33
use Facebook\Url\UrlDetectionHandler;
34
use Facebook\PersistentData\PersistentDataFactory;
35
use Facebook\PersistentData\PersistentDataInterface;
36
use Facebook\Helper\CanvasHelper;
37
use Facebook\Helper\JavaScriptHelper;
38
use Facebook\Helper\PageTabHelper;
39
use Facebook\Helper\RedirectLoginHelper;
40
use Facebook\Exception\SDKException;
41
use Http\Client\HttpClient;
42
43
/**
44
 * @package Facebook
45
 */
46
class Facebook
47
{
48
    /**
49
     * @const string Version number of the Facebook PHP SDK.
50
     */
51
    const VERSION = '6.0-dev';
52
53
    /**
54
     * @const string The name of the environment variable that contains the app ID.
55
     */
56
    const APP_ID_ENV_NAME = 'FACEBOOK_APP_ID';
57
58
    /**
59
     * @const string The name of the environment variable that contains the app secret.
60
     */
61
    const APP_SECRET_ENV_NAME = 'FACEBOOK_APP_SECRET';
62
63
    /**
64
     * @var Application the Application entity
65
     */
66
    protected $app;
67
68
    /**
69
     * @var Client the Facebook client service
70
     */
71
    protected $client;
72
73
    /**
74
     * @var OAuth2Client The OAuth 2.0 client service.
75
     */
76
    protected $oAuth2Client;
77
78
    /**
79
     * @var null|UrlDetectionInterface the URL detection handler
80
     */
81
    protected $urlDetectionHandler;
82
83
    /**
84
     * @var null|AccessToken the default access token to use with requests
85
     */
86
    protected $defaultAccessToken;
87
88
    /**
89
     * @var null|string the default Graph version we want to use
90
     */
91
    protected $defaultGraphVersion;
92
93
    /**
94
     * @var null|PersistentDataInterface the persistent data handler
95
     */
96
    protected $persistentDataHandler;
97
98
    /**
99
     * @var null|BatchResponse|Response stores the last request made to Graph
100
     */
101
    protected $lastResponse;
102
103
    /**
104
     * Instantiates a new Facebook super-class object.
105
     *
106
     * @param array $config
107
     *
108
     * @throws SDKException
109
     */
110 18
    public function __construct(array $config = [])
111
    {
112 18
        $config = array_merge([
113 18
            'app_id' => getenv(static::APP_ID_ENV_NAME),
114 18
            'app_secret' => getenv(static::APP_SECRET_ENV_NAME),
115
            'default_graph_version' => null,
116
            'enable_beta_mode' => false,
117
            'http_client' => null,
118
            'persistent_data_handler' => null,
119
            'url_detection_handler' => null,
120 18
        ], $config);
121
122 18
        if (!$config['app_id']) {
123 1
            throw new SDKException('Required "app_id" key not supplied in config and could not find fallback environment variable "' . static::APP_ID_ENV_NAME . '"');
124
        }
125 17
        if (!$config['app_secret']) {
126 1
            throw new SDKException('Required "app_secret" key not supplied in config and could not find fallback environment variable "' . static::APP_SECRET_ENV_NAME . '"');
127
        }
128 16
        if ($config['http_client'] !== null && !$config['http_client'] instanceof HttpClient) {
129 2
            throw new \InvalidArgumentException('Required "http_client" key to be null or an instance of \Http\Client\HttpClient');
130
        }
131 14
        if (!$config['default_graph_version']) {
132 1
            throw new \InvalidArgumentException('Required "default_graph_version" key not supplied in config');
133
        }
134
135 13
        $this->app = new Application($config['app_id'], $config['app_secret']);
136 13
        $this->client = new Client(
137 13
            $config['http_client'],
138 13
            $config['enable_beta_mode']
139
        );
140 13
        $this->setUrlDetectionHandler($config['url_detection_handler'] ?: new UrlDetectionHandler());
141 12
        $this->persistentDataHandler = PersistentDataFactory::createPersistentDataHandler(
142 12
            $config['persistent_data_handler']
143
        );
144
145 11
        if (isset($config['default_access_token'])) {
146 3
            $this->setDefaultAccessToken($config['default_access_token']);
147
        }
148
149 10
        $this->defaultGraphVersion = $config['default_graph_version'];
150 10
    }
151
152
    /**
153
     * Returns the Application entity.
154
     *
155
     * @return Application
156
     */
157 3
    public function getApplication()
158
    {
159 3
        return $this->app;
160
    }
161
162
    /**
163
     * Returns the Client service.
164
     *
165
     * @return Client
166
     */
167 4
    public function getClient()
168
    {
169 4
        return $this->client;
170
    }
171
172
    /**
173
     * Returns the OAuth 2.0 client service.
174
     *
175
     * @return OAuth2Client
176
     */
177 2
    public function getOAuth2Client()
178
    {
179 2
        if (!$this->oAuth2Client instanceof OAuth2Client) {
0 ignored issues
show
introduced by
$this->oAuth2Client is always a sub-type of Facebook\Authentication\OAuth2Client. If $this->oAuth2Client can have other possible types, add them to src/Facebook.php:74.
Loading history...
180 2
            $app = $this->getApplication();
181 2
            $client = $this->getClient();
182 2
            $this->oAuth2Client = new OAuth2Client($app, $client, $this->defaultGraphVersion);
183
        }
184
185 2
        return $this->oAuth2Client;
186
    }
187
188
    /**
189
     * Returns the last response returned from Graph.
190
     *
191
     * @return null|BatchResponse|Response
192
     */
193 1
    public function getLastResponse()
194
    {
195 1
        return $this->lastResponse;
196
    }
197
198
    /**
199
     * Returns the URL detection handler.
200
     *
201
     * @return UrlDetectionInterface
202
     */
203 1
    public function getUrlDetectionHandler()
204
    {
205 1
        return $this->urlDetectionHandler;
206
    }
207
208
    /**
209
     * Changes the URL detection handler.
210
     *
211
     * @param UrlDetectionInterface $urlDetectionHandler
212
     */
213 12
    private function setUrlDetectionHandler(UrlDetectionInterface $urlDetectionHandler)
214
    {
215 12
        $this->urlDetectionHandler = $urlDetectionHandler;
216 12
    }
217
218
    /**
219
     * Returns the default AccessToken entity.
220
     *
221
     * @return null|AccessToken
222
     */
223 2
    public function getDefaultAccessToken()
224
    {
225 2
        return $this->defaultAccessToken;
226
    }
227
228
    /**
229
     * Sets the default access token to use with requests.
230
     *
231
     * @param AccessToken|string $accessToken the access token to save
232
     *
233
     * @throws \InvalidArgumentException
234
     */
235 5
    public function setDefaultAccessToken($accessToken)
236
    {
237 5
        if (is_string($accessToken)) {
238 3
            $this->defaultAccessToken = new AccessToken($accessToken);
239
240 3
            return;
241
        }
242
243 2
        if ($accessToken instanceof AccessToken) {
0 ignored issues
show
introduced by
$accessToken is always a sub-type of Facebook\Authentication\AccessToken.
Loading history...
244 1
            $this->defaultAccessToken = $accessToken;
245
246 1
            return;
247
        }
248
249 1
        throw new \InvalidArgumentException('The default access token must be of type "string" or Facebook\AccessToken');
250
    }
251
252
    /**
253
     * Returns the default Graph version.
254
     *
255
     * @return string
256
     */
257
    public function getDefaultGraphVersion()
258
    {
259
        return $this->defaultGraphVersion;
260
    }
261
262
    /**
263
     * Returns the redirect login helper.
264
     *
265
     * @return RedirectLoginHelper
266
     */
267 2
    public function getRedirectLoginHelper()
268
    {
269 2
        return new RedirectLoginHelper(
270 2
            $this->getOAuth2Client(),
271 2
            $this->persistentDataHandler,
272 2
            $this->urlDetectionHandler
273
        );
274
    }
275
276
    /**
277
     * Returns the JavaScript helper.
278
     *
279
     * @return JavaScriptHelper
280
     */
281
    public function getJavaScriptHelper()
282
    {
283
        return new JavaScriptHelper($this->app, $this->client, $this->defaultGraphVersion);
284
    }
285
286
    /**
287
     * Returns the canvas helper.
288
     *
289
     * @return CanvasHelper
290
     */
291
    public function getCanvasHelper()
292
    {
293
        return new CanvasHelper($this->app, $this->client, $this->defaultGraphVersion);
294
    }
295
296
    /**
297
     * Returns the page tab helper.
298
     *
299
     * @return PageTabHelper
300
     */
301
    public function getPageTabHelper()
302
    {
303
        return new PageTabHelper($this->app, $this->client, $this->defaultGraphVersion);
304
    }
305
306
    /**
307
     * Sends a GET request to Graph and returns the result.
308
     *
309
     * @param string                  $endpoint
310
     * @param null|AccessToken|string $accessToken
311
     * @param null|string             $eTag
312
     * @param null|string             $graphVersion
313
     *
314
     * @throws SDKException
315
     *
316
     * @return Response
317
     */
318
    public function get($endpoint, $accessToken = null, $eTag = null, $graphVersion = null)
319
    {
320
        return $this->sendRequest(
321
            'GET',
322
            $endpoint,
323
            $params = [],
324
            $accessToken,
325
            $eTag,
326
            $graphVersion
327
        );
328
    }
329
330
    /**
331
     * Sends a POST request to Graph and returns the result.
332
     *
333
     * @param string                  $endpoint
334
     * @param array                   $params
335
     * @param null|AccessToken|string $accessToken
336
     * @param null|string             $eTag
337
     * @param null|string             $graphVersion
338
     *
339
     * @throws SDKException
340
     *
341
     * @return Response
342
     */
343
    public function post($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
344
    {
345
        return $this->sendRequest(
346
            'POST',
347
            $endpoint,
348
            $params,
349
            $accessToken,
350
            $eTag,
351
            $graphVersion
352
        );
353
    }
354
355
    /**
356
     * Sends a DELETE request to Graph and returns the result.
357
     *
358
     * @param string                  $endpoint
359
     * @param array                   $params
360
     * @param null|AccessToken|string $accessToken
361
     * @param null|string             $eTag
362
     * @param null|string             $graphVersion
363
     *
364
     * @throws SDKException
365
     *
366
     * @return Response
367
     */
368
    public function delete($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
369
    {
370
        return $this->sendRequest(
371
            'DELETE',
372
            $endpoint,
373
            $params,
374
            $accessToken,
375
            $eTag,
376
            $graphVersion
377
        );
378
    }
379
380
    /**
381
     * Sends a request to Graph for the next page of results.
382
     *
383
     * @param GraphEdge $graphEdge the GraphEdge to paginate over
384
     *
385
     * @throws SDKException
386
     *
387
     * @return null|GraphEdge
388
     */
389 1
    public function next(GraphEdge $graphEdge)
390
    {
391 1
        return $this->getPaginationResults($graphEdge, 'next');
392
    }
393
394
    /**
395
     * Sends a request to Graph for the previous page of results.
396
     *
397
     * @param GraphEdge $graphEdge the GraphEdge to paginate over
398
     *
399
     * @throws SDKException
400
     *
401
     * @return null|GraphEdge
402
     */
403
    public function previous(GraphEdge $graphEdge)
404
    {
405
        return $this->getPaginationResults($graphEdge, 'previous');
406
    }
407
408
    /**
409
     * Sends a request to Graph for the next page of results.
410
     *
411
     * @param GraphEdge $graphEdge the GraphEdge to paginate over
412
     * @param string    $direction the direction of the pagination: next|previous
413
     *
414
     * @throws SDKException
415
     *
416
     * @return null|GraphEdge
417
     */
418 1
    public function getPaginationResults(GraphEdge $graphEdge, $direction)
419
    {
420 1
        $paginationRequest = $graphEdge->getPaginationRequest($direction);
421 1
        if (!$paginationRequest) {
422
            return null;
423
        }
424
425 1
        $this->lastResponse = $this->client->sendRequest($paginationRequest);
426
427
        // Keep the same GraphNode subclass
428 1
        $subClassName = $graphEdge->getSubClassName();
429 1
        $graphEdge = $this->lastResponse->getGraphEdge($subClassName, false);
430
431 1
        return count($graphEdge) > 0 ? $graphEdge : null;
432
    }
433
434
    /**
435
     * Sends a request to Graph and returns the result.
436
     *
437
     * @param string                  $method
438
     * @param string                  $endpoint
439
     * @param array                   $params
440
     * @param null|AccessToken|string $accessToken
441
     * @param null|string             $eTag
442
     * @param null|string             $graphVersion
443
     *
444
     * @throws SDKException
445
     *
446
     * @return Response
447
     */
448
    public function sendRequest($method, $endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
449
    {
450
        $accessToken = $accessToken ?: $this->defaultAccessToken;
451
        $graphVersion = $graphVersion ?: $this->defaultGraphVersion;
452
        $request = $this->request($method, $endpoint, $params, $accessToken, $eTag, $graphVersion);
453
454
        return $this->lastResponse = $this->client->sendRequest($request);
455
    }
456
457
    /**
458
     * Sends a batched request to Graph and returns the result.
459
     *
460
     * @param array                   $requests
461
     * @param null|AccessToken|string $accessToken
462
     * @param null|string             $graphVersion
463
     *
464
     * @throws SDKException
465
     *
466
     * @return BatchResponse
467
     */
468
    public function sendBatchRequest(array $requests, $accessToken = null, $graphVersion = null)
469
    {
470
        $accessToken = $accessToken ?: $this->defaultAccessToken;
471
        $graphVersion = $graphVersion ?: $this->defaultGraphVersion;
472
        $batchRequest = new BatchRequest(
473
            $this->app,
474
            $requests,
475
            $accessToken,
476
            $graphVersion
477
        );
478
479
        return $this->lastResponse = $this->client->sendBatchRequest($batchRequest);
480
    }
481
482
    /**
483
     * Instantiates an empty BatchRequest entity.
484
     *
485
     * @param null|AccessToken|string $accessToken  The top-level access token. Requests with no access token
486
     *                                              will fallback to this.
487
     * @param null|string             $graphVersion the Graph API version to use
488
     *
489
     * @return BatchRequest
490
     */
491 1
    public function newBatchRequest($accessToken = null, $graphVersion = null)
492
    {
493 1
        $accessToken = $accessToken ?: $this->defaultAccessToken;
494 1
        $graphVersion = $graphVersion ?: $this->defaultGraphVersion;
495
496 1
        return new BatchRequest(
497 1
            $this->app,
498 1
            [],
499 1
            $accessToken,
500 1
            $graphVersion
501
        );
502
    }
503
504
    /**
505
     * Instantiates a new Request entity.
506
     *
507
     * @param string                  $method
508
     * @param string                  $endpoint
509
     * @param array                   $params
510
     * @param null|AccessToken|string $accessToken
511
     * @param null|string             $eTag
512
     * @param null|string             $graphVersion
513
     *
514
     * @throws SDKException
515
     *
516
     * @return Request
517
     */
518 1
    public function request($method, $endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
519
    {
520 1
        $accessToken = $accessToken ?: $this->defaultAccessToken;
521 1
        $graphVersion = $graphVersion ?: $this->defaultGraphVersion;
522
523 1
        return new Request(
524 1
            $this->app,
525 1
            $accessToken,
526 1
            $method,
527 1
            $endpoint,
528 1
            $params,
529 1
            $eTag,
530 1
            $graphVersion
531
        );
532
    }
533
534
    /**
535
     * Factory to create File's.
536
     *
537
     * @param string $pathToFile
538
     *
539
     * @throws SDKException
540
     *
541
     * @return File
542
     */
543
    public function fileToUpload($pathToFile)
544
    {
545
        return new File($pathToFile);
546
    }
547
548
    /**
549
     * Factory to create Video's.
550
     *
551
     * @param string $pathToFile
552
     *
553
     * @throws SDKException
554
     *
555
     * @return Video
556
     */
557 2
    public function videoToUpload($pathToFile)
558
    {
559 2
        return new Video($pathToFile);
560
    }
561
562
    /**
563
     * Upload a video in chunks.
564
     *
565
     * @param int         $target           the id of the target node before the /videos edge
566
     * @param string      $pathToFile       the full path to the file
567
     * @param array       $metadata         the metadata associated with the video file
568
     * @param null|string $accessToken      the access token
569
     * @param int         $maxTransferTries the max times to retry a failed upload chunk
570
     * @param null|string $graphVersion     the Graph API version to use
571
     *
572
     * @throws SDKException
573
     *
574
     * @return array
575
     */
576 2
    public function uploadVideo($target, $pathToFile, $metadata = [], $accessToken = null, $maxTransferTries = 5, $graphVersion = null)
577
    {
578 2
        $accessToken = $accessToken ?: $this->defaultAccessToken;
579 2
        $graphVersion = $graphVersion ?: $this->defaultGraphVersion;
580
581 2
        $uploader = new ResumableUploader($this->app, $this->client, $accessToken, $graphVersion);
582 2
        $endpoint = '/'.$target.'/videos';
583 2
        $file = $this->videoToUpload($pathToFile);
584 2
        $chunk = $uploader->start($endpoint, $file);
585
586
        do {
587 2
            $chunk = $this->maxTriesTransfer($uploader, $endpoint, $chunk, $maxTransferTries);
588 1
        } while (!$chunk->isLastChunk());
589
590
        return [
591 1
          'video_id' => $chunk->getVideoId(),
592 1
          'success' => $uploader->finish($endpoint, $chunk->getUploadSessionId(), $metadata),
593
        ];
594
    }
595
596
    /**
597
     * Attempts to upload a chunk of a file in $retryCountdown tries.
598
     *
599
     * @param ResumableUploader $uploader
600
     * @param string            $endpoint
601
     * @param TransferChunk     $chunk
602
     * @param int               $retryCountdown
603
     *
604
     * @throws SDKException
605
     *
606
     * @return TransferChunk
607
     */
608 2
    private function maxTriesTransfer(ResumableUploader $uploader, $endpoint, TransferChunk $chunk, $retryCountdown)
609
    {
610 2
        $newChunk = $uploader->transfer($endpoint, $chunk, $retryCountdown < 1);
611
612 2
        if ($newChunk !== $chunk) {
613 1
            return $newChunk;
614
        }
615
616 1
        $retryCountdown--;
617
618
        // If transfer() returned the same chunk entity, the transfer failed but is resumable.
619 1
        return $this->maxTriesTransfer($uploader, $endpoint, $chunk, $retryCountdown);
620
    }
621
}
622