From 74890cad008e5a27e240ba615075a37e3891c7c6 Mon Sep 17 00:00:00 2001 From: "rusakov.vv" Date: Tue, 11 Jan 2022 22:50:01 +0300 Subject: [PATCH] Add PHP 8.1 Support --- composer.json | 12 +- docs/reference/FacebookApp.md | 6 +- docs/reference/FacebookBatchRequest.md | 6 +- docs/reference/FacebookClient.md | 2 +- docs/reference/FacebookFile.md | 4 +- docs/reference/FacebookRequest.md | 8 +- docs/reference/FacebookVideo.md | 4 +- docs/reference/PersistentDataInterface.md | 4 +- .../PseudoRandomStringGeneratorInterface.md | 4 +- docs/reference/SignedRequest.md | 4 +- docs/reference/UrlDetectionInterface.md | 4 +- .../{FacebookApp.php => Application.php} | 49 +-- src/Facebook/Authentication/OAuth2Client.php | 120 ++++--- ...ebookBatchRequest.php => BatchRequest.php} | 30 +- ...ookBatchResponse.php => BatchResponse.php} | 14 +- .../{FacebookClient.php => Client.php} | 107 +++--- .../Exceptions/FacebookResponseException.php | 14 +- src/Facebook/Facebook.php | 309 ++++++++++-------- .../FileUpload/{FacebookFile.php => File.php} | 2 +- ...ableUploader.php => ResumableUploader.php} | 42 +-- ...ookTransferChunk.php => TransferChunk.php} | 22 +- .../{FacebookVideo.php => Video.php} | 2 +- src/Facebook/GraphNodes/GraphAchievement.php | 2 +- src/Facebook/GraphNodes/GraphAlbum.php | 2 +- src/Facebook/GraphNodes/GraphEdge.php | 22 +- src/Facebook/GraphNodes/GraphEvent.php | 2 +- src/Facebook/GraphNodes/GraphGroup.php | 2 +- src/Facebook/GraphNodes/GraphList.php | 36 -- src/Facebook/GraphNodes/GraphNode.php | 151 ++++++--- src/Facebook/GraphNodes/GraphNodeFactory.php | 126 ++++--- src/Facebook/GraphNodes/GraphObject.php | 36 -- .../GraphNodes/GraphObjectFactory.php | 88 ----- src/Facebook/GraphNodes/GraphPage.php | 2 +- src/Facebook/GraphNodes/GraphUser.php | 2 +- ...ebookCanvasHelper.php => CanvasHelper.php} | 2 +- .../FacebookSignedRequestFromInputHelper.php | 14 +- ...aScriptHelper.php => JavaScriptHelper.php} | 2 +- ...ookPageTabHelper.php => PageTabHelper.php} | 14 +- ...oginHelper.php => RedirectLoginHelper.php} | 113 +++---- src/Facebook/Http/RequestBodyMultipart.php | 14 +- src/Facebook/Http/RequestBodyUrlEncoded.php | 6 +- src/Facebook/HttpClients/FacebookCurl.php | 129 -------- .../HttpClients/FacebookCurlHttpClient.php | 163 --------- .../HttpClients/FacebookGuzzleHttpClient.php | 97 ------ .../FacebookHttpClientInterface.php | 47 --- src/Facebook/HttpClients/FacebookStream.php | 80 ----- .../HttpClients/FacebookStreamHttpClient.php | 94 ------ .../HttpClients/HttpClientsFactory.php | 99 ------ .../certs/DigiCertHighAssuranceEVRootCA.pem | 23 -- .../McryptPseudoRandomStringGenerator.php | 68 ---- .../OpenSslPseudoRandomStringGenerator.php | 67 ---- .../PseudoRandomStringGeneratorFactory.php | 101 ------ .../PseudoRandomStringGeneratorInterface.php | 45 --- .../PseudoRandomStringGeneratorTrait.php | 58 ---- ...RandomBytesPseudoRandomStringGenerator.php | 59 ---- .../UrandomPseudoRandomStringGenerator.php | 89 ----- .../{FacebookRequest.php => Request.php} | 190 ++++++----- .../{FacebookResponse.php => Response.php} | 161 ++++----- src/Facebook/SignedRequest.php | 6 +- src/Facebook/Url/FacebookUrlManipulator.php | 2 +- ...ionHandler.php => UrlDetectionHandler.php} | 2 +- src/Facebook/autoload.php | 81 ----- src/Facebook/polyfills.php | 49 --- ...acebookAppTest.php => ApplicationTest.php} | 55 ++-- .../AccessTokenMetadataTest.php | 60 ++-- tests/Authentication/AccessTokenTest.php | 32 +- ...th2Test.php => FooClientForOAuth2Test.php} | 17 +- tests/Authentication/OAuth2ClientTest.php | 60 ++-- ...chRequestTest.php => BatchRequestTest.php} | 250 +++++++------- ...ResponseTest.php => BatchResponseTest.php} | 130 ++++---- tests/ClientTest.php | 297 +++++++++++++++++ .../FacebookResponseExceptionTest.php | 278 ---------------- tests/Exceptions/ResponseExceptionTest.php | 291 +++++++++++++++++ tests/FacebookClientTest.php | 294 ----------------- tests/FacebookRequestTest.php | 207 ------------ tests/FacebookTest.php | 292 +++++------------ .../{FacebookFileTest.php => FileTest.php} | 27 +- tests/FileUpload/MimetypesTest.php | 14 +- ...aderTest.php => ResumableUploaderTest.php} | 73 +++-- .../FakeGraphApiForResumableUpload.php | 90 +++-- .../FooBarPseudoRandomStringGenerator.php | 34 -- tests/Fixtures/FooClientInterface.php | 32 +- tests/Fixtures/FooPersistentDataInterface.php | 21 +- .../FooPseudoRandomStringGenerator.php | 34 -- .../Fixtures/FooRedirectLoginOAuth2Client.php | 17 +- tests/Fixtures/FooSignedRequestHelper.php | 13 +- ...t.php => FooSignedRequestHelperClient.php} | 18 +- tests/Fixtures/FooUrlDetectionInterface.php | 8 +- .../MyFooBarPseudoRandomStringGenerator.php | 31 -- tests/Fixtures/MyFooBatchClientHandler.php | 23 +- tests/Fixtures/MyFooClientHandler.php | 23 +- tests/Fixtures/MyFooGraphNode.php | 10 +- tests/Fixtures/MyFooSubClassGraphNode.php | 6 + tests/GraphNodes/AbstractGraphNode.php | 39 ++- tests/GraphNodes/CollectionTest.php | 48 ++- tests/GraphNodes/GraphAchievementTest.php | 20 +- tests/GraphNodes/GraphAlbumTest.php | 54 +-- tests/GraphNodes/GraphEdgeTest.php | 177 ++++++++-- tests/GraphNodes/GraphEventTest.php | 71 ++-- tests/GraphNodes/GraphGroupTest.php | 75 ----- tests/GraphNodes/GraphNodeFactoryTest.php | 196 +++++------ tests/GraphNodes/GraphNodeTest.php | 203 ++++++++---- tests/GraphNodes/GraphObjectFactoryTest.php | 114 ------- tests/GraphNodes/GraphPageTest.php | 95 ------ tests/GraphNodes/GraphSessionInfoTest.php | 62 ---- tests/GraphNodes/GraphUserTest.php | 204 ------------ ...vasHelperTest.php => CanvasHelperTest.php} | 31 +- ...elperTest.php => JavaScriptHelperTest.php} | 25 +- ...abHelperTest.php => PageTabHelperTest.php} | 31 +- ...erTest.php => RedirectLoginHelperTest.php} | 68 ++-- ...p => SignedRequestFromInputHelperTest.php} | 51 +-- tests/Http/GraphRawResponseTest.php | 46 +-- tests/Http/RequestBodyMultipartTest.php | 32 +- tests/Http/RequestUrlEncodedTest.php | 20 +- tests/HttpClients/AbstractTestHttpClient.php | 60 ---- .../FacebookCurlHttpClientTest.php | 283 ---------------- .../FacebookGuzzleHttpClientTest.php | 143 -------- .../FacebookStreamHttpClientTest.php | 134 -------- tests/HttpClients/HttpClientsFactoryTest.php | 72 ---- ...cebookSessionPersistentDataHandlerTest.php | 33 +- ...hp => MemoryPersistentDataHandlerTest.php} | 16 +- .../PersistentDataFactoryTest.php | 20 +- .../McryptPseudoRandomStringGeneratorTest.php | 48 --- ...OpenSslPseudoRandomStringGeneratorTest.php | 44 --- .../PseudoRandomStringFactoryTest.php | 71 ---- .../PseudoRandomStringGeneratorTraitTest.php | 47 --- ...omBytesPseudoRandomStringGeneratorTest.php | 44 --- ...UrandomPseudoRandomStringGeneratorTest.php | 50 --- tests/RequestTest.php | 205 ++++++++++++ ...ebookResponseTest.php => ResponseTest.php} | 74 +++-- tests/SignedRequestTest.php | 73 ++--- ...erTest.php => UrlDetectionHandlerTest.php} | 52 +-- ...pulatorTest.php => UrlManipulatorTest.php} | 69 ++-- tests/bootstrap.php | 2 + 134 files changed, 3099 insertions(+), 5955 deletions(-) rename src/Facebook/{FacebookApp.php => Application.php} (65%) rename src/Facebook/{FacebookBatchRequest.php => BatchRequest.php} (90%) rename src/Facebook/{FacebookBatchResponse.php => BatchResponse.php} (90%) rename src/Facebook/{FacebookClient.php => Client.php} (61%) rename src/Facebook/FileUpload/{FacebookFile.php => File.php} (99%) rename src/Facebook/FileUpload/{FacebookResumableUploader.php => ResumableUploader.php} (77%) rename src/Facebook/FileUpload/{FacebookTransferChunk.php => TransferChunk.php} (85%) rename src/Facebook/FileUpload/{FacebookVideo.php => Video.php} (96%) delete mode 100644 src/Facebook/GraphNodes/GraphList.php delete mode 100644 src/Facebook/GraphNodes/GraphObject.php delete mode 100644 src/Facebook/GraphNodes/GraphObjectFactory.php rename src/Facebook/Helpers/{FacebookCanvasHelper.php => CanvasHelper.php} (95%) rename src/Facebook/Helpers/{FacebookJavaScriptHelper.php => JavaScriptHelper.php} (94%) rename src/Facebook/Helpers/{FacebookPageTabHelper.php => PageTabHelper.php} (84%) rename src/Facebook/Helpers/{FacebookRedirectLoginHelper.php => RedirectLoginHelper.php} (70%) delete mode 100644 src/Facebook/HttpClients/FacebookCurl.php delete mode 100644 src/Facebook/HttpClients/FacebookCurlHttpClient.php delete mode 100644 src/Facebook/HttpClients/FacebookGuzzleHttpClient.php delete mode 100644 src/Facebook/HttpClients/FacebookHttpClientInterface.php delete mode 100644 src/Facebook/HttpClients/FacebookStream.php delete mode 100644 src/Facebook/HttpClients/FacebookStreamHttpClient.php delete mode 100644 src/Facebook/HttpClients/HttpClientsFactory.php delete mode 100644 src/Facebook/HttpClients/certs/DigiCertHighAssuranceEVRootCA.pem delete mode 100644 src/Facebook/PseudoRandomString/McryptPseudoRandomStringGenerator.php delete mode 100644 src/Facebook/PseudoRandomString/OpenSslPseudoRandomStringGenerator.php delete mode 100644 src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorFactory.php delete mode 100644 src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorInterface.php delete mode 100644 src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorTrait.php delete mode 100644 src/Facebook/PseudoRandomString/RandomBytesPseudoRandomStringGenerator.php delete mode 100644 src/Facebook/PseudoRandomString/UrandomPseudoRandomStringGenerator.php rename src/Facebook/{FacebookRequest.php => Request.php} (69%) rename src/Facebook/{FacebookResponse.php => Response.php} (64%) rename src/Facebook/Url/{FacebookUrlDetectionHandler.php => UrlDetectionHandler.php} (98%) delete mode 100644 src/Facebook/autoload.php delete mode 100644 src/Facebook/polyfills.php rename tests/{FacebookAppTest.php => ApplicationTest.php} (52%) rename tests/Authentication/{FooFacebookClientForOAuth2Test.php => FooClientForOAuth2Test.php} (85%) rename tests/{FacebookBatchRequestTest.php => BatchRequestTest.php} (57%) mode change 100755 => 100644 rename tests/{FacebookBatchResponseTest.php => BatchResponseTest.php} (57%) mode change 100755 => 100644 create mode 100644 tests/ClientTest.php delete mode 100644 tests/Exceptions/FacebookResponseExceptionTest.php create mode 100644 tests/Exceptions/ResponseExceptionTest.php delete mode 100644 tests/FacebookClientTest.php delete mode 100755 tests/FacebookRequestTest.php rename tests/FileUpload/{FacebookFileTest.php => FileTest.php} (71%) rename tests/FileUpload/{FacebookResumableUploaderTest.php => ResumableUploaderTest.php} (55%) delete mode 100644 tests/Fixtures/FooBarPseudoRandomStringGenerator.php delete mode 100644 tests/Fixtures/FooPseudoRandomStringGenerator.php rename tests/Fixtures/{FooSignedRequestHelperFacebookClient.php => FooSignedRequestHelperClient.php} (82%) delete mode 100644 tests/Fixtures/MyFooBarPseudoRandomStringGenerator.php delete mode 100644 tests/GraphNodes/GraphGroupTest.php delete mode 100644 tests/GraphNodes/GraphObjectFactoryTest.php delete mode 100644 tests/GraphNodes/GraphPageTest.php delete mode 100644 tests/GraphNodes/GraphSessionInfoTest.php delete mode 100644 tests/GraphNodes/GraphUserTest.php rename tests/Helpers/{FacebookCanvasHelperTest.php => CanvasHelperTest.php} (64%) rename tests/Helpers/{FacebookJavaScriptHelperTest.php => JavaScriptHelperTest.php} (66%) rename tests/Helpers/{FacebookPageTabHelperTest.php => PageTabHelperTest.php} (56%) rename tests/Helpers/{FacebookRedirectLoginHelperTest.php => RedirectLoginHelperTest.php} (63%) rename tests/Helpers/{FacebookSignedRequestFromInputHelperTest.php => SignedRequestFromInputHelperTest.php} (58%) delete mode 100644 tests/HttpClients/AbstractTestHttpClient.php delete mode 100644 tests/HttpClients/FacebookCurlHttpClientTest.php delete mode 100644 tests/HttpClients/FacebookGuzzleHttpClientTest.php delete mode 100644 tests/HttpClients/FacebookStreamHttpClientTest.php delete mode 100644 tests/HttpClients/HttpClientsFactoryTest.php rename tests/PersistentData/{FacebookMemoryPersistentDataHandlerTest.php => MemoryPersistentDataHandlerTest.php} (83%) delete mode 100644 tests/PseudoRandomString/McryptPseudoRandomStringGeneratorTest.php delete mode 100644 tests/PseudoRandomString/OpenSslPseudoRandomStringGeneratorTest.php delete mode 100644 tests/PseudoRandomString/PseudoRandomStringFactoryTest.php delete mode 100644 tests/PseudoRandomString/PseudoRandomStringGeneratorTraitTest.php delete mode 100644 tests/PseudoRandomString/RandomBytesPseudoRandomStringGeneratorTest.php delete mode 100644 tests/PseudoRandomString/UrandomPseudoRandomStringGeneratorTest.php create mode 100644 tests/RequestTest.php rename tests/{FacebookResponseTest.php => ResponseTest.php} (55%) mode change 100755 => 100644 rename tests/Url/{FacebookUrlDetectionHandlerTest.php => UrlDetectionHandlerTest.php} (72%) rename tests/Url/{FacebookUrlManipulatorTest.php => UrlManipulatorTest.php} (78%) diff --git a/composer.json b/composer.json index 9d54abc37..7720cfe3a 100644 --- a/composer.json +++ b/composer.json @@ -12,12 +12,13 @@ } ], "require": { - "php": "^5.4|^7.0" + "php": "^8.1", + "guzzlehttp/guzzle": "^7.4" }, "require-dev": { - "phpunit/phpunit": "~4.0", - "mockery/mockery": "~0.8", - "guzzlehttp/guzzle": "~5.0" + "phpunit/phpunit": "^9.5.10", + "mockery/mockery": "^1.4.4", + "phpspec/prophecy-phpunit": "^v2.0.0" }, "suggest": { "paragonie/random_compat": "Provides a better CSPRNG option in PHP 5", @@ -26,8 +27,7 @@ "autoload": { "psr-4": { "Facebook\\": "src/Facebook/" - }, - "files": ["src/Facebook/polyfills.php"] + } }, "autoload-dev": { "psr-4": { diff --git a/docs/reference/FacebookApp.md b/docs/reference/FacebookApp.md index 2506fd301..0dcbd45c5 100644 --- a/docs/reference/FacebookApp.md +++ b/docs/reference/FacebookApp.md @@ -9,14 +9,14 @@ In order to make requests to the Graph API, you need to [create a Facebook app]( To instantiate a new `Facebook\FacebookApp` entity, pass the app ID and app secret to the constructor. ```php -$fbApp = new Facebook\FacebookApp('{app-id}', '{app-secret}'); +$fbApp = new Facebook\Application('{app-id}', '{app-secret}'); ``` Alternatively you can obtain the `Facebook\FacebookApp` entity from the [`Facebook\Facebook`](Facebook.md) super service class. ```php $fb = new Facebook\Facebook([/* . . . */]); -$fbApp = $fb->getApp(); +$fbApp = $fb->getApplication(); ``` You'll rarely be using the `FacebookApp` entity directly unless you're doing some extreme customizations of the SDK for PHP. But this entity plays an important role in the internal workings of the SDK for PHP. @@ -46,7 +46,7 @@ Returns the app secret. The `Facebook\FacebookApp` entity can be serialized and unserialized. ```php -$fbApp = new Facebook\FacebookApp('foo-app-id', 'foo-app-secret'); +$fbApp = new Facebook\Application('foo-app-id', 'foo-app-secret'); $serializedFacebookApp = serialize($fbApp); // C:29:"Facebook\\FacebookApp":54:{a:2:{i:0;s:10:"foo-app-id";i:1;s:14:"foo-app-secret";}} diff --git a/docs/reference/FacebookBatchRequest.md b/docs/reference/FacebookBatchRequest.md index c3d40dc53..0ec93f09a 100644 --- a/docs/reference/FacebookBatchRequest.md +++ b/docs/reference/FacebookBatchRequest.md @@ -8,9 +8,9 @@ You can instantiate a new `FacebookBatchRequest` entity directly by sending the by using the [`Facebook\Facebook::newBatchRequest()`](Facebook.md#newBatchRequest) factory method. ```php -use Facebook\FacebookBatchRequest; +use Facebook\BatchRequest; -$request = new FacebookBatchRequest( +$request = new BatchRequest( Facebook\FacebookApp $app, array $requests, string|null $accessToken, @@ -86,7 +86,7 @@ $requests = [ 'foo' => $fb->request('GET', '/me'), 'bar' => $fb->request('POST', '/me/feed', [/* */]), ]; -$batchRequest = new Facebook\FacebookBatchRequest($fb->getApp(), $requests, '{access-token}'); +$batchRequest = new Facebook\BatchRequest($fb->getApplication(), $requests, '{access-token}'); var_dump($batchRequest[0]); /* diff --git a/docs/reference/FacebookClient.md b/docs/reference/FacebookClient.md index 91e4be8c9..5d62f7ff7 100644 --- a/docs/reference/FacebookClient.md +++ b/docs/reference/FacebookClient.md @@ -16,7 +16,7 @@ $fbClient = $fb->getClient(); Alternatively you could instantiate a new `Facebook\FacebookClient` service directly. ```php -$fbClient = new Facebook\FacebookClient($httpClientHandler, $enableBeta = false); +$fbClient = new Facebook\Client($httpClientHandler, $enableBeta = false); ``` The Graph API has a number of different base URL's based on what request you want to send. For example, if you wanted to send requests to the beta version of Graph, you'd need to send requests to [https://graph.beta.facebook.com](https://graph.beta.facebook.com) instead [https://graph.facebook.com](https://graph.facebook.com). And if you wanted to upload a video, that request would need to be sent to [https://graph-video.facebook.com](https://graph-video.facebook.com). diff --git a/docs/reference/FacebookFile.md b/docs/reference/FacebookFile.md index 304699538..6982acdd2 100644 --- a/docs/reference/FacebookFile.md +++ b/docs/reference/FacebookFile.md @@ -9,9 +9,9 @@ The `FacebookFile` entity represents a local or remote file to be uploaded with There are two ways to instantiate a `FacebookFile` entity. One way is to instantiate it directly: ```php -use Facebook\FileUpload\FacebookFile; +use Facebook\FileUpload\File; -$myFileToUpload = new FacebookFile('/path/to/file.jpg'); +$myFileToUpload = new File('/path/to/file.jpg'); ``` Alternatively, you can use the `fileToUpload()` factory on the `Facebook\Facebook` super service to instantiate a new `FacebookFile` entity. diff --git a/docs/reference/FacebookRequest.md b/docs/reference/FacebookRequest.md index cc8b7b203..cd7a65905 100644 --- a/docs/reference/FacebookRequest.md +++ b/docs/reference/FacebookRequest.md @@ -7,9 +7,9 @@ Represents a request that will be sent to the Graph API. You can instantiate a new `FacebookRequest` entity directly by sending the arguments to the constructor. ```php -use Facebook\FacebookRequest; +use Facebook\Request; -$request = new FacebookRequest( +$request = new Request( Facebook\FacebookApp $app, string $accessToken, string $method, @@ -27,8 +27,8 @@ The `FacebookRequest` entity does not actually make any calls to the Graph API, Usage: ```php -$fbApp = new Facebook\FacebookApp('{app-id}', '{app-secret}'); -$request = new Facebook\FacebookRequest($fbApp, '{access-token}', 'GET', '/me'); +$fbApp = new Facebook\Application('{app-id}', '{app-secret}'); +$request = new Facebook\Request($fbApp, '{access-token}', 'GET', '/me'); // OR diff --git a/docs/reference/FacebookVideo.md b/docs/reference/FacebookVideo.md index df7e424c1..0a7ec89e7 100644 --- a/docs/reference/FacebookVideo.md +++ b/docs/reference/FacebookVideo.md @@ -9,9 +9,9 @@ The `FacebookVideo` entity represents a local or remote video file to be uploade There are two ways to instantiate a `FacebookVideo` entity. One way is to instantiate it directly: ```php -use Facebook\FileUpload\FacebookVideo; +use Facebook\FileUpload\Video; -$myVideoFileToUpload = new FacebookVideo('/path/to/video-file.mp4'); +$myVideoFileToUpload = new Video('/path/to/video-file.mp4'); ``` Alternatively, you can use the `videoToUpload()` factory on the `Facebook\Facebook` super service to instantiate a new `FacebookVideo` entity. diff --git a/docs/reference/PersistentDataInterface.md b/docs/reference/PersistentDataInterface.md index 9f2283981..3d6a5195a 100644 --- a/docs/reference/PersistentDataInterface.md +++ b/docs/reference/PersistentDataInterface.md @@ -49,10 +49,10 @@ $fb = new Facebook\Facebook([ Alternatively, if you're working with the `Facebook\Helpers\FacebookRedirectLoginHelper` directly, you can inject your custom handler via the constructor. ```php -use Facebook\Helpers\FacebookRedirectLoginHelper; +use Facebook\Helpers\RedirectLoginHelper; $myPersistentDataHandler = new MyLaravelPersistentDataHandler(); -$helper = new FacebookRedirectLoginHelper($fbApp, $myPersistentDataHandler); +$helper = new RedirectLoginHelper($fbApp, $myPersistentDataHandler); ``` ## Method Reference diff --git a/docs/reference/PseudoRandomStringGeneratorInterface.md b/docs/reference/PseudoRandomStringGeneratorInterface.md index a6409ed30..6f5c270c3 100644 --- a/docs/reference/PseudoRandomStringGeneratorInterface.md +++ b/docs/reference/PseudoRandomStringGeneratorInterface.md @@ -44,10 +44,10 @@ $fb = new Facebook\Facebook([ Alternatively, if you're working with the `Facebook\Helpers\FacebookRedirectLoginHelper` directly, you can inject your custom generator via the constructor. ```php -use Facebook\Helpers\FacebookRedirectLoginHelper; +use Facebook\Helpers\RedirectLoginHelper; $myPseudoRandomStringGenerator = new MyCustomPseudoRandomStringGenerator(); -$helper = new FacebookRedirectLoginHelper($fbApp, null, null, $myPseudoRandomStringGenerator); +$helper = new RedirectLoginHelper($fbApp, null, null, $myPseudoRandomStringGenerator); ``` ## Method Reference diff --git a/docs/reference/SignedRequest.md b/docs/reference/SignedRequest.md index 70539f69c..eb9903543 100644 --- a/docs/reference/SignedRequest.md +++ b/docs/reference/SignedRequest.md @@ -9,7 +9,7 @@ The `Facebook\SignedRequest` entity represents a signed request. To instantiate a new `Facebook\SignedRequest` entity, pass the [`Facebook\FacebookApp`](FacebookApp.md) entity and raw signed request to the constructor. ```php -$fbApp = new Facebook\FacebookApp('{app-id}', '{app-secret}'); +$fbApp = new Facebook\Application('{app-id}', '{app-secret}'); $signedRequest = new Facebook\SignedRequest($fbApp, 'raw.signed_request'); ``` @@ -70,7 +70,7 @@ public string make(array $payload) Generates a valid raw signed request as a string that contains the data from the `$payload` array. The signature is signed using the app secret from the `Facebook\FacebookApp` entity. This can be useful for testing purposes. ```php -$fbApp = new Facebook\FacebookApp('{app-id}', '{app-secret}'); +$fbApp = new Facebook\Application('{app-id}', '{app-secret}'); $signedRequest = new Facebook\SignedRequest($fbApp); $payload = [ diff --git a/docs/reference/UrlDetectionInterface.md b/docs/reference/UrlDetectionInterface.md index 7e14b2445..b09c310b4 100644 --- a/docs/reference/UrlDetectionInterface.md +++ b/docs/reference/UrlDetectionInterface.md @@ -36,10 +36,10 @@ $fb = new Facebook\Facebook([ Alternatively, if you're working with the `Facebook\Helpers\FacebookRedirectLoginHelper` directly, you can inject your custom handler via the constructor. ```php -use Facebook\Helpers\FacebookRedirectLoginHelper; +use Facebook\Helpers\RedirectLoginHelper; $myUrlDetectionHandler = new MyLaravelUrlDetectionHandler(); -$helper = new FacebookRedirectLoginHelper($fbApp, null, $myUrlDetectionHandler); +$helper = new RedirectLoginHelper($fbApp, null, $myUrlDetectionHandler); ``` ## Method Reference diff --git a/src/Facebook/FacebookApp.php b/src/Facebook/Application.php similarity index 65% rename from src/Facebook/FacebookApp.php rename to src/Facebook/Application.php index 804c9bb56..a777886b7 100644 --- a/src/Facebook/FacebookApp.php +++ b/src/Facebook/Application.php @@ -21,22 +21,28 @@ * DEALINGS IN THE SOFTWARE. * */ + namespace Facebook; use Facebook\Authentication\AccessToken; use Facebook\Exceptions\FacebookSDKException; -class FacebookApp implements \Serializable +/** + * Class Application + * + * @package Facebook + */ +class Application { /** * @var string The app ID. */ - protected $id; + protected string $id; /** * @var string The app secret. */ - protected $secret; + protected string $secret; /** * @param string $id @@ -44,15 +50,10 @@ class FacebookApp implements \Serializable * * @throws FacebookSDKException */ - public function __construct($id, $secret) + public function __construct(string $id, string $secret) { - if (!is_string($id) - // Keeping this for BC. Integers greater than PHP_INT_MAX will make is_int() return false - && !is_int($id)) { - throw new FacebookSDKException('The "app_id" must be formatted as a string since many app ID\'s are greater than PHP_INT_MAX on some systems.'); - } // We cast as a string in case a valid int was set on a 64-bit system and this is unserialised on a 32-bit system - $this->id = (string) $id; + $this->id = $id; $this->secret = $secret; } @@ -61,7 +62,7 @@ public function __construct($id, $secret) * * @return string */ - public function getId() + public function getId(): string { return $this->id; } @@ -71,7 +72,7 @@ public function getId() * * @return string */ - public function getSecret() + public function getSecret(): string { return $this->secret; } @@ -81,30 +82,8 @@ public function getSecret() * * @return AccessToken */ - public function getAccessToken() + public function getAccessToken(): AccessToken { return new AccessToken($this->id . '|' . $this->secret); } - - /** - * Serializes the FacebookApp entity as a string. - * - * @return string - */ - public function serialize() - { - return implode('|', [$this->id, $this->secret]); - } - - /** - * Unserializes a string as a FacebookApp entity. - * - * @param string $serialized - */ - public function unserialize($serialized) - { - list($id, $secret) = explode('|', $serialized); - - $this->__construct($id, $secret); - } } diff --git a/src/Facebook/Authentication/OAuth2Client.php b/src/Facebook/Authentication/OAuth2Client.php index 94df9b7b5..073749b2d 100644 --- a/src/Facebook/Authentication/OAuth2Client.php +++ b/src/Facebook/Authentication/OAuth2Client.php @@ -1,4 +1,6 @@ app = $app; - $this->client = $client; - $this->graphVersion = $graphVersion ?: Facebook::DEFAULT_GRAPH_VERSION; + } /** * Returns the last FacebookRequest that was sent. * Useful for debugging and testing. * - * @return FacebookRequest|null + * @return Request|null */ - public function getLastRequest() + public function getLastRequest(): ?Request { return $this->lastRequest; } @@ -97,18 +83,18 @@ public function getLastRequest() /** * Get the metadata associated with the access token. * - * @param AccessToken|string $accessToken The access token to debug. + * @param string|AccessToken $accessToken The access token to debug. * * @return AccessTokenMetadata */ - public function debugToken($accessToken) + public function debugToken(string|AccessToken $accessToken): AccessTokenMetadata { $accessToken = $accessToken instanceof AccessToken ? $accessToken->getValue() : $accessToken; $params = ['input_token' => $accessToken]; - $this->lastRequest = new FacebookRequest( - $this->app, - $this->app->getAccessToken(), + $this->lastRequest = new Request( + $this->application, + $this->application->getAccessToken(), 'GET', '/debug_token', $params, @@ -132,10 +118,16 @@ public function debugToken($accessToken) * * @return string */ - public function getAuthorizationUrl($redirectUrl, $state, array $scope = [], array $params = [], $separator = '&') + #[Pure] public function getAuthorizationUrl( + string $redirectUrl, + string $state, + array $scope = [], + array $params = [], + string $separator = '&', + ): string { $params += [ - 'client_id' => $this->app->getId(), + 'client_id' => $this->application->getId(), 'state' => $state, 'response_type' => 'code', 'sdk' => 'php-sdk-' . Facebook::VERSION, @@ -143,7 +135,7 @@ public function getAuthorizationUrl($redirectUrl, $state, array $scope = [], arr 'scope' => implode(',', $scope) ]; - return static::BASE_AUTHORIZATION_URL . '/' . $this->graphVersion . '/dialog/oauth?' . http_build_query($params, null, $separator); + return static::BASE_AUTHORIZATION_URL . '/' . $this->graphVersion . '/dialog/oauth?' . http_build_query($params, '', $separator); } /** @@ -156,7 +148,7 @@ public function getAuthorizationUrl($redirectUrl, $state, array $scope = [], arr * * @throws FacebookSDKException */ - public function getAccessTokenFromCode($code, $redirectUri = '') + public function getAccessTokenFromCode(string $code, string $redirectUri = ''): AccessToken { $params = [ 'code' => $code, @@ -169,13 +161,13 @@ public function getAccessTokenFromCode($code, $redirectUri = '') /** * Exchanges a short-lived access token with a long-lived access token. * - * @param AccessToken|string $accessToken + * @param string|AccessToken $accessToken * * @return AccessToken * * @throws FacebookSDKException */ - public function getLongLivedAccessToken($accessToken) + public function getLongLivedAccessToken(string|AccessToken $accessToken): AccessToken { $accessToken = $accessToken instanceof AccessToken ? $accessToken->getValue() : $accessToken; $params = [ @@ -189,14 +181,14 @@ public function getLongLivedAccessToken($accessToken) /** * Get a valid code from an access token. * - * @param AccessToken|string $accessToken + * @param string|AccessToken $accessToken * @param string $redirectUri * - * @return AccessToken + * @return string * * @throws FacebookSDKException */ - public function getCodeFromLongLivedAccessToken($accessToken, $redirectUri = '') + public function getCodeFromLongLivedAccessToken(string|AccessToken $accessToken, string $redirectUri = ''): string { $params = [ 'redirect_uri' => $redirectUri, @@ -221,7 +213,7 @@ public function getCodeFromLongLivedAccessToken($accessToken, $redirectUri = '') * * @throws FacebookSDKException */ - protected function requestAnAccessToken(array $params) + protected function requestAnAccessToken(array $params): AccessToken { $response = $this->sendRequestWithClientParams('/oauth/access_token', $params); $data = $response->getDecodedBody(); @@ -234,11 +226,11 @@ protected function requestAnAccessToken(array $params) // on the same endpoint. Doh! :/ $expiresAt = 0; if (isset($data['expires'])) { - // For exchanging a short lived token with a long lived token. + // For exchanging a short-lived token with a long-lived token. // The expiration time in seconds will be returned as "expires". $expiresAt = time() + $data['expires']; } elseif (isset($data['expires_in'])) { - // For exchanging a code for a short lived access token. + // For exchanging a code for a short-lived access token. // The expiration time in seconds will be returned as "expires_in". // See: https://developers.facebook.com/docs/facebook-login/access-tokens#long-via-code $expiresAt = time() + $data['expires_in']; @@ -252,20 +244,24 @@ protected function requestAnAccessToken(array $params) * * @param string $endpoint * @param array $params - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * - * @return FacebookResponse + * @return Response * * @throws FacebookResponseException */ - protected function sendRequestWithClientParams($endpoint, array $params, $accessToken = null) + protected function sendRequestWithClientParams( + string $endpoint, + array $params, + string|AccessToken $accessToken = null, + ): Response { $params += $this->getClientParams(); - $accessToken = $accessToken ?: $this->app->getAccessToken(); + $accessToken = $accessToken ?: $this->application->getAccessToken(); - $this->lastRequest = new FacebookRequest( - $this->app, + $this->lastRequest = new Request( + $this->application, $accessToken, 'GET', $endpoint, @@ -282,11 +278,11 @@ protected function sendRequestWithClientParams($endpoint, array $params, $access * * @return array */ - protected function getClientParams() + #[ArrayShape(['client_id' => "string", 'client_secret' => "string"])] #[Pure] protected function getClientParams(): array { return [ - 'client_id' => $this->app->getId(), - 'client_secret' => $this->app->getSecret(), + 'client_id' => $this->application->getId(), + 'client_secret' => $this->application->getSecret(), ]; } } diff --git a/src/Facebook/FacebookBatchRequest.php b/src/Facebook/BatchRequest.php similarity index 90% rename from src/Facebook/FacebookBatchRequest.php rename to src/Facebook/BatchRequest.php index 9297e77d7..ec4ca0d8f 100644 --- a/src/Facebook/FacebookBatchRequest.php +++ b/src/Facebook/BatchRequest.php @@ -34,7 +34,7 @@ * * @package Facebook */ -class FacebookBatchRequest extends FacebookRequest implements IteratorAggregate, ArrayAccess +class BatchRequest extends Request implements IteratorAggregate, ArrayAccess { /** * @var array An array of FacebookRequest entities to send. @@ -49,12 +49,12 @@ class FacebookBatchRequest extends FacebookRequest implements IteratorAggregate, /** * Creates a new Request entity. * - * @param FacebookApp|null $app + * @param Application|null $app * @param array $requests * @param AccessToken|string|null $accessToken * @param string|null $graphVersion */ - public function __construct(FacebookApp $app = null, array $requests = [], $accessToken = null, $graphVersion = null) + public function __construct(Application $app = null, array $requests = [], $accessToken = null, $graphVersion = null) { parent::__construct($app, $accessToken, 'POST', '', [], null, $graphVersion); @@ -64,11 +64,11 @@ public function __construct(FacebookApp $app = null, array $requests = [], $acce /** * Adds a new request to the array. * - * @param FacebookRequest|array $request - * @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'. + * @param Request|array $request + * @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'. * If a string is given, it is the value of the 'name' option. * - * @return FacebookBatchRequest + * @return BatchRequest * * @throws \InvalidArgumentException */ @@ -82,7 +82,7 @@ public function add($request, $options = null) return $this; } - if (!$request instanceof FacebookRequest) { + if (!$request instanceof Request) { throw new \InvalidArgumentException('Argument for add() must be of type array or FacebookRequest.'); } @@ -116,14 +116,14 @@ public function add($request, $options = null) /** * Ensures that the FacebookApp and access token fall back when missing. * - * @param FacebookRequest $request + * @param Request $request * * @throws FacebookSDKException */ - public function addFallbackDefaults(FacebookRequest $request) + public function addFallbackDefaults(Request $request) { - if (!$request->getApp()) { - $app = $this->getApp(); + if (!$request->getApplication()) { + $app = $this->getApplication(); if (!$app) { throw new FacebookSDKException('Missing FacebookApp on FacebookRequest and no fallback detected on FacebookBatchRequest.'); } @@ -142,13 +142,13 @@ public function addFallbackDefaults(FacebookRequest $request) /** * Extracts the files from a request. * - * @param FacebookRequest $request + * @param Request $request * * @return string|null * * @throws FacebookSDKException */ - public function extractFileAttachments(FacebookRequest $request) + public function extractFileAttachments(Request $request) { if (!$request->containsFileUploads()) { return null; @@ -234,14 +234,14 @@ public function validateBatchRequestCount() /** * Converts a Request entity into an array that is batch-friendly. * - * @param FacebookRequest $request The request entity to convert. + * @param Request $request The request entity to convert. * @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'. * If a string is given, it is the value of the 'name' option. * @param string|null $attachedFiles Names of files associated with the request. * * @return array */ - public function requestEntityToBatchArray(FacebookRequest $request, $options = null, $attachedFiles = null) + public function requestEntityToBatchArray(Request $request, $options = null, $attachedFiles = null) { if (null === $options) { diff --git a/src/Facebook/FacebookBatchResponse.php b/src/Facebook/BatchResponse.php similarity index 90% rename from src/Facebook/FacebookBatchResponse.php rename to src/Facebook/BatchResponse.php index 8e1464c98..d6eccd7da 100644 --- a/src/Facebook/FacebookBatchResponse.php +++ b/src/Facebook/BatchResponse.php @@ -28,14 +28,14 @@ use ArrayAccess; /** - * Class FacebookBatchResponse + * Class BatchResponse * * @package Facebook */ -class FacebookBatchResponse extends FacebookResponse implements IteratorAggregate, ArrayAccess +class BatchResponse extends Response implements IteratorAggregate, ArrayAccess { /** - * @var FacebookBatchRequest The original entity that made the batch request. + * @var BatchRequest The original entity that made the batch request. */ protected $batchRequest; @@ -47,10 +47,10 @@ class FacebookBatchResponse extends FacebookResponse implements IteratorAggregat /** * Creates a new Response entity. * - * @param FacebookBatchRequest $batchRequest - * @param FacebookResponse $response + * @param BatchRequest $batchRequest + * @param Response $response */ - public function __construct(FacebookBatchRequest $batchRequest, FacebookResponse $response) + public function __construct(BatchRequest $batchRequest, Response $response) { $this->batchRequest = $batchRequest; @@ -105,7 +105,7 @@ public function addResponse($key, $response) // @TODO With PHP 5.5 support, this becomes array_column($response['headers'], 'value', 'name') $httpResponseHeaders = isset($response['headers']) ? $this->normalizeBatchHeaders($response['headers']) : []; - $this->responses[$originalRequestName] = new FacebookResponse( + $this->responses[$originalRequestName] = new Response( $originalRequest, $httpResponseBody, $httpResponseCode, diff --git a/src/Facebook/FacebookClient.php b/src/Facebook/Client.php similarity index 61% rename from src/Facebook/FacebookClient.php rename to src/Facebook/Client.php index dbf759238..ecaf3711e 100644 --- a/src/Facebook/FacebookClient.php +++ b/src/Facebook/Client.php @@ -1,4 +1,6 @@ httpClientHandler = $httpClientHandler ?: $this->detectHttpClientHandler(); - $this->enableBetaMode = $enableBeta; + $this->httpCllient = $httpClient ?? new HttpClient(); } /** * Sets the HTTP client handler. - * - * @param FacebookHttpClientInterface $httpClientHandler */ - public function setHttpClientHandler(FacebookHttpClientInterface $httpClientHandler) + public function setHttpClient(HttpClient $httpClient): void { - $this->httpClientHandler = $httpClientHandler; + $this->httpCllient = $httpClient; } /** * Returns the HTTP client handler. * - * @return FacebookHttpClientInterface */ - public function getHttpClientHandler() + public function getHttpCllient(): HttpClient { - return $this->httpClientHandler; - } - - /** - * Detects which HTTP client handler to use. - * - * @return FacebookHttpClientInterface - */ - public function detectHttpClientHandler() - { - return extension_loaded('curl') ? new FacebookCurlHttpClient() : new FacebookStreamHttpClient(); + return $this->httpCllient; } /** @@ -132,7 +117,7 @@ public function detectHttpClientHandler() * * @param boolean $betaMode */ - public function enableBetaMode($betaMode = true) + public function enableBetaMode(bool $betaMode = true) { $this->enableBetaMode = $betaMode; } @@ -144,7 +129,7 @@ public function enableBetaMode($betaMode = true) * * @return string */ - public function getBaseGraphUrl($postToVideoUrl = false) + public function getBaseGraphUrl(bool $postToVideoUrl = false): string { if ($postToVideoUrl) { return $this->enableBetaMode ? static::BASE_GRAPH_VIDEO_URL_BETA : static::BASE_GRAPH_VIDEO_URL; @@ -156,11 +141,11 @@ public function getBaseGraphUrl($postToVideoUrl = false) /** * Prepares the request for sending to the client handler. * - * @param FacebookRequest $request + * @param Request|BatchRequest $request * * @return array */ - public function prepareRequestMessage(FacebookRequest $request) + public function prepareRequestMessage(Request|BatchRequest $request): array { $postToVideoUrl = $request->containsVideoUploads(); $url = $this->getBaseGraphUrl($postToVideoUrl) . $request->getUrl(); @@ -189,62 +174,58 @@ public function prepareRequestMessage(FacebookRequest $request) /** * Makes the request to Graph and returns the result. * - * @param FacebookRequest $request + * @param Request $request * - * @return FacebookResponse + * @return Response * * @throws FacebookSDKException */ - public function sendRequest(FacebookRequest $request) + public function sendRequest(Request $request): Response { - if (get_class($request) === 'Facebook\FacebookRequest') { + if ($request::class === Request::class) { $request->validateAccessToken(); } - list($url, $method, $headers, $body) = $this->prepareRequestMessage($request); - - // Since file uploads can take a while, we need to give more time for uploads - $timeOut = static::DEFAULT_REQUEST_TIMEOUT; - if ($request->containsFileUploads()) { - $timeOut = static::DEFAULT_FILE_UPLOAD_REQUEST_TIMEOUT; - } elseif ($request->containsVideoUploads()) { - $timeOut = static::DEFAULT_VIDEO_UPLOAD_REQUEST_TIMEOUT; - } + [$url, $method, $headers, $body] = $this->prepareRequestMessage($request); // Should throw `FacebookSDKException` exception on HTTP client error. // Don't catch to allow it to bubble up. - $rawResponse = $this->httpClientHandler->send($url, $method, $body, $headers, $timeOut); + $rawResponse = $this->getHttpCllient()->request($method, $url, [ + 'body' => $body, + 'headers' => $headers, + 'verify' => false + ]); static::$requestCount++; - $returnResponse = new FacebookResponse( + $response = new Response( $request, - $rawResponse->getBody(), - $rawResponse->getHttpResponseCode(), + $rawResponse->getBody()->getContents(), + $rawResponse->getStatusCode(), $rawResponse->getHeaders() ); - if ($returnResponse->isError()) { - throw $returnResponse->getThrownException(); + if ($response->isError()) { + throw $response->getThrownException(); } - return $returnResponse; + return $response; } /** * Makes a batched request to Graph and returns the result. * - * @param FacebookBatchRequest $request + * @param BatchRequest $request * - * @return FacebookBatchResponse + * @return BatchResponse * * @throws FacebookSDKException */ - public function sendBatchRequest(FacebookBatchRequest $request) + public function sendBatchRequest(BatchRequest $request): BatchResponse { $request->prepareRequestsForBatch(); $facebookResponse = $this->sendRequest($request); - return new FacebookBatchResponse($request, $facebookResponse); + return new BatchResponse($request, $facebookResponse); } } diff --git a/src/Facebook/Exceptions/FacebookResponseException.php b/src/Facebook/Exceptions/FacebookResponseException.php index e51f1c840..0b8d44cf5 100644 --- a/src/Facebook/Exceptions/FacebookResponseException.php +++ b/src/Facebook/Exceptions/FacebookResponseException.php @@ -23,7 +23,7 @@ */ namespace Facebook\Exceptions; -use Facebook\FacebookResponse; +use Facebook\Response; /** * Class FacebookResponseException @@ -33,7 +33,7 @@ class FacebookResponseException extends FacebookSDKException { /** - * @var FacebookResponse The response that threw the exception. + * @var Response The response that threw the exception. */ protected $response; @@ -45,10 +45,10 @@ class FacebookResponseException extends FacebookSDKException /** * Creates a FacebookResponseException. * - * @param FacebookResponse $response The response that threw the exception. + * @param Response $response The response that threw the exception. * @param FacebookSDKException $previousException The more detailed exception. */ - public function __construct(FacebookResponse $response, FacebookSDKException $previousException = null) + public function __construct(Response $response, FacebookSDKException $previousException = null) { $this->response = $response; $this->responseData = $response->getDecodedBody(); @@ -62,11 +62,11 @@ public function __construct(FacebookResponse $response, FacebookSDKException $pr /** * A factory for creating the appropriate exception based on the response from Graph. * - * @param FacebookResponse $response The response that threw the exception. + * @param Response $response The response that threw the exception. * * @return FacebookResponseException */ - public static function create(FacebookResponse $response) + public static function create(Response $response) { $data = $response->getDecodedBody(); @@ -216,7 +216,7 @@ public function getResponseData() /** * Returns the response entity used to create the exception. * - * @return FacebookResponse + * @return Response */ public function getResponse() { diff --git a/src/Facebook/Facebook.php b/src/Facebook/Facebook.php index 03a523480..538e23974 100644 --- a/src/Facebook/Facebook.php +++ b/src/Facebook/Facebook.php @@ -21,27 +21,27 @@ * DEALINGS IN THE SOFTWARE. * */ + namespace Facebook; use Facebook\Authentication\AccessToken; use Facebook\Authentication\OAuth2Client; -use Facebook\FileUpload\FacebookFile; -use Facebook\FileUpload\FacebookResumableUploader; -use Facebook\FileUpload\FacebookTransferChunk; -use Facebook\FileUpload\FacebookVideo; +use Facebook\FileUpload\File; +use Facebook\FileUpload\ResumableUploader; +use Facebook\FileUpload\TransferChunk; +use Facebook\FileUpload\Video; use Facebook\GraphNodes\GraphEdge; use Facebook\Url\UrlDetectionInterface; -use Facebook\Url\FacebookUrlDetectionHandler; -use Facebook\PseudoRandomString\PseudoRandomStringGeneratorFactory; -use Facebook\PseudoRandomString\PseudoRandomStringGeneratorInterface; -use Facebook\HttpClients\HttpClientsFactory; +use Facebook\Url\UrlDetectionHandler; use Facebook\PersistentData\PersistentDataFactory; use Facebook\PersistentData\PersistentDataInterface; -use Facebook\Helpers\FacebookCanvasHelper; -use Facebook\Helpers\FacebookJavaScriptHelper; -use Facebook\Helpers\FacebookPageTabHelper; -use Facebook\Helpers\FacebookRedirectLoginHelper; +use Facebook\Helpers\CanvasHelper; +use Facebook\Helpers\JavaScriptHelper; +use Facebook\Helpers\PageTabHelper; +use Facebook\Helpers\RedirectLoginHelper; use Facebook\Exceptions\FacebookSDKException; +use InvalidArgumentException; +use JetBrains\PhpStorm\ArrayShape; /** * Class Facebook @@ -53,12 +53,7 @@ class Facebook /** * @const string Version number of the Facebook PHP SDK. */ - const VERSION = '5.7.0'; - - /** - * @const string Default Graph API version for requests. - */ - const DEFAULT_GRAPH_VERSION = 'v2.10'; + const VERSION = '1.0'; /** * @const string The name of the environment variable that contains the app ID. @@ -71,49 +66,44 @@ class Facebook const APP_SECRET_ENV_NAME = 'FACEBOOK_APP_SECRET'; /** - * @var FacebookApp The FacebookApp entity. + * @var Application The FacebookApp entity. */ - protected $app; + protected Application $app; /** - * @var FacebookClient The Facebook client service. + * @var Client The Facebook client service. */ - protected $client; + protected Client $client; /** - * @var OAuth2Client The OAuth 2.0 client service. + * @var ?OAuth2Client The OAuth 2.0 client service. */ - protected $oAuth2Client; + protected ?OAuth2Client $oAuth2Client = null; /** * @var UrlDetectionInterface|null The URL detection handler. */ - protected $urlDetectionHandler; - - /** - * @var PseudoRandomStringGeneratorInterface|null The cryptographically secure pseudo-random string generator. - */ - protected $pseudoRandomStringGenerator; + protected ?UrlDetectionInterface $urlDetectionHandler; /** * @var AccessToken|null The default access token to use with requests. */ - protected $defaultAccessToken; + protected ?AccessToken $defaultAccessToken; /** * @var string|null The default Graph version we want to use. */ - protected $defaultGraphVersion; + protected ?string $defaultGraphVersion; /** * @var PersistentDataInterface|null The persistent data handler. */ - protected $persistentDataHandler; + protected ?PersistentDataInterface $persistentDataHandler; /** - * @var FacebookResponse|FacebookBatchResponse|null Stores the last request made to Graph. + * @var Response|BatchResponse|null Stores the last request made to Graph. */ - protected $lastResponse; + protected BatchResponse|null|Response $lastResponse; /** * Instantiates a new Facebook super-class object. @@ -127,11 +117,10 @@ public function __construct(array $config = []) $config = array_merge([ 'app_id' => getenv(static::APP_ID_ENV_NAME), 'app_secret' => getenv(static::APP_SECRET_ENV_NAME), - 'default_graph_version' => static::DEFAULT_GRAPH_VERSION, + 'default_graph_version' => null, 'enable_beta_mode' => false, - 'http_client_handler' => null, + 'http_client' => null, 'persistent_data_handler' => null, - 'pseudo_random_string_generator' => null, 'url_detection_handler' => null, ], $config); @@ -141,16 +130,16 @@ public function __construct(array $config = []) if (!$config['app_secret']) { throw new FacebookSDKException('Required "app_secret" key not supplied in config and could not find fallback environment variable "' . static::APP_SECRET_ENV_NAME . '"'); } + if ($config['http_client'] !== null && !$config['http_client'] instanceof \GuzzleHttp\Client) { + throw new InvalidArgumentException('Required "http_client" key to be null or an instance of \Http\Client\HttpClient'); + } + if (!$config['default_graph_version']) { + throw new InvalidArgumentException('Required "default_graph_version" key not supplied in config'); + } - $this->app = new FacebookApp($config['app_id'], $config['app_secret']); - $this->client = new FacebookClient( - HttpClientsFactory::createHttpClient($config['http_client_handler']), - $config['enable_beta_mode'] - ); - $this->pseudoRandomStringGenerator = PseudoRandomStringGeneratorFactory::createPseudoRandomStringGenerator( - $config['pseudo_random_string_generator'] - ); - $this->setUrlDetectionHandler($config['url_detection_handler'] ?: new FacebookUrlDetectionHandler()); + $this->app = new Application($config['app_id'], $config['app_secret']); + $this->client = new Client($config['http_client'], $config['enable_beta_mode']); + $this->setUrlDetectionHandler($config['url_detection_handler'] ?: new UrlDetectionHandler()); $this->persistentDataHandler = PersistentDataFactory::createPersistentDataHandler( $config['persistent_data_handler'] ); @@ -159,16 +148,15 @@ public function __construct(array $config = []) $this->setDefaultAccessToken($config['default_access_token']); } - // @todo v6: Throw an InvalidArgumentException if "default_graph_version" is not set $this->defaultGraphVersion = $config['default_graph_version']; } /** * Returns the FacebookApp entity. * - * @return FacebookApp + * @return Application */ - public function getApp() + public function getApplication(): Application { return $this->app; } @@ -176,9 +164,9 @@ public function getApp() /** * Returns the FacebookClient service. * - * @return FacebookClient + * @return Client */ - public function getClient() + public function getClient(): Client { return $this->client; } @@ -188,12 +176,12 @@ public function getClient() * * @return OAuth2Client */ - public function getOAuth2Client() + public function getOAuth2Client(): OAuth2Client { - if (!$this->oAuth2Client instanceof OAuth2Client) { - $app = $this->getApp(); + if ($this->oAuth2Client === null) { + $application = $this->getApplication(); $client = $this->getClient(); - $this->oAuth2Client = new OAuth2Client($app, $client, $this->defaultGraphVersion); + $this->oAuth2Client = new OAuth2Client($application, $client, $this->defaultGraphVersion); } return $this->oAuth2Client; @@ -202,9 +190,9 @@ public function getOAuth2Client() /** * Returns the last response returned from Graph. * - * @return FacebookResponse|FacebookBatchResponse|null + * @return Response|BatchResponse|null */ - public function getLastResponse() + public function getLastResponse(): Response|BatchResponse|null { return $this->lastResponse; } @@ -212,9 +200,9 @@ public function getLastResponse() /** * Returns the URL detection handler. * - * @return UrlDetectionInterface + * @return \Facebook\Url\UrlDetectionInterface|null */ - public function getUrlDetectionHandler() + public function getUrlDetectionHandler(): ?UrlDetectionInterface { return $this->urlDetectionHandler; } @@ -234,7 +222,7 @@ private function setUrlDetectionHandler(UrlDetectionInterface $urlDetectionHandl * * @return AccessToken|null */ - public function getDefaultAccessToken() + public function getDefaultAccessToken(): ?AccessToken { return $this->defaultAccessToken; } @@ -242,21 +230,19 @@ public function getDefaultAccessToken() /** * Sets the default access token to use with requests. * - * @param AccessToken|string $accessToken The access token to save. + * @param mixed $accessToken The access token to save. * * @throws \InvalidArgumentException */ - public function setDefaultAccessToken($accessToken) + public function setDefaultAccessToken(mixed $accessToken): void { if (is_string($accessToken)) { $this->defaultAccessToken = new AccessToken($accessToken); - return; } if ($accessToken instanceof AccessToken) { $this->defaultAccessToken = $accessToken; - return; } @@ -266,9 +252,9 @@ public function setDefaultAccessToken($accessToken) /** * Returns the default Graph version. * - * @return string + * @return string|null */ - public function getDefaultGraphVersion() + public function getDefaultGraphVersion(): ?string { return $this->defaultGraphVersion; } @@ -276,66 +262,70 @@ public function getDefaultGraphVersion() /** * Returns the redirect login helper. * - * @return FacebookRedirectLoginHelper + * @return RedirectLoginHelper */ - public function getRedirectLoginHelper() + public function getRedirectLoginHelper(): RedirectLoginHelper { - return new FacebookRedirectLoginHelper( + return new RedirectLoginHelper( $this->getOAuth2Client(), $this->persistentDataHandler, - $this->urlDetectionHandler, - $this->pseudoRandomStringGenerator + $this->urlDetectionHandler ); } /** * Returns the JavaScript helper. * - * @return FacebookJavaScriptHelper + * @return JavaScriptHelper */ - public function getJavaScriptHelper() + public function getJavaScriptHelper(): JavaScriptHelper { - return new FacebookJavaScriptHelper($this->app, $this->client, $this->defaultGraphVersion); + return new JavaScriptHelper($this->app, $this->client, $this->defaultGraphVersion); } /** * Returns the canvas helper. * - * @return FacebookCanvasHelper + * @return CanvasHelper */ - public function getCanvasHelper() + public function getCanvasHelper(): CanvasHelper { - return new FacebookCanvasHelper($this->app, $this->client, $this->defaultGraphVersion); + return new CanvasHelper($this->app, $this->client, $this->defaultGraphVersion); } /** * Returns the page tab helper. * - * @return FacebookPageTabHelper + * @return PageTabHelper */ - public function getPageTabHelper() + public function getPageTabHelper(): PageTabHelper { - return new FacebookPageTabHelper($this->app, $this->client, $this->defaultGraphVersion); + return new PageTabHelper($this->app, $this->client, $this->defaultGraphVersion); } /** * Sends a GET request to Graph and returns the result. * * @param string $endpoint - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $eTag * @param string|null $graphVersion * - * @return FacebookResponse + * @return Response * * @throws FacebookSDKException */ - public function get($endpoint, $accessToken = null, $eTag = null, $graphVersion = null) + public function get( + string $endpoint, + string|AccessToken $accessToken = null, + string $eTag = null, + string $graphVersion = null + ): Response { return $this->sendRequest( 'GET', $endpoint, - $params = [], + [], $accessToken, $eTag, $graphVersion @@ -347,15 +337,21 @@ public function get($endpoint, $accessToken = null, $eTag = null, $graphVersion * * @param string $endpoint * @param array $params - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $eTag * @param string|null $graphVersion * - * @return FacebookResponse + * @return Response * * @throws FacebookSDKException */ - public function post($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null) + public function post( + string $endpoint, + array $params = [], + string|AccessToken $accessToken = null, + string $eTag = null, + string $graphVersion = null + ): Response { return $this->sendRequest( 'POST', @@ -372,15 +368,21 @@ public function post($endpoint, array $params = [], $accessToken = null, $eTag = * * @param string $endpoint * @param array $params - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $eTag * @param string|null $graphVersion * - * @return FacebookResponse + * @return Response * * @throws FacebookSDKException */ - public function delete($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null) + public function delete( + string $endpoint, + array $params = [], + string|AccessToken $accessToken = null, + string $eTag = null, + string $graphVersion = null, + ): Response { return $this->sendRequest( 'DELETE', @@ -401,7 +403,7 @@ public function delete($endpoint, array $params = [], $accessToken = null, $eTag * * @throws FacebookSDKException */ - public function next(GraphEdge $graphEdge) + public function next(GraphEdge $graphEdge): ?GraphEdge { return $this->getPaginationResults($graphEdge, 'next'); } @@ -415,7 +417,7 @@ public function next(GraphEdge $graphEdge) * * @throws FacebookSDKException */ - public function previous(GraphEdge $graphEdge) + public function previous(GraphEdge $graphEdge): ?GraphEdge { return $this->getPaginationResults($graphEdge, 'previous'); } @@ -430,7 +432,7 @@ public function previous(GraphEdge $graphEdge) * * @throws FacebookSDKException */ - public function getPaginationResults(GraphEdge $graphEdge, $direction) + public function getPaginationResults(GraphEdge $graphEdge, string $direction): ?GraphEdge { $paginationRequest = $graphEdge->getPaginationRequest($direction); if (!$paginationRequest) { @@ -452,15 +454,22 @@ public function getPaginationResults(GraphEdge $graphEdge, $direction) * @param string $method * @param string $endpoint * @param array $params - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $eTag * @param string|null $graphVersion * - * @return FacebookResponse + * @return Response * * @throws FacebookSDKException */ - public function sendRequest($method, $endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null) + public function sendRequest( + string $method, + string $endpoint, + array $params = [], + string|AccessToken $accessToken = null, + string $eTag = null, + string $graphVersion = null, + ): Response { $accessToken = $accessToken ?: $this->defaultAccessToken; $graphVersion = $graphVersion ?: $this->defaultGraphVersion; @@ -473,18 +482,22 @@ public function sendRequest($method, $endpoint, array $params = [], $accessToken * Sends a batched request to Graph and returns the result. * * @param array $requests - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $graphVersion * - * @return FacebookBatchResponse + * @return BatchResponse * * @throws FacebookSDKException */ - public function sendBatchRequest(array $requests, $accessToken = null, $graphVersion = null) + public function sendBatchRequest( + array $requests, + string|AccessToken $accessToken = null, + string $graphVersion = null + ): BatchResponse { $accessToken = $accessToken ?: $this->defaultAccessToken; $graphVersion = $graphVersion ?: $this->defaultGraphVersion; - $batchRequest = new FacebookBatchRequest( + $batchRequest = new BatchRequest( $this->app, $requests, $accessToken, @@ -497,17 +510,18 @@ public function sendBatchRequest(array $requests, $accessToken = null, $graphVer /** * Instantiates an empty FacebookBatchRequest entity. * - * @param AccessToken|string|null $accessToken The top-level access token. Requests with no access token + * @param string|AccessToken|null $accessToken The top-level access token. Requests with no access token * will fallback to this. - * @param string|null $graphVersion The Graph API version to use. - * @return FacebookBatchRequest + * @param string|null $graphVersion The Graph API version to use. + * + * @return BatchRequest */ - public function newBatchRequest($accessToken = null, $graphVersion = null) + public function newBatchRequest(string|AccessToken $accessToken = null, string $graphVersion = null): BatchRequest { $accessToken = $accessToken ?: $this->defaultAccessToken; $graphVersion = $graphVersion ?: $this->defaultGraphVersion; - return new FacebookBatchRequest( + return new BatchRequest( $this->app, [], $accessToken, @@ -521,20 +535,27 @@ public function newBatchRequest($accessToken = null, $graphVersion = null) * @param string $method * @param string $endpoint * @param array $params - * @param AccessToken|string|null $accessToken + * @param string|AccessToken|null $accessToken * @param string|null $eTag * @param string|null $graphVersion * - * @return FacebookRequest + * @return Request * * @throws FacebookSDKException */ - public function request($method, $endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null) + public function request( + string $method, + string $endpoint, + array $params = [], + string|AccessToken $accessToken = null, + string $eTag = null, + string $graphVersion = null, + ): Request { $accessToken = $accessToken ?: $this->defaultAccessToken; $graphVersion = $graphVersion ?: $this->defaultGraphVersion; - return new FacebookRequest( + return new Request( $this->app, $accessToken, $method, @@ -550,13 +571,13 @@ public function request($method, $endpoint, array $params = [], $accessToken = n * * @param string $pathToFile * - * @return FacebookFile + * @return File * * @throws FacebookSDKException */ - public function fileToUpload($pathToFile) + public function fileToUpload(string $pathToFile): File { - return new FacebookFile($pathToFile); + return new File($pathToFile); } /** @@ -564,36 +585,45 @@ public function fileToUpload($pathToFile) * * @param string $pathToFile * - * @return FacebookVideo + * @return Video * * @throws FacebookSDKException */ - public function videoToUpload($pathToFile) + public function videoToUpload(string $pathToFile): Video { - return new FacebookVideo($pathToFile); + return new Video($pathToFile); } /** * Upload a video in chunks. * - * @param int $target The id of the target node before the /videos edge. - * @param string $pathToFile The full path to the file. - * @param array $metadata The metadata associated with the video file. - * @param string|null $accessToken The access token. - * @param int $maxTransferTries The max times to retry a failed upload chunk. - * @param string|null $graphVersion The Graph API version to use. + * @param int|string $target The id of the target node before the + * /videos edge. + * @param string $pathToFile The full path to the file. + * @param array $metadata The metadata associated with the video + * file. + * @param string|\Facebook\Authentication\AccessToken|null $accessToken The access token. + * @param int $maxTransferTries The max times to retry a failed upload + * chunk. + * @param string|null $graphVersion The Graph API version to use. * * @return array * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function uploadVideo($target, $pathToFile, $metadata = [], $accessToken = null, $maxTransferTries = 5, $graphVersion = null) + #[ArrayShape(['video_id' => "int", 'success' => "bool"])] public function uploadVideo( + int|string $target, + string $pathToFile, + array $metadata = [], + string|AccessToken $accessToken = null, + int $maxTransferTries = 5, + string $graphVersion = null, + ): array { - $accessToken = $accessToken ?: $this->defaultAccessToken; - $graphVersion = $graphVersion ?: $this->defaultGraphVersion; - - $uploader = new FacebookResumableUploader($this->app, $this->client, $accessToken, $graphVersion); - $endpoint = '/'.$target.'/videos'; + $accessToken ??= $this->defaultAccessToken; + $graphVersion ??= $this->defaultGraphVersion; + $uploader = new ResumableUploader($this->app, $this->client, $accessToken, $graphVersion); + $endpoint = '/' . $target . '/videos'; $file = $this->videoToUpload($pathToFile); $chunk = $uploader->start($endpoint, $file); @@ -602,24 +632,29 @@ public function uploadVideo($target, $pathToFile, $metadata = [], $accessToken = } while (!$chunk->isLastChunk()); return [ - 'video_id' => $chunk->getVideoId(), - 'success' => $uploader->finish($endpoint, $chunk->getUploadSessionId(), $metadata), + 'video_id' => $chunk->getVideoId(), + 'success' => $uploader->finish($endpoint, $chunk->getUploadSessionId(), $metadata), ]; } /** * Attempts to upload a chunk of a file in $retryCountdown tries. * - * @param FacebookResumableUploader $uploader - * @param string $endpoint - * @param FacebookTransferChunk $chunk - * @param int $retryCountdown + * @param ResumableUploader $uploader + * @param string $endpoint + * @param TransferChunk $chunk + * @param int $retryCountdown * - * @return FacebookTransferChunk + * @return TransferChunk * * @throws FacebookSDKException */ - private function maxTriesTransfer(FacebookResumableUploader $uploader, $endpoint, FacebookTransferChunk $chunk, $retryCountdown) + private function maxTriesTransfer( + ResumableUploader $uploader, + string $endpoint, + TransferChunk $chunk, + int $retryCountdown, + ): TransferChunk { $newChunk = $uploader->transfer($endpoint, $chunk, $retryCountdown < 1); diff --git a/src/Facebook/FileUpload/FacebookFile.php b/src/Facebook/FileUpload/File.php similarity index 99% rename from src/Facebook/FileUpload/FacebookFile.php rename to src/Facebook/FileUpload/File.php index 3c1536d43..4acb23809 100644 --- a/src/Facebook/FileUpload/FacebookFile.php +++ b/src/Facebook/FileUpload/File.php @@ -30,7 +30,7 @@ * * @package Facebook */ -class FacebookFile +class File { /** * @var string The path to the file on the system. diff --git a/src/Facebook/FileUpload/FacebookResumableUploader.php b/src/Facebook/FileUpload/ResumableUploader.php similarity index 77% rename from src/Facebook/FileUpload/FacebookResumableUploader.php rename to src/Facebook/FileUpload/ResumableUploader.php index 46a2727b9..a059d2be7 100644 --- a/src/Facebook/FileUpload/FacebookResumableUploader.php +++ b/src/Facebook/FileUpload/ResumableUploader.php @@ -27,19 +27,19 @@ use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookResumableUploadException; use Facebook\Exceptions\FacebookSDKException; -use Facebook\FacebookApp; -use Facebook\FacebookClient; -use Facebook\FacebookRequest; +use Facebook\Application; +use Facebook\Client; +use Facebook\Request; /** * Class FacebookResumableUploader * * @package Facebook */ -class FacebookResumableUploader +class ResumableUploader { /** - * @var FacebookApp + * @var Application */ protected $app; @@ -49,7 +49,7 @@ class FacebookResumableUploader protected $accessToken; /** - * @var FacebookClient The Facebook client service. + * @var Client The Facebook client service. */ protected $client; @@ -59,12 +59,12 @@ class FacebookResumableUploader protected $graphVersion; /** - * @param FacebookApp $app - * @param FacebookClient $client + * @param Application $app + * @param Client $client * @param AccessToken|string|null $accessToken * @param string $graphVersion */ - public function __construct(FacebookApp $app, FacebookClient $client, $accessToken, $graphVersion) + public function __construct(Application $app, Client $client, $accessToken, $graphVersion) { $this->app = $app; $this->client = $client; @@ -76,13 +76,13 @@ public function __construct(FacebookApp $app, FacebookClient $client, $accessTok * Upload by chunks - start phase * * @param string $endpoint - * @param FacebookFile $file + * @param File $file * - * @return FacebookTransferChunk + * @return TransferChunk * * @throws FacebookSDKException */ - public function start($endpoint, FacebookFile $file) + public function start($endpoint, File $file) { $params = [ 'upload_phase' => 'start', @@ -90,21 +90,21 @@ public function start($endpoint, FacebookFile $file) ]; $response = $this->sendUploadRequest($endpoint, $params); - return new FacebookTransferChunk($file, $response['upload_session_id'], $response['video_id'], $response['start_offset'], $response['end_offset']); + return new TransferChunk($file, $response['upload_session_id'], $response['video_id'], $response['start_offset'], $response['end_offset']); } /** * Upload by chunks - transfer phase * - * @param string $endpoint - * @param FacebookTransferChunk $chunk - * @param boolean $allowToThrow + * @param string $endpoint + * @param TransferChunk $chunk + * @param boolean $allowToThrow * - * @return FacebookTransferChunk + * @return TransferChunk * * @throws FacebookResponseException */ - public function transfer($endpoint, FacebookTransferChunk $chunk, $allowToThrow = false) + public function transfer($endpoint, TransferChunk $chunk, $allowToThrow = false) { $params = [ 'upload_phase' => 'transfer', @@ -122,7 +122,7 @@ public function transfer($endpoint, FacebookTransferChunk $chunk, $allowToThrow } if (null !== $preException->getStartOffset() && null !== $preException->getEndOffset()) { - return new FacebookTransferChunk( + return new TransferChunk( $chunk->getFile(), $chunk->getUploadSessionId(), $chunk->getVideoId(), @@ -135,7 +135,7 @@ public function transfer($endpoint, FacebookTransferChunk $chunk, $allowToThrow return $chunk; } - return new FacebookTransferChunk($chunk->getFile(), $chunk->getUploadSessionId(), $chunk->getVideoId(), $response['start_offset'], $response['end_offset']); + return new TransferChunk($chunk->getFile(), $chunk->getUploadSessionId(), $chunk->getVideoId(), $response['start_offset'], $response['end_offset']); } /** @@ -170,7 +170,7 @@ public function finish($endpoint, $uploadSessionId, $metadata = []) */ private function sendUploadRequest($endpoint, $params = []) { - $request = new FacebookRequest($this->app, $this->accessToken, 'POST', $endpoint, $params, null, $this->graphVersion); + $request = new Request($this->app, $this->accessToken, 'POST', $endpoint, $params, null, $this->graphVersion); return $this->client->sendRequest($request)->getDecodedBody(); } diff --git a/src/Facebook/FileUpload/FacebookTransferChunk.php b/src/Facebook/FileUpload/TransferChunk.php similarity index 85% rename from src/Facebook/FileUpload/FacebookTransferChunk.php rename to src/Facebook/FileUpload/TransferChunk.php index 99ea7752a..5bbea86bd 100644 --- a/src/Facebook/FileUpload/FacebookTransferChunk.php +++ b/src/Facebook/FileUpload/TransferChunk.php @@ -28,10 +28,10 @@ * * @package Facebook */ -class FacebookTransferChunk +class TransferChunk { /** - * @var FacebookFile The file to chunk during upload. + * @var File The file to chunk during upload. */ private $file; @@ -56,13 +56,13 @@ class FacebookTransferChunk private $videoId; /** - * @param FacebookFile $file - * @param int $uploadSessionId - * @param int $videoId - * @param int $startOffset - * @param int $endOffset + * @param File $file + * @param int $uploadSessionId + * @param int $videoId + * @param int $startOffset + * @param int $endOffset */ - public function __construct(FacebookFile $file, $uploadSessionId, $videoId, $startOffset, $endOffset) + public function __construct(File $file, $uploadSessionId, $videoId, $startOffset, $endOffset) { $this->file = $file; $this->uploadSessionId = $uploadSessionId; @@ -74,7 +74,7 @@ public function __construct(FacebookFile $file, $uploadSessionId, $videoId, $sta /** * Return the file entity. * - * @return FacebookFile + * @return File */ public function getFile() { @@ -84,13 +84,13 @@ public function getFile() /** * Return a FacebookFile entity with partial content. * - * @return FacebookFile + * @return File */ public function getPartialFile() { $maxLength = $this->endOffset - $this->startOffset; - return new FacebookFile($this->file->getFilePath(), $maxLength, $this->startOffset); + return new File($this->file->getFilePath(), $maxLength, $this->startOffset); } /** diff --git a/src/Facebook/FileUpload/FacebookVideo.php b/src/Facebook/FileUpload/Video.php similarity index 96% rename from src/Facebook/FileUpload/FacebookVideo.php rename to src/Facebook/FileUpload/Video.php index ee6dd5389..f966520db 100644 --- a/src/Facebook/FileUpload/FacebookVideo.php +++ b/src/Facebook/FileUpload/Video.php @@ -28,6 +28,6 @@ * * @package Facebook */ -class FacebookVideo extends FacebookFile +class Video extends File { } diff --git a/src/Facebook/GraphNodes/GraphAchievement.php b/src/Facebook/GraphNodes/GraphAchievement.php index 31508ee45..76af42c39 100644 --- a/src/Facebook/GraphNodes/GraphAchievement.php +++ b/src/Facebook/GraphNodes/GraphAchievement.php @@ -33,7 +33,7 @@ class GraphAchievement extends GraphNode /** * @var array Maps object key names to Graph object types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'from' => '\Facebook\GraphNodes\GraphUser', 'application' => '\Facebook\GraphNodes\GraphApplication', ]; diff --git a/src/Facebook/GraphNodes/GraphAlbum.php b/src/Facebook/GraphNodes/GraphAlbum.php index 52f19b51f..fa3387218 100644 --- a/src/Facebook/GraphNodes/GraphAlbum.php +++ b/src/Facebook/GraphNodes/GraphAlbum.php @@ -34,7 +34,7 @@ class GraphAlbum extends GraphNode /** * @var array Maps object key names to Graph object types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'from' => '\Facebook\GraphNodes\GraphUser', 'place' => '\Facebook\GraphNodes\GraphPage', ]; diff --git a/src/Facebook/GraphNodes/GraphEdge.php b/src/Facebook/GraphNodes/GraphEdge.php index f6f4970c0..674380280 100644 --- a/src/Facebook/GraphNodes/GraphEdge.php +++ b/src/Facebook/GraphNodes/GraphEdge.php @@ -23,7 +23,7 @@ */ namespace Facebook\GraphNodes; -use Facebook\FacebookRequest; +use Facebook\Request; use Facebook\Url\FacebookUrlManipulator; use Facebook\Exceptions\FacebookSDKException; @@ -35,7 +35,7 @@ class GraphEdge extends Collection { /** - * @var FacebookRequest The original request that generated this data. + * @var Request The original request that generated this data. */ protected $request; @@ -57,13 +57,13 @@ class GraphEdge extends Collection /** * Init this collection of GraphNode's. * - * @param FacebookRequest $request The original request that generated this data. - * @param array $data An array of GraphNode's. - * @param array $metaData An array of Graph meta data like pagination, etc. - * @param string|null $parentEdgeEndpoint The parent Graph edge endpoint that generated the list. - * @param string|null $subclassName The subclass of the child GraphNode's. + * @param Request $request The original request that generated this data. + * @param array $data An array of GraphNode's. + * @param array $metaData An array of Graph meta data like pagination, etc. + * @param string|null $parentEdgeEndpoint The parent Graph edge endpoint that generated the list. + * @param string|null $subclassName The subclass of the child GraphNode's. */ - public function __construct(FacebookRequest $request, array $data = [], array $metaData = [], $parentEdgeEndpoint = null, $subclassName = null) + public function __construct(Request $request, array $data = [], array $metaData = [], $parentEdgeEndpoint = null, $subclassName = null) { $this->request = $request; $this->metaData = $metaData; @@ -179,7 +179,7 @@ public function validateForPagination() * * @param string $direction The direction of the page: next|previous * - * @return FacebookRequest|null + * @return Request|null * * @throws FacebookSDKException */ @@ -199,7 +199,7 @@ public function getPaginationRequest($direction) /** * Gets the request object needed to make a "next" page request. * - * @return FacebookRequest|null + * @return Request|null * * @throws FacebookSDKException */ @@ -211,7 +211,7 @@ public function getNextPageRequest() /** * Gets the request object needed to make a "previous" page request. * - * @return FacebookRequest|null + * @return Request|null * * @throws FacebookSDKException */ diff --git a/src/Facebook/GraphNodes/GraphEvent.php b/src/Facebook/GraphNodes/GraphEvent.php index a470d89f9..c44b23c08 100644 --- a/src/Facebook/GraphNodes/GraphEvent.php +++ b/src/Facebook/GraphNodes/GraphEvent.php @@ -33,7 +33,7 @@ class GraphEvent extends GraphNode /** * @var array Maps object key names to GraphNode types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'cover' => '\Facebook\GraphNodes\GraphCoverPhoto', 'place' => '\Facebook\GraphNodes\GraphPage', 'picture' => '\Facebook\GraphNodes\GraphPicture', diff --git a/src/Facebook/GraphNodes/GraphGroup.php b/src/Facebook/GraphNodes/GraphGroup.php index 6217bd4dc..a8d39307c 100644 --- a/src/Facebook/GraphNodes/GraphGroup.php +++ b/src/Facebook/GraphNodes/GraphGroup.php @@ -33,7 +33,7 @@ class GraphGroup extends GraphNode /** * @var array Maps object key names to GraphNode types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'cover' => '\Facebook\GraphNodes\GraphCoverPhoto', 'venue' => '\Facebook\GraphNodes\GraphLocation', ]; diff --git a/src/Facebook/GraphNodes/GraphList.php b/src/Facebook/GraphNodes/GraphList.php deleted file mode 100644 index 3dfbd4975..000000000 --- a/src/Facebook/GraphNodes/GraphList.php +++ /dev/null @@ -1,36 +0,0 @@ -castItems($data)); + $this->fields = $this->castFields($data); } /** - * Iterates over an array and detects the types each node - * should be cast to and returns all the items as an array. + * Gets the value of a field from the Graph node. * + * @param string $name the field to retrieve + * @param mixed $default the default to return if the field doesn't exist + */ + public function getField(string $name, mixed $default = null): mixed + { + if (isset($this->fields[$name])) { + return $this->fields[$name]; + } + + return $default; + } + + + /** + * Returns a list of all fields set on the object. + * @return array + */ + public function getFieldNames(): array + { + return array_keys($this->fields); + } + + + /** + * Get all the fields in the node. + * @return array + */ + public function getFields(): array + { + return $this->fields; + } + + + /** + * @return array + */ + public function asArray(): array + { + return array_map(function ($value) { + if ($value instanceof self || $value instanceof GraphEdge) { + return $value->asArray(); + } + + return $value; + }, $this->fields); + } + + + /** + * Convert the collection to its string representation. + */ + public function __toString(): string + { + return json_encode($this->uncastFields()); + } + + + /** + * @return array + */ + public static function getNodeMap(): array + { + return static::$graphNodeMap; + } + + /** + * Iterates over an array and detects the types each node + * should be cast to and returns all the fields as an array. * @TODO Add auto-casting to AccessToken entities. * - * @param array $data The array to iterate over. + * @param array $data * * @return array */ - public function castItems(array $data) + private function castFields(array $data): array { - $items = []; + $fields = []; foreach ($data as $k => $v) { - if ($this->shouldCastAsDateTime($k) - && (is_numeric($v) - || $this->isIso8601DateString($v)) - ) { - $items[$k] = $this->castToDateTime($v); + if ($this->shouldCastAsDateTime($k) && (is_numeric($v) || $this->isIso8601DateString($v))) { + $fields[$k] = $this->castToDateTime($v); } elseif ($k === 'birthday') { - $items[$k] = $this->castToBirthday($v); + $fields[$k] = $this->castToBirthday($v); } else { - $items[$k] = $v; + $fields[$k] = $v; } } - return $items; + return $fields; } /** * Uncasts any auto-casted datatypes. - * Basically the reverse of castItems(). - * + * Basically the reverse of castFields(). * @return array */ - public function uncastItems() + private function uncastFields(): array { - $items = $this->asArray(); + $fields = $this->asArray(); return array_map(function ($v) { if ($v instanceof \DateTime) { - return $v->format(\DateTime::ISO8601); + return $v->format(DateTimeInterface::ISO8601); } return $v; - }, $items); - } - - /** - * Get the collection of items as JSON. - * - * @param int $options - * - * @return string - */ - public function asJson($options = 0) - { - return json_encode($this->uncastItems(), $options); + }, $fields); } /** @@ -117,7 +178,7 @@ public function asJson($options = 0) * @see http://www.cl.cam.ac.uk/~mgk25/iso-time.html * @see http://en.wikipedia.org/wiki/ISO_8601 */ - public function isIso8601DateString($string) + public function isIso8601DateString(string $string): bool { // This insane regex was yoinked from here: // http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ @@ -136,22 +197,22 @@ public function isIso8601DateString($string) /** * Determines if a value from Graph should be cast to DateTime. * - * @param string $key + * @param mixed $key * * @return boolean */ - public function shouldCastAsDateTime($key) + public function shouldCastAsDateTime(mixed $key): bool { return in_array($key, [ 'created_time', 'updated_time', 'start_time', + 'stop_time', 'end_time', 'backdated_time', 'issued_at', 'expires_at', 'publish_time', - 'joined' ], true); } @@ -162,7 +223,7 @@ public function shouldCastAsDateTime($key) * * @return \DateTime */ - public function castToDateTime($value) + public function castToDateTime(int|string $value): \DateTime { if (is_int($value)) { $dt = new \DateTime(); @@ -181,18 +242,8 @@ public function castToDateTime($value) * * @return Birthday */ - public function castToBirthday($value) + public function castToBirthday(string $value): Birthday { return new Birthday($value); } - - /** - * Getter for $graphObjectMap. - * - * @return array - */ - public static function getObjectMap() - { - return static::$graphObjectMap; - } } diff --git a/src/Facebook/GraphNodes/GraphNodeFactory.php b/src/Facebook/GraphNodes/GraphNodeFactory.php index 937128bb3..af6667577 100644 --- a/src/Facebook/GraphNodes/GraphNodeFactory.php +++ b/src/Facebook/GraphNodes/GraphNodeFactory.php @@ -1,4 +1,6 @@ response = $response; $this->decodedBody = $response->getDecodedBody(); } /** * Tries to convert a FacebookResponse entity into a GraphNode. * - * @param string|null $subclassName The GraphNode sub class to cast to. + * @param string|null $subclassName The GraphNode subclass to cast to. * * @return GraphNode * * @throws FacebookSDKException */ - public function makeGraphNode($subclassName = null) + public function makeGraphNode(string $subclassName = null): GraphNode { - $this->validateResponseAsArray(); $this->validateResponseCastableAsGraphNode(); return $this->castAsGraphNodeOrGraphEdge($this->decodedBody, $subclassName); @@ -98,11 +95,11 @@ public function makeGraphNode($subclassName = null) /** * Convenience method for creating a GraphAchievement collection. * - * @return GraphAchievement + * @return \Facebook\GraphNodes\GraphAchievement|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphAchievement() + public function makeGraphAchievement(): GraphAchievement|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphAchievement'); } @@ -110,11 +107,11 @@ public function makeGraphAchievement() /** * Convenience method for creating a GraphAlbum collection. * - * @return GraphAlbum + * @return \Facebook\GraphNodes\GraphAlbum|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphAlbum() + public function makeGraphAlbum(): GraphAlbum|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphAlbum'); } @@ -122,11 +119,11 @@ public function makeGraphAlbum() /** * Convenience method for creating a GraphPage collection. * - * @return GraphPage + * @return \Facebook\GraphNodes\GraphPage|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphPage() + public function makeGraphPage(): GraphPage|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphPage'); } @@ -134,11 +131,11 @@ public function makeGraphPage() /** * Convenience method for creating a GraphSessionInfo collection. * - * @return GraphSessionInfo + * @return \Facebook\GraphNodes\GraphSessionInfo|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphSessionInfo() + public function makeGraphSessionInfo(): GraphSessionInfo|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphSessionInfo'); } @@ -146,11 +143,11 @@ public function makeGraphSessionInfo() /** * Convenience method for creating a GraphUser collection. * - * @return GraphUser + * @return \Facebook\GraphNodes\GraphUser|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphUser() + public function makeGraphUser(): GraphUser|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphUser'); } @@ -158,11 +155,11 @@ public function makeGraphUser() /** * Convenience method for creating a GraphEvent collection. * - * @return GraphEvent + * @return \Facebook\GraphNodes\GraphEvent|\Facebook\GraphNodes\GraphNode * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphEvent() + public function makeGraphEvent(): GraphEvent|GraphNode { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphEvent'); } @@ -170,11 +167,11 @@ public function makeGraphEvent() /** * Convenience method for creating a GraphGroup collection. * - * @return GraphGroup + * @return \Facebook\GraphNodes\GraphNode|\Facebook\GraphNodes\GraphGroup * - * @throws FacebookSDKException + * @throws \Facebook\Exceptions\FacebookSDKException */ - public function makeGraphGroup() + public function makeGraphGroup(): GraphNode|GraphGroup { return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphGroup'); } @@ -182,16 +179,15 @@ public function makeGraphGroup() /** * Tries to convert a FacebookResponse entity into a GraphEdge. * - * @param string|null $subclassName The GraphNode sub class to cast the list items to. + * @param string|null $subclassName The GraphNode subclass to cast the list items to. * @param boolean $auto_prefix Toggle to auto-prefix the subclass name. * * @return GraphEdge * * @throws FacebookSDKException */ - public function makeGraphEdge($subclassName = null, $auto_prefix = true) + public function makeGraphEdge(string $subclassName = null, bool $auto_prefix = true): GraphEdge { - $this->validateResponseAsArray(); $this->validateResponseCastableAsGraphEdge(); if ($subclassName && $auto_prefix) { @@ -201,18 +197,6 @@ public function makeGraphEdge($subclassName = null, $auto_prefix = true) return $this->castAsGraphNodeOrGraphEdge($this->decodedBody, $subclassName); } - /** - * Validates the decoded body. - * - * @throws FacebookSDKException - */ - public function validateResponseAsArray() - { - if (!is_array($this->decodedBody)) { - throw new FacebookSDKException('Unable to get response from Graph as array.', 620); - } - } - /** * Validates that the return data can be cast as a GraphNode. * @@ -253,13 +237,13 @@ public function validateResponseCastableAsGraphEdge() * * @throws FacebookSDKException */ - public function safelyMakeGraphNode(array $data, $subclassName = null) + public function safelyMakeGraphNode(array $data, string $subclassName = null): GraphNode { $subclassName = $subclassName ?: static::BASE_GRAPH_NODE_CLASS; static::validateSubclass($subclassName); // Remember the parent node ID - $parentNodeId = isset($data['id']) ? $data['id'] : null; + $parentNodeId = $data['id'] ?? null; $items = []; @@ -269,11 +253,8 @@ public function safelyMakeGraphNode(array $data, $subclassName = null) // Detect any smart-casting from the $graphObjectMap array. // This is always empty on the GraphNode collection, but subclasses can define // their own array of smart-casting types. - $graphObjectMap = $subclassName::getObjectMap(); - $objectSubClass = isset($graphObjectMap[$k]) - ? $graphObjectMap[$k] - : null; - + $graphObjectMap = $subclassName::getNodeMap(); + $objectSubClass = $graphObjectMap[$k] ?? null; // Could be a GraphEdge or GraphNode $items[$k] = $this->castAsGraphNodeOrGraphEdge($v, $objectSubClass, $k, $parentNodeId); } else { @@ -296,7 +277,12 @@ public function safelyMakeGraphNode(array $data, $subclassName = null) * * @throws FacebookSDKException */ - public function castAsGraphNodeOrGraphEdge(array $data, $subclassName = null, $parentKey = null, $parentNodeId = null) + public function castAsGraphNodeOrGraphEdge( + array $data, + string $subclassName = null, + string $parentKey = null, + string $parentNodeId = null, + ): GraphEdge|GraphNode { if (isset($data['data'])) { // Create GraphEdge @@ -325,7 +311,12 @@ public function castAsGraphNodeOrGraphEdge(array $data, $subclassName = null, $p * * @throws FacebookSDKException */ - public function safelyMakeGraphEdge(array $data, $subclassName = null, $parentKey = null, $parentNodeId = null) + public function safelyMakeGraphEdge( + array $data, + string $subclassName = null, + string $parentKey = null, + string $parentNodeId = null, + ): GraphEdge { if (!isset($data['data'])) { throw new FacebookSDKException('Cannot cast data to GraphEdge. Expected a "data" key.', 620); @@ -346,13 +337,13 @@ public function safelyMakeGraphEdge(array $data, $subclassName = null, $parentKe } /** - * Get the meta data from a list in a Graph response. + * Get the metadata from a list in a Graph response. * * @param array $data The Graph response. * * @return array */ - public function getMetaData(array $data) + public function getMetaData(array $data): array { unset($data['data']); @@ -360,13 +351,13 @@ public function getMetaData(array $data) } /** - * Determines whether or not the data should be cast as a GraphEdge. + * Determines whether the data should be cast as a GraphEdge. * * @param array $data * * @return boolean */ - public static function isCastableAsGraphEdge(array $data) + public static function isCastableAsGraphEdge(array $data): bool { if ($data === []) { return true; @@ -383,9 +374,12 @@ public static function isCastableAsGraphEdge(array $data) * * @throws FacebookSDKException */ - public static function validateSubclass($subclassName) + public static function validateSubclass(string $subclassName): void { - if ($subclassName == static::BASE_GRAPH_NODE_CLASS || is_subclass_of($subclassName, static::BASE_GRAPH_NODE_CLASS)) { + if ( + $subclassName == static::BASE_GRAPH_NODE_CLASS + || is_subclass_of($subclassName, static::BASE_GRAPH_NODE_CLASS) + ) { return; } diff --git a/src/Facebook/GraphNodes/GraphObject.php b/src/Facebook/GraphNodes/GraphObject.php deleted file mode 100644 index 0633c405b..000000000 --- a/src/Facebook/GraphNodes/GraphObject.php +++ /dev/null @@ -1,36 +0,0 @@ -makeGraphNode($subclassName); - } - - /** - * Convenience method for creating a GraphEvent collection. - * - * @return GraphEvent - * - * @throws FacebookSDKException - */ - public function makeGraphEvent() - { - return $this->makeGraphNode(static::BASE_GRAPH_OBJECT_PREFIX . 'GraphEvent'); - } - - /** - * Tries to convert a FacebookResponse entity into a GraphEdge. - * - * @param string|null $subclassName The GraphNode sub class to cast the list items to. - * @param boolean $auto_prefix Toggle to auto-prefix the subclass name. - * - * @return GraphEdge - * - * @deprecated 5.0.0 GraphObjectFactory has been renamed to GraphNodeFactory - */ - public function makeGraphList($subclassName = null, $auto_prefix = true) - { - return $this->makeGraphEdge($subclassName, $auto_prefix); - } -} diff --git a/src/Facebook/GraphNodes/GraphPage.php b/src/Facebook/GraphNodes/GraphPage.php index 503b96b55..cdd624748 100644 --- a/src/Facebook/GraphNodes/GraphPage.php +++ b/src/Facebook/GraphNodes/GraphPage.php @@ -33,7 +33,7 @@ class GraphPage extends GraphNode /** * @var array Maps object key names to Graph object types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'best_page' => '\Facebook\GraphNodes\GraphPage', 'global_brand_parent_page' => '\Facebook\GraphNodes\GraphPage', 'location' => '\Facebook\GraphNodes\GraphLocation', diff --git a/src/Facebook/GraphNodes/GraphUser.php b/src/Facebook/GraphNodes/GraphUser.php index 6e1ed8f54..08bf72c13 100644 --- a/src/Facebook/GraphNodes/GraphUser.php +++ b/src/Facebook/GraphNodes/GraphUser.php @@ -33,7 +33,7 @@ class GraphUser extends GraphNode /** * @var array Maps object key names to Graph object types. */ - protected static $graphObjectMap = [ + protected static array $graphObjectMap = [ 'hometown' => '\Facebook\GraphNodes\GraphPage', 'location' => '\Facebook\GraphNodes\GraphPage', 'significant_other' => '\Facebook\GraphNodes\GraphUser', diff --git a/src/Facebook/Helpers/FacebookCanvasHelper.php b/src/Facebook/Helpers/CanvasHelper.php similarity index 95% rename from src/Facebook/Helpers/FacebookCanvasHelper.php rename to src/Facebook/Helpers/CanvasHelper.php index 7f3466ff7..25b9e5597 100644 --- a/src/Facebook/Helpers/FacebookCanvasHelper.php +++ b/src/Facebook/Helpers/CanvasHelper.php @@ -28,7 +28,7 @@ * * @package Facebook */ -class FacebookCanvasHelper extends FacebookSignedRequestFromInputHelper +class CanvasHelper extends FacebookSignedRequestFromInputHelper { /** * Returns the app data value. diff --git a/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php b/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php index 4044da107..3e386e1ed 100644 --- a/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php +++ b/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php @@ -24,8 +24,8 @@ namespace Facebook\Helpers; use Facebook\Facebook; -use Facebook\FacebookApp; -use Facebook\FacebookClient; +use Facebook\Application; +use Facebook\Client; use Facebook\SignedRequest; use Facebook\Authentication\AccessToken; use Facebook\Authentication\OAuth2Client; @@ -43,7 +43,7 @@ abstract class FacebookSignedRequestFromInputHelper protected $signedRequest; /** - * @var FacebookApp The FacebookApp entity. + * @var Application The FacebookApp entity. */ protected $app; @@ -55,11 +55,11 @@ abstract class FacebookSignedRequestFromInputHelper /** * Initialize the helper and process available signed request data. * - * @param FacebookApp $app The FacebookApp entity. - * @param FacebookClient $client The client to make HTTP requests. - * @param string|null $graphVersion The version of Graph to use. + * @param Application $app The FacebookApp entity. + * @param Client $client The client to make HTTP requests. + * @param string|null $graphVersion The version of Graph to use. */ - public function __construct(FacebookApp $app, FacebookClient $client, $graphVersion = null) + public function __construct(Application $app, Client $client, $graphVersion = null) { $this->app = $app; $graphVersion = $graphVersion ?: Facebook::DEFAULT_GRAPH_VERSION; diff --git a/src/Facebook/Helpers/FacebookJavaScriptHelper.php b/src/Facebook/Helpers/JavaScriptHelper.php similarity index 94% rename from src/Facebook/Helpers/FacebookJavaScriptHelper.php rename to src/Facebook/Helpers/JavaScriptHelper.php index 01a76b8b2..4b3e59993 100644 --- a/src/Facebook/Helpers/FacebookJavaScriptHelper.php +++ b/src/Facebook/Helpers/JavaScriptHelper.php @@ -28,7 +28,7 @@ * * @package Facebook */ -class FacebookJavaScriptHelper extends FacebookSignedRequestFromInputHelper +class JavaScriptHelper extends FacebookSignedRequestFromInputHelper { /** * Get raw signed request from the cookie. diff --git a/src/Facebook/Helpers/FacebookPageTabHelper.php b/src/Facebook/Helpers/PageTabHelper.php similarity index 84% rename from src/Facebook/Helpers/FacebookPageTabHelper.php rename to src/Facebook/Helpers/PageTabHelper.php index da2c356c7..205f2d8c0 100644 --- a/src/Facebook/Helpers/FacebookPageTabHelper.php +++ b/src/Facebook/Helpers/PageTabHelper.php @@ -23,15 +23,15 @@ */ namespace Facebook\Helpers; -use Facebook\FacebookApp; -use Facebook\FacebookClient; +use Facebook\Application; +use Facebook\Client; /** * Class FacebookPageTabHelper * * @package Facebook */ -class FacebookPageTabHelper extends FacebookCanvasHelper +class PageTabHelper extends CanvasHelper { /** * @var array|null @@ -41,11 +41,11 @@ class FacebookPageTabHelper extends FacebookCanvasHelper /** * Initialize the helper and process available signed request data. * - * @param FacebookApp $app The FacebookApp entity. - * @param FacebookClient $client The client to make HTTP requests. - * @param string|null $graphVersion The version of Graph to use. + * @param Application $app The FacebookApp entity. + * @param Client $client The client to make HTTP requests. + * @param string|null $graphVersion The version of Graph to use. */ - public function __construct(FacebookApp $app, FacebookClient $client, $graphVersion = null) + public function __construct(Application $app, Client $client, $graphVersion = null) { parent::__construct($app, $client, $graphVersion); diff --git a/src/Facebook/Helpers/FacebookRedirectLoginHelper.php b/src/Facebook/Helpers/RedirectLoginHelper.php similarity index 70% rename from src/Facebook/Helpers/FacebookRedirectLoginHelper.php rename to src/Facebook/Helpers/RedirectLoginHelper.php index 6003a20f3..0eb3710d6 100644 --- a/src/Facebook/Helpers/FacebookRedirectLoginHelper.php +++ b/src/Facebook/Helpers/RedirectLoginHelper.php @@ -1,4 +1,6 @@ oAuth2Client = $oAuth2Client; - $this->persistentDataHandler = $persistentDataHandler ?: new FacebookSessionPersistentDataHandler(); - $this->urlDetectionHandler = $urlHandler ?: new FacebookUrlDetectionHandler(); - $this->pseudoRandomStringGenerator = PseudoRandomStringGeneratorFactory::createPseudoRandomStringGenerator($prsg); + $this->persistentDataHandler = $persistentData ?? new FacebookSessionPersistentDataHandler; + $this->urlDetectionHandler = $urlDetection ?? new UrlDetectionHandler; } /** * Returns the persistent data handler. - * - * @return PersistentDataInterface */ - public function getPersistentDataHandler() + public function getPersistentDataHandler(): PersistentDataInterface { return $this->persistentDataHandler; } + /** * Returns the URL detection handler. * * @return UrlDetectionInterface */ - public function getUrlDetectionHandler() + public function getUrlDetectionHandler(): UrlDetectionInterface { return $this->urlDetectionHandler; } /** - * Returns the cryptographically secure pseudo-random string generator. - * - * @return PseudoRandomStringGeneratorInterface - */ - public function getPseudoRandomStringGenerator() - { - return $this->pseudoRandomStringGenerator; - } - - /** - * Stores CSRF state and returns a URL to which the user should be sent to in order to continue the login process with Facebook. + * Stores CSRF state and returns a URL to which the user should be sent to in order to continue the login process + * with Facebook. * * @param string $redirectUrl The URL Facebook should redirect users to after login. * @param array $scope List of permissions to request during login. @@ -120,14 +103,19 @@ public function getPseudoRandomStringGenerator() * * @return string */ - private function makeUrl($redirectUrl, array $scope, array $params = [], $separator = '&') + private function makeUrl(string $redirectUrl, array $scope, array $params = [], string $separator = '&'): string { - $state = $this->persistentDataHandler->get('state') ?: $this->pseudoRandomStringGenerator->getPseudoRandomString(static::CSRF_LENGTH); + $state = $this->persistentDataHandler->get('state') ?? $this->getPseudoRandomString(); $this->persistentDataHandler->set('state', $state); return $this->oAuth2Client->getAuthorizationUrl($redirectUrl, $state, $scope, $params, $separator); } + private function getPseudoRandomString(): string + { + return bin2hex(random_bytes(static::CSRF_LENGTH)); + } + /** * Returns the URL to send the user in order to login to Facebook. * @@ -137,7 +125,7 @@ private function makeUrl($redirectUrl, array $scope, array $params = [], $separa * * @return string */ - public function getLoginUrl($redirectUrl, array $scope = [], $separator = '&') + public function getLoginUrl(string $redirectUrl, array $scope = [], string $separator = '&'): string { return $this->makeUrl($redirectUrl, $scope, [], $separator); } @@ -145,7 +133,7 @@ public function getLoginUrl($redirectUrl, array $scope = [], $separator = '&') /** * Returns the URL to send the user in order to log out of Facebook. * - * @param AccessToken|string $accessToken The access token that will be logged out. + * @param string|AccessToken $accessToken The access token that will be logged out. * @param string $next The url Facebook should redirect the user to after a successful logout. * @param string $separator The separator to use in http_build_query(). * @@ -153,7 +141,7 @@ public function getLoginUrl($redirectUrl, array $scope = [], $separator = '&') * * @throws FacebookSDKException */ - public function getLogoutUrl($accessToken, $next, $separator = '&') + public function getLogoutUrl(string|AccessToken $accessToken, string $next, string $separator = '&'): string { if (!$accessToken instanceof AccessToken) { $accessToken = new AccessToken($accessToken); @@ -168,7 +156,7 @@ public function getLogoutUrl($accessToken, $next, $separator = '&') 'access_token' => $accessToken->getValue(), ]; - return 'https://www.facebook.com/logout.php?' . http_build_query($params, null, $separator); + return 'https://www.facebook.com/logout.php?' . http_build_query($params, '', $separator); } /** @@ -180,7 +168,7 @@ public function getLogoutUrl($accessToken, $next, $separator = '&') * * @return string */ - public function getReRequestUrl($redirectUrl, array $scope = [], $separator = '&') + public function getReRequestUrl(string $redirectUrl, array $scope = [], string $separator = '&'): string { $params = ['auth_type' => 'rerequest']; @@ -196,7 +184,7 @@ public function getReRequestUrl($redirectUrl, array $scope = [], $separator = '& * * @return string */ - public function getReAuthenticationUrl($redirectUrl, array $scope = [], $separator = '&') + public function getReAuthenticationUrl(string $redirectUrl, array $scope = [], string $separator = '&'): string { $params = ['auth_type' => 'reauthenticate']; @@ -212,9 +200,10 @@ public function getReAuthenticationUrl($redirectUrl, array $scope = [], $separat * * @throws FacebookSDKException */ - public function getAccessToken($redirectUrl = null) + public function getAccessToken(string $redirectUrl = null): ?AccessToken { - if (!$code = $this->getCode()) { + $code = $this->getCode(); + if ($code === null) { return null; } @@ -233,14 +222,14 @@ public function getAccessToken($redirectUrl = null) * * @throws FacebookSDKException */ - protected function validateCsrf() + protected function validateCsrf(): void { $state = $this->getState(); - if (!$state) { + if ($state === null) { throw new FacebookSDKException('Cross-site request forgery validation failed. Required GET param "state" missing.'); } $savedState = $this->persistentDataHandler->get('state'); - if (!$savedState) { + if ($savedState === null) { throw new FacebookSDKException('Cross-site request forgery validation failed. Required param "state" missing from persistent data.'); } @@ -254,7 +243,7 @@ protected function validateCsrf() /** * Resets the CSRF so that it doesn't get reused. */ - private function resetCsrf() + private function resetCsrf(): void { $this->persistentDataHandler->set('state', null); } @@ -264,7 +253,7 @@ private function resetCsrf() * * @return string|null */ - protected function getCode() + #[Pure] protected function getCode(): ?string { return $this->getInput('code'); } @@ -274,7 +263,7 @@ protected function getCode() * * @return string|null */ - protected function getState() + #[Pure] protected function getState(): ?string { return $this->getInput('state'); } @@ -284,7 +273,7 @@ protected function getState() * * @return string|null */ - public function getErrorCode() + #[Pure] public function getErrorCode(): ?string { return $this->getInput('error_code'); } @@ -294,7 +283,7 @@ public function getErrorCode() * * @return string|null */ - public function getError() + #[Pure] public function getError(): ?string { return $this->getInput('error'); } @@ -304,7 +293,7 @@ public function getError() * * @return string|null */ - public function getErrorReason() + #[Pure] public function getErrorReason(): ?string { return $this->getInput('error_reason'); } @@ -314,7 +303,7 @@ public function getErrorReason() * * @return string|null */ - public function getErrorDescription() + #[Pure] public function getErrorDescription(): ?string { return $this->getInput('error_description'); } @@ -326,8 +315,8 @@ public function getErrorDescription() * * @return string|null */ - private function getInput($key) + private function getInput(string $key): ?string { - return isset($_GET[$key]) ? $_GET[$key] : null; + return $_GET[$key] ?? null; } } diff --git a/src/Facebook/Http/RequestBodyMultipart.php b/src/Facebook/Http/RequestBodyMultipart.php index e43695a4f..3d265315c 100644 --- a/src/Facebook/Http/RequestBodyMultipart.php +++ b/src/Facebook/Http/RequestBodyMultipart.php @@ -23,7 +23,7 @@ */ namespace Facebook\Http; -use Facebook\FileUpload\FacebookFile; +use Facebook\FileUpload\File; /** * Class RequestBodyMultipartt @@ -100,12 +100,12 @@ public function getBoundary() /** * Get the string needed to transfer a file. * - * @param string $name - * @param FacebookFile $file + * @param string $name + * @param File $file * * @return string */ - private function getFileString($name, FacebookFile $file) + private function getFileString($name, File $file) { return sprintf( "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"%s\r\n\r\n%s\r\n", @@ -144,7 +144,7 @@ private function getParamString($name, $value) */ private function getNestedParams(array $params) { - $query = http_build_query($params, null, '&'); + $query = http_build_query($params); $params = explode('&', $query); $result = []; @@ -159,11 +159,11 @@ private function getNestedParams(array $params) /** * Get the headers needed before transferring the content of a POST file. * - * @param FacebookFile $file + * @param File $file * * @return string */ - protected function getFileHeaders(FacebookFile $file) + protected function getFileHeaders(File $file) { return "\r\nContent-Type: {$file->getMimetype()}"; } diff --git a/src/Facebook/Http/RequestBodyUrlEncoded.php b/src/Facebook/Http/RequestBodyUrlEncoded.php index c1e35f43d..6004d5ff5 100644 --- a/src/Facebook/Http/RequestBodyUrlEncoded.php +++ b/src/Facebook/Http/RequestBodyUrlEncoded.php @@ -33,7 +33,7 @@ class RequestBodyUrlEncoded implements RequestBodyInterface /** * @var array The parameters to send with this request. */ - protected $params = []; + protected array $params = []; /** * Creates a new GraphUrlEncodedBody entity. @@ -48,8 +48,8 @@ public function __construct(array $params) /** * @inheritdoc */ - public function getBody() + public function getBody(): string { - return http_build_query($this->params, null, '&'); + return http_build_query($this->params); } } diff --git a/src/Facebook/HttpClients/FacebookCurl.php b/src/Facebook/HttpClients/FacebookCurl.php deleted file mode 100644 index 28e4ba598..000000000 --- a/src/Facebook/HttpClients/FacebookCurl.php +++ /dev/null @@ -1,129 +0,0 @@ -curl = curl_init(); - } - - /** - * Set a curl option - * - * @param $key - * @param $value - */ - public function setopt($key, $value) - { - curl_setopt($this->curl, $key, $value); - } - - /** - * Set an array of options to a curl resource - * - * @param array $options - */ - public function setoptArray(array $options) - { - curl_setopt_array($this->curl, $options); - } - - /** - * Send a curl request - * - * @return mixed - */ - public function exec() - { - return curl_exec($this->curl); - } - - /** - * Return the curl error number - * - * @return int - */ - public function errno() - { - return curl_errno($this->curl); - } - - /** - * Return the curl error message - * - * @return string - */ - public function error() - { - return curl_error($this->curl); - } - - /** - * Get info from a curl reference - * - * @param $type - * - * @return mixed - */ - public function getinfo($type) - { - return curl_getinfo($this->curl, $type); - } - - /** - * Get the currently installed curl version - * - * @return array - */ - public function version() - { - return curl_version(); - } - - /** - * Close the resource connection to curl - */ - public function close() - { - curl_close($this->curl); - } -} diff --git a/src/Facebook/HttpClients/FacebookCurlHttpClient.php b/src/Facebook/HttpClients/FacebookCurlHttpClient.php deleted file mode 100644 index 9516cc835..000000000 --- a/src/Facebook/HttpClients/FacebookCurlHttpClient.php +++ /dev/null @@ -1,163 +0,0 @@ -facebookCurl = $facebookCurl ?: new FacebookCurl(); - } - - /** - * @inheritdoc - */ - public function send($url, $method, $body, array $headers, $timeOut) - { - $this->openConnection($url, $method, $body, $headers, $timeOut); - $this->sendRequest(); - - if ($curlErrorCode = $this->facebookCurl->errno()) { - throw new FacebookSDKException($this->facebookCurl->error(), $curlErrorCode); - } - - // Separate the raw headers from the raw body - list($rawHeaders, $rawBody) = $this->extractResponseHeadersAndBody(); - - $this->closeConnection(); - - return new GraphRawResponse($rawHeaders, $rawBody); - } - - /** - * Opens a new curl connection. - * - * @param string $url The endpoint to send the request to. - * @param string $method The request method. - * @param string $body The body of the request. - * @param array $headers The request headers. - * @param int $timeOut The timeout in seconds for the request. - */ - public function openConnection($url, $method, $body, array $headers, $timeOut) - { - $options = [ - CURLOPT_CUSTOMREQUEST => $method, - CURLOPT_HTTPHEADER => $this->compileRequestHeaders($headers), - CURLOPT_URL => $url, - CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_TIMEOUT => $timeOut, - CURLOPT_RETURNTRANSFER => true, // Return response as string - CURLOPT_HEADER => true, // Enable header processing - CURLOPT_SSL_VERIFYHOST => 2, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_CAINFO => __DIR__ . '/certs/DigiCertHighAssuranceEVRootCA.pem', - ]; - - if ($method !== "GET") { - $options[CURLOPT_POSTFIELDS] = $body; - } - - $this->facebookCurl->init(); - $this->facebookCurl->setoptArray($options); - } - - /** - * Closes an existing curl connection - */ - public function closeConnection() - { - $this->facebookCurl->close(); - } - - /** - * Send the request and get the raw response from curl - */ - public function sendRequest() - { - $this->rawResponse = $this->facebookCurl->exec(); - } - - /** - * Compiles the request headers into a curl-friendly format. - * - * @param array $headers The request headers. - * - * @return array - */ - public function compileRequestHeaders(array $headers) - { - $return = []; - - foreach ($headers as $key => $value) { - $return[] = $key . ': ' . $value; - } - - return $return; - } - - /** - * Extracts the headers and the body into a two-part array - * - * @return array - */ - public function extractResponseHeadersAndBody() - { - $parts = explode("\r\n\r\n", $this->rawResponse); - $rawBody = array_pop($parts); - $rawHeaders = implode("\r\n\r\n", $parts); - - return [trim($rawHeaders), trim($rawBody)]; - } -} diff --git a/src/Facebook/HttpClients/FacebookGuzzleHttpClient.php b/src/Facebook/HttpClients/FacebookGuzzleHttpClient.php deleted file mode 100644 index 8feb7cb6d..000000000 --- a/src/Facebook/HttpClients/FacebookGuzzleHttpClient.php +++ /dev/null @@ -1,97 +0,0 @@ -guzzleClient = $guzzleClient ?: new Client(); - } - - /** - * @inheritdoc - */ - public function send($url, $method, $body, array $headers, $timeOut) - { - $options = [ - 'headers' => $headers, - 'body' => $body, - 'timeout' => $timeOut, - 'connect_timeout' => 10, - 'verify' => __DIR__ . '/certs/DigiCertHighAssuranceEVRootCA.pem', - ]; - $request = $this->guzzleClient->createRequest($method, $url, $options); - - try { - $rawResponse = $this->guzzleClient->send($request); - } catch (RequestException $e) { - $rawResponse = $e->getResponse(); - - if ($e->getPrevious() instanceof RingException || !$rawResponse instanceof ResponseInterface) { - throw new FacebookSDKException($e->getMessage(), $e->getCode()); - } - } - - $rawHeaders = $this->getHeadersAsString($rawResponse); - $rawBody = $rawResponse->getBody(); - $httpStatusCode = $rawResponse->getStatusCode(); - - return new GraphRawResponse($rawHeaders, $rawBody, $httpStatusCode); - } - - /** - * Returns the Guzzle array of headers as a string. - * - * @param ResponseInterface $response The Guzzle response. - * - * @return string - */ - public function getHeadersAsString(ResponseInterface $response) - { - $headers = $response->getHeaders(); - $rawHeaders = []; - foreach ($headers as $name => $values) { - $rawHeaders[] = $name . ": " . implode(", ", $values); - } - - return implode("\r\n", $rawHeaders); - } -} diff --git a/src/Facebook/HttpClients/FacebookHttpClientInterface.php b/src/Facebook/HttpClients/FacebookHttpClientInterface.php deleted file mode 100644 index 1fbf953d8..000000000 --- a/src/Facebook/HttpClients/FacebookHttpClientInterface.php +++ /dev/null @@ -1,47 +0,0 @@ -stream = stream_context_create($options); - } - - /** - * The response headers from the stream wrapper - * - * @return array - */ - public function getResponseHeaders() - { - return $this->responseHeaders; - } - - /** - * Send a stream wrapped request - * - * @param string $url - * - * @return mixed - */ - public function fileGetContents($url) - { - $rawResponse = file_get_contents($url, false, $this->stream); - $this->responseHeaders = $http_response_header ?: []; - - return $rawResponse; - } -} diff --git a/src/Facebook/HttpClients/FacebookStreamHttpClient.php b/src/Facebook/HttpClients/FacebookStreamHttpClient.php deleted file mode 100644 index 1cdfd5398..000000000 --- a/src/Facebook/HttpClients/FacebookStreamHttpClient.php +++ /dev/null @@ -1,94 +0,0 @@ -facebookStream = $facebookStream ?: new FacebookStream(); - } - - /** - * @inheritdoc - */ - public function send($url, $method, $body, array $headers, $timeOut) - { - $options = [ - 'http' => [ - 'method' => $method, - 'header' => $this->compileHeader($headers), - 'content' => $body, - 'timeout' => $timeOut, - 'ignore_errors' => true - ], - 'ssl' => [ - 'verify_peer' => true, - 'verify_peer_name' => true, - 'allow_self_signed' => true, // All root certificates are self-signed - 'cafile' => __DIR__ . '/certs/DigiCertHighAssuranceEVRootCA.pem', - ], - ]; - - $this->facebookStream->streamContextCreate($options); - $rawBody = $this->facebookStream->fileGetContents($url); - $rawHeaders = $this->facebookStream->getResponseHeaders(); - - if ($rawBody === false || empty($rawHeaders)) { - throw new FacebookSDKException('Stream returned an empty response', 660); - } - - $rawHeaders = implode("\r\n", $rawHeaders); - - return new GraphRawResponse($rawHeaders, $rawBody); - } - - /** - * Formats the headers for use in the stream wrapper. - * - * @param array $headers The request headers. - * - * @return string - */ - public function compileHeader(array $headers) - { - $header = []; - foreach ($headers as $k => $v) { - $header[] = $k . ': ' . $v; - } - - return implode("\r\n", $header); - } -} diff --git a/src/Facebook/HttpClients/HttpClientsFactory.php b/src/Facebook/HttpClients/HttpClientsFactory.php deleted file mode 100644 index d9f2a8d3d..000000000 --- a/src/Facebook/HttpClients/HttpClientsFactory.php +++ /dev/null @@ -1,99 +0,0 @@ -validateLength($length); - - $binaryString = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); - - if ($binaryString === false) { - throw new FacebookSDKException( - static::ERROR_MESSAGE . - 'mcrypt_create_iv() returned an error.' - ); - } - - return $this->binToHex($binaryString, $length); - } -} diff --git a/src/Facebook/PseudoRandomString/OpenSslPseudoRandomStringGenerator.php b/src/Facebook/PseudoRandomString/OpenSslPseudoRandomStringGenerator.php deleted file mode 100644 index 4b4276dc7..000000000 --- a/src/Facebook/PseudoRandomString/OpenSslPseudoRandomStringGenerator.php +++ /dev/null @@ -1,67 +0,0 @@ -validateLength($length); - - $wasCryptographicallyStrong = false; - $binaryString = openssl_random_pseudo_bytes($length, $wasCryptographicallyStrong); - - if ($binaryString === false) { - throw new FacebookSDKException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned an unknown error.'); - } - - if ($wasCryptographicallyStrong !== true) { - throw new FacebookSDKException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned a pseudo-random string but it was not cryptographically secure and cannot be used.'); - } - - return $this->binToHex($binaryString, $length); - } -} diff --git a/src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorFactory.php b/src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorFactory.php deleted file mode 100644 index 412f48135..000000000 --- a/src/Facebook/PseudoRandomString/PseudoRandomStringGeneratorFactory.php +++ /dev/null @@ -1,101 +0,0 @@ -validateLength($length); - - return $this->binToHex(random_bytes($length), $length); - } -} diff --git a/src/Facebook/PseudoRandomString/UrandomPseudoRandomStringGenerator.php b/src/Facebook/PseudoRandomString/UrandomPseudoRandomStringGenerator.php deleted file mode 100644 index 5ab434e6e..000000000 --- a/src/Facebook/PseudoRandomString/UrandomPseudoRandomStringGenerator.php +++ /dev/null @@ -1,89 +0,0 @@ -validateLength($length); - - $stream = fopen('/dev/urandom', 'rb'); - if (!is_resource($stream)) { - throw new FacebookSDKException( - static::ERROR_MESSAGE . - 'Unable to open stream to /dev/urandom.' - ); - } - - if (!defined('HHVM_VERSION')) { - stream_set_read_buffer($stream, 0); - } - - $binaryString = fread($stream, $length); - fclose($stream); - - if (!$binaryString) { - throw new FacebookSDKException( - static::ERROR_MESSAGE . - 'Stream to /dev/urandom returned no data.' - ); - } - - return $this->binToHex($binaryString, $length); - } -} diff --git a/src/Facebook/FacebookRequest.php b/src/Facebook/Request.php similarity index 69% rename from src/Facebook/FacebookRequest.php rename to src/Facebook/Request.php index 2b1008991..992b0f2d0 100644 --- a/src/Facebook/FacebookRequest.php +++ b/src/Facebook/Request.php @@ -1,4 +1,6 @@ setApp($app); + * @param \Facebook\Application|null $application + * @param \Facebook\Authentication\AccessToken|string|null $accessToken + * @param string|null $method + * @param string|null $endpoint + * @param array $params + * @param string|null $eTag + * @param string|null $graphVersion + * + * @throws \Facebook\Exceptions\FacebookSDKException + */ + public function __construct( + Application $application = null, + AccessToken|string $accessToken = null, + string $method = null, + string $endpoint = null, + array $params = [], + string $eTag = null, + protected ?string $graphVersion = null, + ) + { + $this->setApp($application); $this->setAccessToken($accessToken); $this->setMethod($method); $this->setEndpoint($endpoint); $this->setParams($params); $this->setETag($eTag); - $this->graphVersion = $graphVersion ?: Facebook::DEFAULT_GRAPH_VERSION; } /** @@ -110,14 +119,13 @@ public function __construct(FacebookApp $app = null, $accessToken = null, $metho * * @param AccessToken|string|null * - * @return FacebookRequest + * @return Request */ - public function setAccessToken($accessToken) + public function setAccessToken($accessToken): static { - $this->accessToken = $accessToken; - if ($accessToken instanceof AccessToken) { - $this->accessToken = $accessToken->getValue(); - } + $this->accessToken = $accessToken instanceof AccessToken + ? $accessToken->getValue() + : $accessToken; return $this; } @@ -127,11 +135,11 @@ public function setAccessToken($accessToken) * * @param string $accessToken The access token. * - * @return FacebookRequest + * @return Request * * @throws FacebookSDKException */ - public function setAccessTokenFromParams($accessToken) + public function setAccessTokenFromParams(string $accessToken): static { $existingAccessToken = $this->getAccessToken(); if (!$existingAccessToken) { @@ -148,7 +156,7 @@ public function setAccessTokenFromParams($accessToken) * * @return string|null */ - public function getAccessToken() + public function getAccessToken(): ?string { return $this->accessToken; } @@ -158,27 +166,27 @@ public function getAccessToken() * * @return AccessToken|null */ - public function getAccessTokenEntity() + public function getAccessTokenEntity(): ?AccessToken { - return $this->accessToken ? new AccessToken($this->accessToken) : null; + return $this->accessToken !== null ? new AccessToken($this->accessToken) : null; } /** * Set the FacebookApp entity used for this request. * - * @param FacebookApp|null $app + * @param Application|null $application */ - public function setApp(FacebookApp $app = null) + public function setApp(Application $application = null) { - $this->app = $app; + $this->app = $application; } /** * Return the FacebookApp entity used for this request. * - * @return FacebookApp + * @return \Facebook\Application|null */ - public function getApp() + public function getApplication(): ?Application { return $this->app; } @@ -188,13 +196,14 @@ public function getApp() * * @return string|null */ - public function getAppSecretProof() + public function getAppSecretProof(): ?string { - if (!$accessTokenEntity = $this->getAccessTokenEntity()) { + $accessTokenEntity = $this->getAccessTokenEntity(); + if (!$accessTokenEntity instanceof AccessToken) { return null; } - return $accessTokenEntity->getAppSecretProof($this->app->getSecret()); + return $accessTokenEntity->getAppSecretProof((string)$this->app?->getSecret()); } /** @@ -212,12 +221,12 @@ public function validateAccessToken() /** * Set the HTTP method for this request. - * - * @param string */ - public function setMethod($method) + public function setMethod(?string $method): void { - $this->method = strtoupper($method); + if ($method !== null) { + $this->method = strtoupper($method); + } } /** @@ -225,7 +234,7 @@ public function setMethod($method) * * @return string */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -251,12 +260,16 @@ public function validateMethod() * * @param string * - * @return FacebookRequest + * @return Request * * @throws FacebookSDKException */ - public function setEndpoint($endpoint) + public function setEndpoint($endpoint): static { + if ($endpoint === null) { + return $this; + } + // Harvest the access token from the endpoint to keep things in sync $params = FacebookUrlManipulator::getParamsAsArray($endpoint); if (isset($params['access_token'])) { @@ -273,9 +286,9 @@ public function setEndpoint($endpoint) /** * Return the endpoint for this request. * - * @return string + * @return ?string */ - public function getEndpoint() + public function getEndpoint(): ?string { // For batch requests, this will be empty return $this->endpoint; @@ -286,11 +299,11 @@ public function getEndpoint() * * @return array */ - public function getHeaders() + #[Pure] public function getHeaders(): array { $headers = static::getDefaultHeaders(); - if ($this->eTag) { + if ($this->eTag !== null && $this->eTag !== '' && $this->eTag !== '0') { $headers['If-None-Match'] = $this->eTag; } @@ -310,9 +323,9 @@ public function setHeaders(array $headers) /** * Sets the eTag value. * - * @param string $eTag + * @param ?string $eTag */ - public function setETag($eTag) + public function setETag(?string $eTag) { $this->eTag = $eTag; } @@ -322,11 +335,11 @@ public function setETag($eTag) * * @param array $params * - * @return FacebookRequest + * @return Request * * @throws FacebookSDKException */ - public function setParams(array $params = []) + public function setParams(array $params = []): static { if (isset($params['access_token'])) { $this->setAccessTokenFromParams($params['access_token']); @@ -335,8 +348,6 @@ public function setParams(array $params = []) // Don't let these buggers slip in. unset($params['access_token'], $params['appsecret_proof']); - // @TODO Refactor code above with this - //$params = $this->sanitizeAuthenticationParams($params); $params = $this->sanitizeFileParams($params); $this->dangerouslySetParams($params); @@ -348,9 +359,9 @@ public function setParams(array $params = []) * * @param array $params * - * @return FacebookRequest + * @return Request */ - public function dangerouslySetParams(array $params = []) + public function dangerouslySetParams(array $params = []): static { $this->params = array_merge($this->params, $params); @@ -364,10 +375,10 @@ public function dangerouslySetParams(array $params = []) * * @return array */ - public function sanitizeFileParams(array $params) + public function sanitizeFileParams(array $params): array { foreach ($params as $key => $value) { - if ($value instanceof FacebookFile) { + if ($value instanceof File) { $this->addFile($key, $value); unset($params[$key]); } @@ -379,10 +390,10 @@ public function sanitizeFileParams(array $params) /** * Add a file to be uploaded. * - * @param string $key - * @param FacebookFile $file + * @param string $key + * @param File $file */ - public function addFile($key, FacebookFile $file) + public function addFile(string $key, File $file) { $this->files[$key] = $file; } @@ -400,30 +411,30 @@ public function resetFiles() * * @return array */ - public function getFiles() + public function getFiles(): array { return $this->files; } /** - * Let's us know if there is a file upload with this request. + * Lets us know if there is a file upload with this request. * * @return boolean */ - public function containsFileUploads() + public function containsFileUploads(): bool { return !empty($this->files); } /** - * Let's us know if there is a video upload with this request. + * Lets us know if there is a video upload with this request. * * @return boolean */ - public function containsVideoUploads() + public function containsVideoUploads(): bool { foreach ($this->files as $file) { - if ($file instanceof FacebookVideo) { + if ($file instanceof Video) { return true; } } @@ -436,7 +447,7 @@ public function containsVideoUploads() * * @return RequestBodyMultipart */ - public function getMultipartBody() + public function getMultipartBody(): RequestBodyMultipart { $params = $this->getPostParams(); @@ -448,7 +459,7 @@ public function getMultipartBody() * * @return RequestBodyUrlEncoded */ - public function getUrlEncodedBody() + public function getUrlEncodedBody(): RequestBodyUrlEncoded { $params = $this->getPostParams(); @@ -460,12 +471,12 @@ public function getUrlEncodedBody() * * @return array */ - public function getParams() + public function getParams(): array { $params = $this->params; $accessToken = $this->getAccessToken(); - if ($accessToken) { + if ($accessToken !== null) { $params['access_token'] = $accessToken; $params['appsecret_proof'] = $this->getAppSecretProof(); } @@ -478,7 +489,7 @@ public function getParams() * * @return array */ - public function getPostParams() + public function getPostParams(): array { if ($this->getMethod() === 'POST') { return $this->getParams(); @@ -490,9 +501,9 @@ public function getPostParams() /** * The graph version used for this request. * - * @return string + * @return string|null */ - public function getGraphVersion() + public function getGraphVersion(): ?string { return $this->graphVersion; } @@ -502,7 +513,7 @@ public function getGraphVersion() * * @return string */ - public function getUrl() + public function getUrl(): string { $this->validateMethod(); @@ -524,7 +535,8 @@ public function getUrl() * * @return array */ - public static function getDefaultHeaders() + #[ArrayShape(['User-Agent' => "string", 'Accept-Encoding' => "string"])] + public static function getDefaultHeaders(): array { return [ 'User-Agent' => 'fb-php-' . Facebook::VERSION, diff --git a/src/Facebook/FacebookResponse.php b/src/Facebook/Response.php similarity index 64% rename from src/Facebook/FacebookResponse.php rename to src/Facebook/Response.php index 251ca2f79..45198a87f 100644 --- a/src/Facebook/FacebookResponse.php +++ b/src/Facebook/Response.php @@ -1,4 +1,6 @@ request = $request; - $this->body = $body; - $this->httpStatusCode = $httpStatusCode; - $this->headers = $headers; - $this->decodeBody(); } /** * Return the original request that returned this response. * - * @return FacebookRequest + * @return Request */ - public function getRequest() + public function getRequest(): Request { return $this->request; } @@ -95,11 +80,11 @@ public function getRequest() /** * Return the FacebookApp entity used for this response. * - * @return FacebookApp + * @return Application */ - public function getApp() + #[Pure] public function getApplication(): Application { - return $this->request->getApp(); + return $this->request->getApplication(); } /** @@ -107,7 +92,7 @@ public function getApp() * * @return string|null */ - public function getAccessToken() + #[Pure] public function getAccessToken(): ?string { return $this->request->getAccessToken(); } @@ -115,9 +100,9 @@ public function getAccessToken() /** * Return the HTTP status code for this response. * - * @return int + * @return ?int */ - public function getHttpStatusCode() + public function getHttpStatusCode(): ?int { return $this->httpStatusCode; } @@ -127,7 +112,7 @@ public function getHttpStatusCode() * * @return array */ - public function getHeaders() + public function getHeaders(): array { return $this->headers; } @@ -135,9 +120,9 @@ public function getHeaders() /** * Return the raw body response. * - * @return string + * @return string|null */ - public function getBody() + public function getBody(): ?string { return $this->body; } @@ -147,7 +132,7 @@ public function getBody() * * @return array */ - public function getDecodedBody() + public function getDecodedBody(): array { return $this->decodedBody; } @@ -157,7 +142,7 @@ public function getDecodedBody() * * @return string|null */ - public function getAppSecretProof() + public function getAppSecretProof(): ?string { return $this->request->getAppSecretProof(); } @@ -167,9 +152,9 @@ public function getAppSecretProof() * * @return string|null */ - public function getETag() + public function getETag(): ?string { - return isset($this->headers['ETag']) ? $this->headers['ETag'] : null; + return $this->headers['ETag'] ?? null; } /** @@ -177,9 +162,9 @@ public function getETag() * * @return string|null */ - public function getGraphVersion() + public function getGraphVersion(): ?string { - return isset($this->headers['Facebook-API-Version']) ? $this->headers['Facebook-API-Version'] : null; + return $this->headers['Facebook-API-Version'] ?? null; } /** @@ -187,7 +172,7 @@ public function getGraphVersion() * * @return boolean */ - public function isError() + public function isError(): bool { return isset($this->decodedBody['error']); } @@ -213,9 +198,9 @@ public function makeException() /** * Returns the exception that was thrown for this request. * - * @return FacebookResponseException|null + * @return \Facebook\Exceptions\FacebookSDKException|\Facebook\Exceptions\FacebookResponseException|null */ - public function getThrownException() + public function getThrownException(): FacebookSDKException|FacebookResponseException|null { return $this->thrownException; } @@ -231,18 +216,17 @@ public function getThrownException() * a short-lived access token for a long-lived access token * - And sometimes nothing :/ but that'd be a bug. */ - public function decodeBody() + public function decodeBody(): void { - $this->decodedBody = json_decode($this->body, true); + if ($this->body === null) { + $this->decodedBody = []; + } else { + $this->decodedBody = json_decode($this->body, true); + } if ($this->decodedBody === null) { $this->decodedBody = []; parse_str($this->body, $this->decodedBody); - } elseif (is_bool($this->decodedBody)) { - // Backwards compatibility for Graph < 2.1. - // Mimics 2.1 responses. - // @TODO Remove this after Graph 2.0 is no longer supported - $this->decodedBody = ['success' => $this->decodedBody]; } elseif (is_numeric($this->decodedBody)) { $this->decodedBody = ['id' => $this->decodedBody]; } @@ -256,23 +240,6 @@ public function decodeBody() } } - /** - * Instantiate a new GraphObject from response. - * - * @param string|null $subclassName The GraphNode subclass to cast to. - * - * @return \Facebook\GraphNodes\GraphObject - * - * @throws FacebookSDKException - * - * @deprecated 5.0.0 getGraphObject() has been renamed to getGraphNode() - * @todo v6: Remove this method - */ - public function getGraphObject($subclassName = null) - { - return $this->getGraphNode($subclassName); - } - /** * Instantiate a new GraphNode from response. * @@ -282,7 +249,7 @@ public function getGraphObject($subclassName = null) * * @throws FacebookSDKException */ - public function getGraphNode($subclassName = null) + public function getGraphNode(string $subclassName = null): GraphNodes\GraphNode { $factory = new GraphNodeFactory($this); @@ -296,7 +263,7 @@ public function getGraphNode($subclassName = null) * * @throws FacebookSDKException */ - public function getGraphAlbum() + public function getGraphAlbum(): GraphNodes\GraphAlbum { $factory = new GraphNodeFactory($this); @@ -310,7 +277,7 @@ public function getGraphAlbum() * * @throws FacebookSDKException */ - public function getGraphPage() + public function getGraphPage(): GraphNodes\GraphPage { $factory = new GraphNodeFactory($this); @@ -324,7 +291,7 @@ public function getGraphPage() * * @throws FacebookSDKException */ - public function getGraphSessionInfo() + public function getGraphSessionInfo(): GraphNodes\GraphSessionInfo { $factory = new GraphNodeFactory($this); @@ -338,7 +305,7 @@ public function getGraphSessionInfo() * * @throws FacebookSDKException */ - public function getGraphUser() + public function getGraphUser(): GraphNodes\GraphUser { $factory = new GraphNodeFactory($this); @@ -352,7 +319,7 @@ public function getGraphUser() * * @throws FacebookSDKException */ - public function getGraphEvent() + public function getGraphEvent(): GraphNodes\GraphEvent { $factory = new GraphNodeFactory($this); @@ -366,31 +333,13 @@ public function getGraphEvent() * * @throws FacebookSDKException */ - public function getGraphGroup() + public function getGraphGroup(): GraphNodes\GraphGroup { $factory = new GraphNodeFactory($this); return $factory->makeGraphGroup(); } - /** - * Instantiate a new GraphList from response. - * - * @param string|null $subclassName The GraphNode subclass to cast list items to. - * @param boolean $auto_prefix Toggle to auto-prefix the subclass name. - * - * @return \Facebook\GraphNodes\GraphList - * - * @throws FacebookSDKException - * - * @deprecated 5.0.0 getGraphList() has been renamed to getGraphEdge() - * @todo v6: Remove this method - */ - public function getGraphList($subclassName = null, $auto_prefix = true) - { - return $this->getGraphEdge($subclassName, $auto_prefix); - } - /** * Instantiate a new GraphEdge from response. * @@ -401,7 +350,7 @@ public function getGraphList($subclassName = null, $auto_prefix = true) * * @throws FacebookSDKException */ - public function getGraphEdge($subclassName = null, $auto_prefix = true) + public function getGraphEdge(string $subclassName = null, bool $auto_prefix = true): GraphNodes\GraphEdge { $factory = new GraphNodeFactory($this); diff --git a/src/Facebook/SignedRequest.php b/src/Facebook/SignedRequest.php index 6a175a0a2..c6b413294 100644 --- a/src/Facebook/SignedRequest.php +++ b/src/Facebook/SignedRequest.php @@ -33,7 +33,7 @@ class SignedRequest { /** - * @var FacebookApp The FacebookApp entity. + * @var Application The FacebookApp entity. */ protected $app; @@ -50,10 +50,10 @@ class SignedRequest /** * Instantiate a new SignedRequest entity. * - * @param FacebookApp $facebookApp The FacebookApp entity. + * @param Application $facebookApp The FacebookApp entity. * @param string|null $rawSignedRequest The raw signed request. */ - public function __construct(FacebookApp $facebookApp, $rawSignedRequest = null) + public function __construct(Application $facebookApp, $rawSignedRequest = null) { $this->app = $facebookApp; diff --git a/src/Facebook/Url/FacebookUrlManipulator.php b/src/Facebook/Url/FacebookUrlManipulator.php index daeab9c52..b3abdf6dc 100644 --- a/src/Facebook/Url/FacebookUrlManipulator.php +++ b/src/Facebook/Url/FacebookUrlManipulator.php @@ -53,7 +53,7 @@ public static function removeParamsFromUrl($url, array $paramsToFilter) } if (count($params) > 0) { - $query = '?' . http_build_query($params, null, '&'); + $query = '?' . http_build_query($params); } } diff --git a/src/Facebook/Url/FacebookUrlDetectionHandler.php b/src/Facebook/Url/UrlDetectionHandler.php similarity index 98% rename from src/Facebook/Url/FacebookUrlDetectionHandler.php rename to src/Facebook/Url/UrlDetectionHandler.php index 1d134ddcb..0a70004b1 100644 --- a/src/Facebook/Url/FacebookUrlDetectionHandler.php +++ b/src/Facebook/Url/UrlDetectionHandler.php @@ -28,7 +28,7 @@ * * @package Facebook */ -class FacebookUrlDetectionHandler implements UrlDetectionInterface +class UrlDetectionHandler implements UrlDetectionInterface { /** * @inheritdoc diff --git a/src/Facebook/autoload.php b/src/Facebook/autoload.php deleted file mode 100644 index e0dd21c10..000000000 --- a/src/Facebook/autoload.php +++ /dev/null @@ -1,81 +0,0 @@ -app = new FacebookApp('id', 'secret'); + $this->app = new Application('id', 'secret'); } - public function testGetId() + public function testGetId(): void { - $this->assertEquals('id', $this->app->getId()); + static::assertEquals('id', $this->app->getId()); } - public function testGetSecret() + public function testGetSecret(): void { - $this->assertEquals('secret', $this->app->getSecret()); + static::assertEquals('secret', $this->app->getSecret()); } - public function testAnAppAccessTokenCanBeGenerated() + public function testAnAppAccessTokenCanBeGenerated(): void { $accessToken = $this->app->getAccessToken(); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('id|secret', (string)$accessToken); + static::assertInstanceOf(AccessToken::class, $accessToken); + static::assertEquals('id|secret', (string)$accessToken); } - public function testSerialization() + public function testSerialization(): void { $newApp = unserialize(serialize($this->app)); - $this->assertInstanceOf('Facebook\FacebookApp', $newApp); - $this->assertEquals('id', $newApp->getId()); - $this->assertEquals('secret', $newApp->getSecret()); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testOverflowIntegersWillThrow() - { - new FacebookApp(PHP_INT_MAX + 1, "foo"); + static::assertInstanceOf(Application::class, $newApp); + static::assertEquals('id', $newApp->getId()); + static::assertEquals('secret', $newApp->getSecret()); } - public function testUnserializedIdsWillBeString() + public function testUnserializedIdsWillBeString(): void { - $newApp = unserialize(serialize(new FacebookApp(1, "foo"))); + $newApp = unserialize(serialize(new Application('1', "foo"))); - $this->assertSame('1', $newApp->getId()); + static::assertSame('1', $newApp->getId()); } } diff --git a/tests/Authentication/AccessTokenMetadataTest.php b/tests/Authentication/AccessTokenMetadataTest.php index 1900492c9..b58318539 100644 --- a/tests/Authentication/AccessTokenMetadataTest.php +++ b/tests/Authentication/AccessTokenMetadataTest.php @@ -21,14 +21,20 @@ * DEALINGS IN THE SOFTWARE. * */ + namespace Facebook\Tests\Authentication; use Facebook\Authentication\AccessTokenMetadata; +use Facebook\Exceptions\FacebookSDKException; +use PHPUnit\Framework\TestCase; -class AccessTokenMetadataTest extends \PHPUnit_Framework_TestCase +/** + * + */ +class AccessTokenMetadataTest extends TestCase { - protected $graphResponseData = [ + protected array $graphResponseData = [ 'data' => [ 'app_id' => '123', 'application' => 'Foo App', @@ -58,34 +64,32 @@ public function testDatesGetCastToDateTime() $expires = $metadata->getExpiresAt(); $issuedAt = $metadata->getIssuedAt(); - $this->assertInstanceOf('DateTime', $expires); - $this->assertInstanceOf('DateTime', $issuedAt); + static::assertInstanceOf('DateTime', $expires); + static::assertInstanceOf('DateTime', $issuedAt); } public function testAllTheGettersReturnTheProperValue() { $metadata = new AccessTokenMetadata($this->graphResponseData); - $this->assertEquals('123', $metadata->getAppId()); - $this->assertEquals('Foo App', $metadata->getApplication()); - $this->assertTrue($metadata->isError(), 'Expected an error'); - $this->assertEquals('190', $metadata->getErrorCode()); - $this->assertEquals('Foo error message.', $metadata->getErrorMessage()); - $this->assertEquals('463', $metadata->getErrorSubcode()); - $this->assertFalse($metadata->getIsValid(), 'Expected the access token to not be valid'); - $this->assertEquals('iphone-sso', $metadata->getSso()); - $this->assertEquals('rerequest', $metadata->getAuthType()); - $this->assertEquals('no-replicatey', $metadata->getAuthNonce()); - $this->assertEquals('1000', $metadata->getProfileId()); - $this->assertEquals(['public_profile', 'basic_info', 'user_friends'], $metadata->getScopes()); - $this->assertEquals('1337', $metadata->getUserId()); + static::assertEquals('123', $metadata->getAppId()); + static::assertEquals('Foo App', $metadata->getApplication()); + static::assertTrue($metadata->isError(), 'Expected an error'); + static::assertEquals('190', $metadata->getErrorCode()); + static::assertEquals('Foo error message.', $metadata->getErrorMessage()); + static::assertEquals('463', $metadata->getErrorSubcode()); + static::assertFalse($metadata->getIsValid(), 'Expected the access token to not be valid'); + static::assertEquals('iphone-sso', $metadata->getSso()); + static::assertEquals('rerequest', $metadata->getAuthType()); + static::assertEquals('no-replicatey', $metadata->getAuthNonce()); + static::assertEquals('1000', $metadata->getProfileId()); + static::assertEquals(['public_profile', 'basic_info', 'user_friends'], $metadata->getScopes()); + static::assertEquals('1337', $metadata->getUserId()); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testInvalidMetadataWillThrow() { + $this->expectException(FacebookSDKException::class); new AccessTokenMetadata(['foo' => 'bar']); } @@ -93,13 +97,13 @@ public function testAnExpectedAppIdWillNotThrow() { $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateAppId('123'); + + static::assertTrue(true); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testAnUnexpectedAppIdWillThrow() { + $this->expectException(FacebookSDKException::class); $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateAppId('foo'); } @@ -108,13 +112,12 @@ public function testAnExpectedUserIdWillNotThrow() { $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateUserId('1337'); + static::assertTrue(true); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testAnUnexpectedUserIdWillThrow() { + $this->expectException(FacebookSDKException::class); $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateUserId('foo'); } @@ -124,13 +127,12 @@ public function testAnActiveAccessTokenWillNotThrow() $this->graphResponseData['data']['expires_at'] = time() + 1000; $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateExpiration(); + static::assertTrue(true); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testAnExpiredAccessTokenWillThrow() { + $this->expectException(FacebookSDKException::class); $this->graphResponseData['data']['expires_at'] = time() - 1000; $metadata = new AccessTokenMetadata($this->graphResponseData); $metadata->validateExpiration(); diff --git a/tests/Authentication/AccessTokenTest.php b/tests/Authentication/AccessTokenTest.php index 39e42d48b..7980dd8f9 100644 --- a/tests/Authentication/AccessTokenTest.php +++ b/tests/Authentication/AccessTokenTest.php @@ -24,16 +24,20 @@ namespace Facebook\Tests\Authentication; use Facebook\Authentication\AccessToken; +use PHPUnit\Framework\TestCase; -class AccessTokenTest extends \PHPUnit_Framework_TestCase +/** + * + */ +class AccessTokenTest extends TestCase { public function testAnAccessTokenCanBeReturnedAsAString() { $accessToken = new AccessToken('foo_token'); - $this->assertEquals('foo_token', $accessToken->getValue()); - $this->assertEquals('foo_token', (string)$accessToken); + static::assertEquals('foo_token', $accessToken->getValue()); + static::assertEquals('foo_token', (string)$accessToken); } public function testAnAppSecretProofWillBeProperlyGenerated() @@ -42,7 +46,7 @@ public function testAnAppSecretProofWillBeProperlyGenerated() $appSecretProof = $accessToken->getAppSecretProof('shhhhh!is.my.secret'); - $this->assertEquals('796ba0d8a6b339e476a7b166a9e8ac0a395f7de736dc37de5f2f4397f5854eb8', $appSecretProof); + static::assertEquals('796ba0d8a6b339e476a7b166a9e8ac0a395f7de736dc37de5f2f4397f5854eb8', $appSecretProof); } public function testAnAppAccessTokenCanBeDetected() @@ -50,12 +54,12 @@ public function testAnAppAccessTokenCanBeDetected() $normalToken = new AccessToken('foo_token'); $isNormalToken = $normalToken->isAppAccessToken(); - $this->assertFalse($isNormalToken, 'Normal access token not expected to look like an app access token.'); + static::assertFalse($isNormalToken, 'Normal access token not expected to look like an app access token.'); $appToken = new AccessToken('123|secret'); $isAppToken = $appToken->isAppAccessToken(); - $this->assertTrue($isAppToken, 'App access token expected to look like an app access token.'); + static::assertTrue($isAppToken, 'App access token expected to look like an app access token.'); } public function testShortLivedAccessTokensCanBeDetected() @@ -65,7 +69,7 @@ public function testShortLivedAccessTokensCanBeDetected() $isLongLived = $accessToken->isLongLived(); - $this->assertFalse($isLongLived, 'Expected access token to be short lived.'); + static::assertFalse($isLongLived, 'Expected access token to be short lived.'); } public function testLongLivedAccessTokensCanBeDetected() @@ -74,7 +78,7 @@ public function testLongLivedAccessTokensCanBeDetected() $isLongLived = $accessToken->isLongLived(); - $this->assertTrue($isLongLived, 'Expected access token to be long lived.'); + static::assertTrue($isLongLived, 'Expected access token to be long lived.'); } public function testAnAppAccessTokenDoesNotExpire() @@ -82,7 +86,7 @@ public function testAnAppAccessTokenDoesNotExpire() $appToken = new AccessToken('123|secret'); $hasExpired = $appToken->isExpired(); - $this->assertFalse($hasExpired, 'App access token not expected to expire.'); + static::assertFalse($hasExpired, 'App access token not expected to expire.'); } public function testAnAccessTokenCanExpire() @@ -91,20 +95,20 @@ public function testAnAccessTokenCanExpire() $appToken = new AccessToken('foo_token', $expireTime); $hasExpired = $appToken->isExpired(); - $this->assertTrue($hasExpired, 'Expected 100 second old access token to be expired.'); + static::assertTrue($hasExpired, 'Expected 100 second old access token to be expired.'); } public function testAccessTokenCanBeSerialized() { - $accessToken = new AccessToken('foo', time(), 'bar'); + $accessToken = new AccessToken('foo', time()); $newAccessToken = unserialize(serialize($accessToken)); - $this->assertEquals((string)$accessToken, (string)$newAccessToken); - $this->assertEquals($accessToken->getExpiresAt(), $newAccessToken->getExpiresAt()); + static::assertEquals((string)$accessToken, (string)$newAccessToken); + static::assertEquals($accessToken->getExpiresAt(), $newAccessToken->getExpiresAt()); } - private function aWeekFromNow() + private function aWeekFromNow(): float|int { return time() + (60 * 60 * 24 * 7);//a week from now } diff --git a/tests/Authentication/FooFacebookClientForOAuth2Test.php b/tests/Authentication/FooClientForOAuth2Test.php similarity index 85% rename from tests/Authentication/FooFacebookClientForOAuth2Test.php rename to tests/Authentication/FooClientForOAuth2Test.php index 8c59ae130..0b8e03748 100644 --- a/tests/Authentication/FooFacebookClientForOAuth2Test.php +++ b/tests/Authentication/FooClientForOAuth2Test.php @@ -23,13 +23,16 @@ */ namespace Facebook\Tests\Authentication; -use Facebook\FacebookClient; -use Facebook\FacebookRequest; -use Facebook\FacebookResponse; +use Facebook\Client; +use Facebook\Request; +use Facebook\Response; -class FooFacebookClientForOAuth2Test extends FacebookClient +/** + * + */ +class FooClientForOAuth2Test extends Client { - protected $response = ''; + protected string $response = ''; public function setMetadataResponse() { @@ -46,9 +49,9 @@ public function setCodeResponse() $this->response = '{"code":"my_neat_code"}'; } - public function sendRequest(FacebookRequest $request) + public function sendRequest(Request $request): Response { - return new FacebookResponse( + return new Response( $request, $this->response, 200, diff --git a/tests/Authentication/OAuth2ClientTest.php b/tests/Authentication/OAuth2ClientTest.php index 5b144d7b7..2ea390ac5 100644 --- a/tests/Authentication/OAuth2ClientTest.php +++ b/tests/Authentication/OAuth2ClientTest.php @@ -24,10 +24,14 @@ namespace Facebook\Tests\Authentication; use Facebook\Facebook; -use Facebook\FacebookApp; +use Facebook\Application; use Facebook\Authentication\OAuth2Client; +use PHPUnit\Framework\TestCase; -class OAuth2ClientTest extends \PHPUnit_Framework_TestCase +/** + * + */ +class OAuth2ClientTest extends TestCase { /** @@ -36,19 +40,19 @@ class OAuth2ClientTest extends \PHPUnit_Framework_TestCase const TESTING_GRAPH_VERSION = 'v1337'; /** - * @var FooFacebookClientForOAuth2Test + * @var FooClientForOAuth2Test */ - protected $client; + protected FooClientForOAuth2Test $client; /** * @var OAuth2Client */ - protected $oauth; + protected OAuth2Client $oauth; - protected function setUp() + protected function setUp(): void { - $app = new FacebookApp('123', 'foo_secret'); - $this->client = new FooFacebookClientForOAuth2Test(); + $app = new Application('123', 'foo_secret'); + $this->client = new FooClientForOAuth2Test(); $this->oauth = new OAuth2Client($app, $this->client, static::TESTING_GRAPH_VERSION); } @@ -58,8 +62,8 @@ public function testCanGetMetadataFromAnAccessToken() $metadata = $this->oauth->debugToken('baz_token'); - $this->assertInstanceOf('Facebook\Authentication\AccessTokenMetadata', $metadata); - $this->assertEquals('444', $metadata->getUserId()); + static::assertInstanceOf('Facebook\Authentication\AccessTokenMetadata', $metadata); + static::assertEquals('444', $metadata->getUserId()); $expectedParams = [ 'input_token' => 'baz_token', @@ -68,10 +72,10 @@ public function testCanGetMetadataFromAnAccessToken() ]; $request = $this->oauth->getLastRequest(); - $this->assertEquals('GET', $request->getMethod()); - $this->assertEquals('/debug_token', $request->getEndpoint()); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); + static::assertEquals('GET', $request->getMethod()); + static::assertEquals('/debug_token', $request->getEndpoint()); + static::assertEquals($expectedParams, $request->getParams()); + static::assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); } public function testCanBuildAuthorizationUrl() @@ -79,10 +83,10 @@ public function testCanBuildAuthorizationUrl() $scope = ['email', 'base_foo']; $authUrl = $this->oauth->getAuthorizationUrl('https://foo.bar', 'foo_state', $scope, ['foo' => 'bar'], '*'); - $this->assertContains('*', $authUrl); + static::assertStringContainsString('*', $authUrl); $expectedUrl = 'https://www.facebook.com/' . static::TESTING_GRAPH_VERSION . '/dialog/oauth?'; - $this->assertTrue(strpos($authUrl, $expectedUrl) === 0, 'Unexpected base authorization URL returned from getAuthorizationUrl().'); + static::assertTrue(str_starts_with($authUrl, $expectedUrl), 'Unexpected base authorization URL returned from getAuthorizationUrl().'); $params = [ 'client_id' => '123', @@ -93,7 +97,7 @@ public function testCanBuildAuthorizationUrl() 'foo' => 'bar', ]; foreach ($params as $key => $value) { - $this->assertContains($key . '=' . urlencode($value), $authUrl); + static::assertStringContainsString($key . '=' . urlencode($value), $authUrl); } } @@ -103,8 +107,8 @@ public function testCanGetAccessTokenFromCode() $accessToken = $this->oauth->getAccessTokenFromCode('bar_code', 'foo_uri'); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('my_access_token', $accessToken->getValue()); + static::assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); + static::assertEquals('my_access_token', $accessToken->getValue()); $expectedParams = [ 'code' => 'bar_code', @@ -116,10 +120,10 @@ public function testCanGetAccessTokenFromCode() ]; $request = $this->oauth->getLastRequest(); - $this->assertEquals('GET', $request->getMethod()); - $this->assertEquals('/oauth/access_token', $request->getEndpoint()); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); + static::assertEquals('GET', $request->getMethod()); + static::assertEquals('/oauth/access_token', $request->getEndpoint()); + static::assertEquals($expectedParams, $request->getParams()); + static::assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); } public function testCanGetLongLivedAccessToken() @@ -128,7 +132,7 @@ public function testCanGetLongLivedAccessToken() $accessToken = $this->oauth->getLongLivedAccessToken('short_token'); - $this->assertEquals('my_access_token', $accessToken->getValue()); + static::assertEquals('my_access_token', $accessToken->getValue()); $expectedParams = [ 'grant_type' => 'fb_exchange_token', @@ -140,7 +144,7 @@ public function testCanGetLongLivedAccessToken() ]; $request = $this->oauth->getLastRequest(); - $this->assertEquals($expectedParams, $request->getParams()); + static::assertEquals($expectedParams, $request->getParams()); } public function testCanGetCodeFromLongLivedAccessToken() @@ -149,7 +153,7 @@ public function testCanGetCodeFromLongLivedAccessToken() $code = $this->oauth->getCodeFromLongLivedAccessToken('long_token', 'foo_uri'); - $this->assertEquals('my_neat_code', $code); + static::assertEquals('my_neat_code', $code); $expectedParams = [ 'access_token' => 'long_token', @@ -160,7 +164,7 @@ public function testCanGetCodeFromLongLivedAccessToken() ]; $request = $this->oauth->getLastRequest(); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals('/oauth/client_code', $request->getEndpoint()); + static::assertEquals($expectedParams, $request->getParams()); + static::assertEquals('/oauth/client_code', $request->getEndpoint()); } } diff --git a/tests/FacebookBatchRequestTest.php b/tests/BatchRequestTest.php old mode 100755 new mode 100644 similarity index 57% rename from tests/FacebookBatchRequestTest.php rename to tests/BatchRequestTest.php index a77e75450..e431897ab --- a/tests/FacebookBatchRequestTest.php +++ b/tests/BatchRequestTest.php @@ -1,4 +1,6 @@ app = new FacebookApp('123', 'foo_secret'); + $this->app = new Application('123', 'foo_secret'); } - public function testABatchRequestWillInstantiateWithTheProperProperties() + public function testABatchRequestWillInstantiateWithTheProperProperties(): void { - $batchRequest = new FacebookBatchRequest($this->app, [], 'foo_token', 'v0.1337'); + $batchRequest = new BatchRequest($this->app, [], 'foo_token', 'v0.1337'); - $this->assertSame($this->app, $batchRequest->getApp()); - $this->assertEquals('foo_token', $batchRequest->getAccessToken()); - $this->assertEquals('POST', $batchRequest->getMethod()); - $this->assertEquals('', $batchRequest->getEndpoint()); - $this->assertEquals('v0.1337', $batchRequest->getGraphVersion()); + static::assertSame($this->app, $batchRequest->getApplication()); + static::assertEquals('foo_token', $batchRequest->getAccessToken()); + static::assertEquals('POST', $batchRequest->getMethod()); + static::assertEquals('', $batchRequest->getEndpoint()); + static::assertEquals('v0.1337', $batchRequest->getGraphVersion()); } - public function testEmptyRequestWillFallbackToBatchDefaults() + public function testEmptyRequestWillFallbackToBatchDefaults(): void { - $request = new FacebookRequest(); + $request = new Request(); $this->createBatchRequest()->addFallbackDefaults($request); $this->assertRequestContainsAppAndToken($request, $this->app, 'foo_token'); } - public function testRequestWithTokenOnlyWillFallbackToBatchDefaults() + public function testRequestWithTokenOnlyWillFallbackToBatchDefaults(): void { - $request = new FacebookRequest(null, 'bar_token'); + $request = new Request(null, 'bar_token'); $this->createBatchRequest()->addFallbackDefaults($request); $this->assertRequestContainsAppAndToken($request, $this->app, 'bar_token'); } - public function testRequestWithAppOnlyWillFallbackToBatchDefaults() + public function testRequestWithAppOnlyWillFallbackToBatchDefaults(): void { - $customApp = new FacebookApp('1337', 'bar_secret'); - $request = new FacebookRequest($customApp); + $customApp = new Application('1337', 'bar_secret'); + $request = new Request($customApp); $this->createBatchRequest()->addFallbackDefaults($request); $this->assertRequestContainsAppAndToken($request, $customApp, 'foo_token'); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testWillThrowWhenNoThereIsNoAppFallback() + public function testWillThrowWhenNoThereIsNoAppFallback(): void { - $batchRequest = new FacebookBatchRequest(); + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $batchRequest = new BatchRequest(); - $batchRequest->addFallbackDefaults(new FacebookRequest(null, 'foo_token')); + $batchRequest->addFallbackDefaults(new Request(null, 'foo_token')); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testWillThrowWhenNoThereIsNoAccessTokenFallback() + public function testWillThrowWhenNoThereIsNoAccessTokenFallback(): void { - $request = new FacebookBatchRequest(); + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $request = new BatchRequest(); - $request->addFallbackDefaults(new FacebookRequest($this->app)); + $request->addFallbackDefaults(new Request($this->app)); } - /** - * @expectedException \InvalidArgumentException - */ - public function testAnInvalidTypeGivenToAddWillThrow() - { - $request = new FacebookBatchRequest(); - - $request->add('foo'); - } - - public function testAddingRequestsWillBeFormattedInAnArrayProperly() + public function testAddingRequestsWillBeFormattedInAnArrayProperly(): void { $requests = [ - null => new FacebookRequest(null, null, 'GET', '/foo'), - 'my-second-request' => new FacebookRequest(null, null, 'POST', '/bar', ['foo' => 'bar']), - 'my-third-request' => new FacebookRequest(null, null, 'DELETE', '/baz') + null => new Request(null, null, 'GET', '/foo'), + 'my-second-request' => new Request(null, null, 'POST', '/bar', ['foo' => 'bar']), + 'my-third-request' => new Request(null, null, 'DELETE', '/baz') ]; $batchRequest = $this->createBatchRequest(); @@ -128,12 +121,12 @@ public function testAddingRequestsWillBeFormattedInAnArrayProperly() $this->assertRequestsMatch($requests, $formattedRequests); } - public function testANumericArrayOfRequestsCanBeAdded() + public function testANumericArrayOfRequestsCanBeAdded(): void { $requests = [ - new FacebookRequest(null, null, 'GET', '/foo'), - new FacebookRequest(null, null, 'POST', '/bar', ['foo' => 'bar']), - new FacebookRequest(null, null, 'DELETE', '/baz'), + new Request(null, null, 'GET', '/foo'), + new Request(null, null, 'POST', '/bar', ['foo' => 'bar']), + new Request(null, null, 'DELETE', '/baz'), ]; $formattedRequests = $this->createBatchRequestWithRequests($requests)->getRequests(); @@ -141,12 +134,12 @@ public function testANumericArrayOfRequestsCanBeAdded() $this->assertRequestsMatch($requests, $formattedRequests); } - public function testAnAssociativeArrayOfRequestsCanBeAdded() + public function testAnAssociativeArrayOfRequestsCanBeAdded(): void { $requests = [ - 'req-one' => new FacebookRequest(null, null, 'GET', '/foo'), - 'req-two' => new FacebookRequest(null, null, 'POST', '/bar', ['foo' => 'bar']), - 'req-three' => new FacebookRequest(null, null, 'DELETE', '/baz'), + 'req-one' => new Request(null, null, 'GET', '/foo'), + 'req-two' => new Request(null, null, 'POST', '/bar', ['foo' => 'bar']), + 'req-three' => new Request(null, null, 'DELETE', '/baz'), ]; $formattedRequests = $this->createBatchRequestWithRequests($requests)->getRequests(); @@ -154,35 +147,31 @@ public function testAnAssociativeArrayOfRequestsCanBeAdded() $this->assertRequestsMatch($requests, $formattedRequests); } - public function testRequestsCanBeInjectedIntoConstructor() + public function testRequestsCanBeInjectedIntoConstructor(): void { $requests = [ - new FacebookRequest(null, null, 'GET', '/foo'), - new FacebookRequest(null, null, 'POST', '/bar', ['foo' => 'bar']), - new FacebookRequest(null, null, 'DELETE', '/baz'), + new Request(null, null, 'GET', '/foo'), + new Request(null, null, 'POST', '/bar', ['foo' => 'bar']), + new Request(null, null, 'DELETE', '/baz'), ]; - $batchRequest = new FacebookBatchRequest($this->app, $requests, 'foo_token'); + $batchRequest = new BatchRequest($this->app, $requests, 'foo_token'); $formattedRequests = $batchRequest->getRequests(); $this->assertRequestsMatch($requests, $formattedRequests); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAZeroRequestCountWithThrow() + public function testAZeroRequestCountWithThrow(): void { - $batchRequest = new FacebookBatchRequest($this->app, [], 'foo_token'); + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $batchRequest = new BatchRequest($this->app, [], 'foo_token'); $batchRequest->validateBatchRequestCount(); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testMoreThanFiftyRequestsWillThrow() + public function testMoreThanFiftyRequestsWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); $batchRequest = $this->createBatchRequest(); $this->createAndAppendRequestsTo($batchRequest, 51); @@ -190,19 +179,21 @@ public function testMoreThanFiftyRequestsWillThrow() $batchRequest->validateBatchRequestCount(); } - public function testLessOrEqualThanFiftyRequestsWillNotThrow() + public function testLessOrEqualThanFiftyRequestsWillNotThrow(): void { $batchRequest = $this->createBatchRequest(); $this->createAndAppendRequestsTo($batchRequest, 50); $batchRequest->validateBatchRequestCount(); + + static::assertTrue(true); } /** * @dataProvider requestsAndExpectedResponsesProvider */ - public function testBatchRequestEntitiesProperlyGetConvertedToAnArray($request, $expectedArray) + public function testBatchRequestEntitiesProperlyGetConvertedToAnArray($request, $expectedArray): void { $batchRequest = $this->createBatchRequest(); $batchRequest->add($request, 'foo_name'); @@ -210,51 +201,50 @@ public function testBatchRequestEntitiesProperlyGetConvertedToAnArray($request, $requests = $batchRequest->getRequests(); $batchRequestArray = $batchRequest->requestEntityToBatchArray($requests[0]['request'], $requests[0]['name']); - $this->assertEquals($expectedArray, $batchRequestArray); + static::assertEquals($expectedArray, $batchRequestArray); } - public function requestsAndExpectedResponsesProvider() + public function requestsAndExpectedResponsesProvider(): array { $headers = $this->defaultHeaders(); - $apiVersion = Facebook::DEFAULT_GRAPH_VERSION; return [ [ - new FacebookRequest(null, null, 'GET', '/foo', ['foo' => 'bar']), + new Request(null, null, 'GET', '/foo', ['foo' => 'bar']), [ 'headers' => $headers, 'method' => 'GET', - 'relative_url' => '/' . $apiVersion . '/foo?foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', + 'relative_url' => '/foo?foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', 'name' => 'foo_name', ], ], [ - new FacebookRequest(null, null, 'POST', '/bar', ['bar' => 'baz']), + new Request(null, null, 'POST', '/bar', ['bar' => 'baz']), [ 'headers' => $headers, 'method' => 'POST', - 'relative_url' => '/' . $apiVersion . '/bar', + 'relative_url' => '/bar', 'body' => 'bar=baz&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', 'name' => 'foo_name', ], ], [ - new FacebookRequest(null, null, 'DELETE', '/bar'), + new Request(null, null, 'DELETE', '/bar'), [ 'headers' => $headers, 'method' => 'DELETE', - 'relative_url' => '/' . $apiVersion . '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', + 'relative_url' => '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', 'name' => 'foo_name', ], ], ]; } - public function testBatchRequestsWithFilesGetConvertedToAnArray() + public function testBatchRequestsWithFilesGetConvertedToAnArray(): void { - $request = new FacebookRequest(null, null, 'POST', '/bar', [ + $request = new Request(null, null, 'POST', '/bar', [ 'message' => 'foobar', - 'source' => new FacebookFile(__DIR__ . '/foo.txt'), + 'source' => new File(__DIR__ . '/foo.txt'), ]); $batchRequest = $this->createBatchRequest(); @@ -270,19 +260,19 @@ public function testBatchRequestsWithFilesGetConvertedToAnArray() $attachedFiles ); - $this->assertEquals([ + static::assertEquals([ 'headers' => $this->defaultHeaders(), 'method' => 'POST', - 'relative_url' => '/' . Facebook::DEFAULT_GRAPH_VERSION . '/bar', + 'relative_url' => '/bar', 'body' => 'message=foobar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', 'name' => 'foo_name', 'attached_files' => $attachedFiles, ], $batchRequestArray); } - public function testBatchRequestsWithOptionsGetConvertedToAnArray() + public function testBatchRequestsWithOptionsGetConvertedToAnArray(): void { - $request = new FacebookRequest(null, null, 'GET', '/bar'); + $request = new Request(null, null, 'GET', '/bar'); $batchRequest = $this->createBatchRequest(); $batchRequest->add($request, [ 'name' => 'foo_name', @@ -296,10 +286,10 @@ public function testBatchRequestsWithOptionsGetConvertedToAnArray() $batchRequestArray = $batchRequest->requestEntityToBatchArray($requests[0]['request'], $options); - $this->assertEquals([ + static::assertEquals([ 'headers' => $this->defaultHeaders(), 'method' => 'GET', - 'relative_url' => '/' . Facebook::DEFAULT_GRAPH_VERSION . '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', + 'relative_url' => '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', 'name' => 'foo_name', 'omit_response_on_success' => false, ], $batchRequestArray); @@ -308,31 +298,30 @@ public function testBatchRequestsWithOptionsGetConvertedToAnArray() public function testPreppingABatchRequestProperlySetsThePostParams() { $batchRequest = $this->createBatchRequest(); - $batchRequest->add(new FacebookRequest(null, 'bar_token', 'GET', '/foo'), 'foo_name'); - $batchRequest->add(new FacebookRequest(null, null, 'POST', '/bar', ['foo' => 'bar'])); + $batchRequest->add(new Request(null, 'bar_token', 'GET', '/foo'), 'foo_name'); + $batchRequest->add(new Request(null, null, 'POST', '/bar', ['foo' => 'bar'])); $batchRequest->prepareRequestsForBatch(); $params = $batchRequest->getParams(); $expectedHeaders = json_encode($this->defaultHeaders()); - $version = Facebook::DEFAULT_GRAPH_VERSION; $expectedBatchParams = [ - 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/' . $version . '\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},' - . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/' . $version . '\\/bar","body":"foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9"}]', + 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},' + . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/bar","body":"foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9"}]', 'include_headers' => true, 'access_token' => 'foo_token', 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', ]; - $this->assertEquals($expectedBatchParams, $params); + static::assertEquals($expectedBatchParams, $params); } - public function testPreppingABatchRequestProperlyMovesTheFiles() + public function testPreppingABatchRequestProperlyMovesTheFiles(): void { $batchRequest = $this->createBatchRequest(); - $batchRequest->add(new FacebookRequest(null, 'bar_token', 'GET', '/foo'), 'foo_name'); - $batchRequest->add(new FacebookRequest(null, null, 'POST', '/me/photos', [ + $batchRequest->add(new Request(null, 'bar_token', 'GET', '/foo'), 'foo_name'); + $batchRequest->add(new Request(null, null, 'POST', '/me/photos', [ 'message' => 'foobar', - 'source' => new FacebookFile(__DIR__ . '/foo.txt'), + 'source' => new File(__DIR__ . '/foo.txt'), ])); $batchRequest->prepareRequestsForBatch(); @@ -342,21 +331,20 @@ public function testPreppingABatchRequestProperlyMovesTheFiles() $attachedFiles = implode(',', array_keys($files)); $expectedHeaders = json_encode($this->defaultHeaders()); - $version = Facebook::DEFAULT_GRAPH_VERSION; $expectedBatchParams = [ - 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/' . $version . '\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},' - . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/' . $version . '\\/me\\/photos","body":"message=foobar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9","attached_files":"' . $attachedFiles . '"}]', + 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},' + . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/me\\/photos","body":"message=foobar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9","attached_files":"' . $attachedFiles . '"}]', 'include_headers' => true, 'access_token' => 'foo_token', 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', ]; - $this->assertEquals($expectedBatchParams, $params); + static::assertEquals($expectedBatchParams, $params); } public function testPreppingABatchRequestWithOptionsProperlySetsThePostParams() { $batchRequest = $this->createBatchRequest(); - $batchRequest->add(new FacebookRequest(null, null, 'GET', '/foo'), [ + $batchRequest->add(new Request(null, null, 'GET', '/foo'), [ 'name' => 'foo_name', 'omit_response_on_success' => false, ]); @@ -365,50 +353,62 @@ public function testPreppingABatchRequestWithOptionsProperlySetsThePostParams() $params = $batchRequest->getParams(); $expectedHeaders = json_encode($this->defaultHeaders()); - $version = Facebook::DEFAULT_GRAPH_VERSION; $expectedBatchParams = [ - 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/' . $version . '\\/foo?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9",' + 'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/foo?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9",' . '"name":"foo_name","omit_response_on_success":false}]', 'include_headers' => true, 'access_token' => 'foo_token', 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', ]; - $this->assertEquals($expectedBatchParams, $params); + static::assertEquals($expectedBatchParams, $params); } - private function assertRequestContainsAppAndToken(FacebookRequest $request, FacebookApp $expectedApp, $expectedToken) + /** + * @param \Facebook\Request $request + * @param \Facebook\Application $expectedApp + * @param $expectedToken + * + * @return void + */ + private function assertRequestContainsAppAndToken(Request $request, Application $expectedApp, $expectedToken): void { - $app = $request->getApp(); + $app = $request->getApplication(); $token = $request->getAccessToken(); - $this->assertSame($expectedApp, $app); - $this->assertEquals($expectedToken, $token); + static::assertSame($expectedApp, $app); + static::assertEquals($expectedToken, $token); } - private function defaultHeaders() + #[Pure] private function defaultHeaders(): array { $headers = []; - foreach (FacebookRequest::getDefaultHeaders() as $name => $value) { + foreach (Request::getDefaultHeaders() as $name => $value) { $headers[] = $name . ': ' . $value; } return $headers; } - private function createAndAppendRequestsTo(FacebookBatchRequest $batchRequest, $number) + /** + * @param \Facebook\BatchRequest $batchRequest + * @param $number + * + * @return void + */ + private function createAndAppendRequestsTo(BatchRequest $batchRequest, $number): void { for ($i = 0; $i < $number; $i++) { - $batchRequest->add(new FacebookRequest()); + $batchRequest->add(new Request()); } } - private function createBatchRequest() + private function createBatchRequest(): BatchRequest { - return new FacebookBatchRequest($this->app, [], 'foo_token'); + return new BatchRequest($this->app, [], 'foo_token'); } - private function createBatchRequestWithRequests(array $requests) + private function createBatchRequestWithRequests(array $requests): BatchRequest { $batchRequest = $this->createBatchRequest(); $batchRequest->add($requests); @@ -416,6 +416,12 @@ private function createBatchRequestWithRequests(array $requests) return $batchRequest; } + /** + * @param $requests + * @param $formattedRequests + * + * @return void + */ private function assertRequestsMatch($requests, $formattedRequests) { $expectedRequests = []; @@ -427,6 +433,6 @@ private function assertRequestsMatch($requests, $formattedRequests) 'options' => [], ]; } - $this->assertEquals($expectedRequests, $formattedRequests); + static::assertEquals($expectedRequests, $formattedRequests); } } diff --git a/tests/FacebookBatchResponseTest.php b/tests/BatchResponseTest.php old mode 100755 new mode 100644 similarity index 57% rename from tests/FacebookBatchResponseTest.php rename to tests/BatchResponseTest.php index 8f4e5a8ad..ed89669aa --- a/tests/FacebookBatchResponseTest.php +++ b/tests/BatchResponseTest.php @@ -1,4 +1,6 @@ app = new FacebookApp('123', 'foo_secret'); - $this->request = new FacebookRequest( + $this->app = new Application('123', 'foo_secret'); + $this->request = new Request( $this->app, 'foo_token', 'POST', @@ -55,7 +63,7 @@ protected function setUp() ); } - public function testASuccessfulJsonBatchResponseWillBeDecoded() + public function testASuccessfulJsonBatchResponseWillBeDecoded(): void { $graphResponseJson = '['; // Single Graph object. @@ -67,98 +75,98 @@ public function testASuccessfulJsonBatchResponseWillBeDecoded() // After DELETE operation. $graphResponseJson .= ',{"code":200,"headers":[{"name":"Connection","value":"close"},{"name":"Expires","value":"Sat, 01 Jan 2000 00:00:00 GMT"},{"name":"Cache-Control","value":"private, no-cache, no-store, must-revalidate"},{"name":"Access-Control-Allow-Origin","value":"*"},{"name":"Pragma","value":"no-cache"},{"name":"Content-Type","value":"text\/javascript; charset=UTF-8"},{"name":"Facebook-API-Version","value":"v2.0"}],"body":"true"}'; $graphResponseJson .= ']'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); - $batchRequest = new FacebookBatchRequest($this->app, [ - new FacebookRequest($this->app, 'token'), - new FacebookRequest($this->app, 'token'), - new FacebookRequest($this->app, 'token'), - new FacebookRequest($this->app, 'token'), + $response = new Response($this->request, $graphResponseJson, 200); + $batchRequest = new BatchRequest($this->app, [ + new Request($this->app, 'token'), + new Request($this->app, 'token'), + new Request($this->app, 'token'), + new Request($this->app, 'token'), ]); - $batchResponse = new FacebookBatchResponse($batchRequest, $response); + $batchResponse = new BatchResponse($batchRequest, $response); $decodedResponses = $batchResponse->getResponses(); // Single Graph object. - $this->assertFalse($decodedResponses[0]->isError(), 'Did not expect Response to return an error for single Graph object.'); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $decodedResponses[0]->getGraphNode()); + static::assertFalse($decodedResponses[0]->isError(), 'Did not expect Response to return an error for single Graph object.'); + static::assertInstanceOf(GraphNode::class, $decodedResponses[0]->getGraphNode()); // Paginated list of Graph objects. - $this->assertFalse($decodedResponses[1]->isError(), 'Did not expect Response to return an error for paginated list of Graph objects.'); + static::assertFalse($decodedResponses[1]->isError(), 'Did not expect Response to return an error for paginated list of Graph objects.'); $graphEdge = $decodedResponses[1]->getGraphEdge(); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphEdge[0]); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphEdge[1]); + static::assertInstanceOf(GraphNode::class, $graphEdge[0]); + static::assertInstanceOf(GraphNode::class, $graphEdge[1]); } - public function testABatchResponseCanBeIteratedOver() + public function testABatchResponseCanBeIteratedOver(): void { $graphResponseJson = '['; $graphResponseJson .= '{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ',{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ',{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ']'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); - $batchRequest = new FacebookBatchRequest($this->app, [ - 'req_one' => new FacebookRequest($this->app, 'token'), - 'req_two' => new FacebookRequest($this->app, 'token'), - 'req_three' => new FacebookRequest($this->app, 'token'), + $response = new Response($this->request, $graphResponseJson, 200); + $batchRequest = new BatchRequest($this->app, [ + 'req_one' => new Request($this->app, 'token'), + 'req_two' => new Request($this->app, 'token'), + 'req_three' => new Request($this->app, 'token'), ]); - $batchResponse = new FacebookBatchResponse($batchRequest, $response); + $batchResponse = new BatchResponse($batchRequest, $response); - $this->assertInstanceOf('IteratorAggregate', $batchResponse); + static::assertInstanceOf(\IteratorAggregate::class, $batchResponse); foreach ($batchResponse as $key => $responseEntity) { - $this->assertTrue(in_array($key, ['req_one', 'req_two', 'req_three'])); - $this->assertInstanceOf('Facebook\FacebookResponse', $responseEntity); + static::assertTrue(in_array($key, ['req_one', 'req_two', 'req_three'])); + static::assertInstanceOf(Response::class, $responseEntity); } } - public function testTheOriginalRequestCanBeObtainedForEachRequest() + public function testTheOriginalRequestCanBeObtainedForEachRequest(): void { $graphResponseJson = '['; $graphResponseJson .= '{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ',{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ',{"code":200,"headers":[],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ']'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); + $response = new Response($this->request, $graphResponseJson, 200); $requests = [ - new FacebookRequest($this->app, 'foo_token_one', 'GET', '/me'), - new FacebookRequest($this->app, 'foo_token_two', 'POST', '/you'), - new FacebookRequest($this->app, 'foo_token_three', 'DELETE', '/123456'), + new Request($this->app, 'foo_token_one', 'GET', '/me'), + new Request($this->app, 'foo_token_two', 'POST', '/you'), + new Request($this->app, 'foo_token_three', 'DELETE', '/123456'), ]; - $batchRequest = new FacebookBatchRequest($this->app, $requests); - $batchResponse = new FacebookBatchResponse($batchRequest, $response); + $batchRequest = new BatchRequest($this->app, $requests); + $batchResponse = new BatchResponse($batchRequest, $response); - $this->assertInstanceOf('Facebook\FacebookResponse', $batchResponse[0]); - $this->assertInstanceOf('Facebook\FacebookRequest', $batchResponse[0]->getRequest()); - $this->assertEquals('foo_token_one', $batchResponse[0]->getAccessToken()); - $this->assertEquals('foo_token_two', $batchResponse[1]->getAccessToken()); - $this->assertEquals('foo_token_three', $batchResponse[2]->getAccessToken()); + static::assertInstanceOf(Response::class, $batchResponse[0]); + static::assertInstanceOf(Request::class, $batchResponse[0]->getRequest()); + static::assertEquals('foo_token_one', $batchResponse[0]->getAccessToken()); + static::assertEquals('foo_token_two', $batchResponse[1]->getAccessToken()); + static::assertEquals('foo_token_three', $batchResponse[2]->getAccessToken()); } - public function testHeadersFromBatchRequestCanBeAccessed() + public function testHeadersFromBatchRequestCanBeAccessed(): void { $graphResponseJson = '['; $graphResponseJson .= '{"code":200,"headers":[{"name":"Facebook-API-Version","value":"v2.0"},{"name":"ETag","value":"\"fooTag\""}],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ',{"code":200,"headers":[{"name":"Facebook-API-Version","value":"v2.5"},{"name":"ETag","value":"\"barTag\""}],"body":"{\"foo\":\"bar\"}"}'; $graphResponseJson .= ']'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); + $response = new Response($this->request, $graphResponseJson, 200); $requests = [ - new FacebookRequest($this->app, 'foo_token_one', 'GET', '/me'), - new FacebookRequest($this->app, 'foo_token_two', 'GET', '/you'), + new Request($this->app, 'foo_token_one', 'GET', '/me'), + new Request($this->app, 'foo_token_two', 'GET', '/you'), ]; - $batchRequest = new FacebookBatchRequest($this->app, $requests); - $batchResponse = new FacebookBatchResponse($batchRequest, $response); + $batchRequest = new BatchRequest($this->app, $requests); + $batchResponse = new BatchResponse($batchRequest, $response); - $this->assertEquals('v2.0', $batchResponse[0]->getGraphVersion()); - $this->assertEquals('"fooTag"', $batchResponse[0]->getETag()); - $this->assertEquals('v2.5', $batchResponse[1]->getGraphVersion()); - $this->assertEquals('"barTag"', $batchResponse[1]->getETag()); - $this->assertEquals([ - 'Facebook-API-Version' => 'v2.5', - 'ETag' => '"barTag"', + static::assertEquals('v2.0', $batchResponse[0]->getGraphVersion()); + static::assertEquals('"fooTag"', $batchResponse[0]->getETag()); + static::assertEquals('v2.5', $batchResponse[1]->getGraphVersion()); + static::assertEquals('"barTag"', $batchResponse[1]->getETag()); + static::assertEquals([ + 'Facebook-API-Version' => 'v2.5', + 'ETag' => '"barTag"', ], $batchResponse[1]->getHeaders()); } } diff --git a/tests/ClientTest.php b/tests/ClientTest.php new file mode 100644 index 000000000..b545db702 --- /dev/null +++ b/tests/ClientTest.php @@ -0,0 +1,297 @@ +fbApp = new Application('id', 'shhhh!'); + $this->fbClient = new Client(new MyFooClientHandler()); + } + + public function testACustomHttpClientCanBeInjected(): void + { + $handler = new MyFooClientHandler(); + $client = new Client($handler); + $httpHandler = $client->getHttpCllient(); + + static::assertInstanceOf(MyFooClientHandler::class, $httpHandler); + } + + public function testTheHttpClientWillFallbackToDefault(): void + { + $client = new Client(); + $httpHandler = $client->getHttpCllient(); + + static::assertInstanceOf(ClientInterface::class, $httpHandler); + } + + public function testBetaModeCanBeDisabledOrEnabledViaConstructor(): void + { + $client = new Client(null, false); + $url = $client->getBaseGraphUrl(); + static::assertEquals(Client::BASE_GRAPH_URL, $url); + + $client = new Client(null, true); + $url = $client->getBaseGraphUrl(); + static::assertEquals(Client::BASE_GRAPH_URL_BETA, $url); + } + + public function testBetaModeCanBeDisabledOrEnabledViaMethod(): void + { + $client = new Client(); + $client->enableBetaMode(false); + $url = $client->getBaseGraphUrl(); + static::assertEquals(Client::BASE_GRAPH_URL, $url); + + $client->enableBetaMode(true); + $url = $client->getBaseGraphUrl(); + static::assertEquals(Client::BASE_GRAPH_URL_BETA, $url); + } + + public function testGraphVideoUrlCanBeSet(): void + { + $client = new Client(); + $client->enableBetaMode(false); + $url = $client->getBaseGraphUrl(true); + static::assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url); + + $client->enableBetaMode(true); + $url = $client->getBaseGraphUrl(true); + static::assertEquals(Client::BASE_GRAPH_VIDEO_URL_BETA, $url); + } + + public function testAFacebookRequestEntityCanBeUsedToSendARequestToGraph(): void + { + $fbRequest = new Request($this->fbApp, 'token', 'GET', '/foo', ['verify' => false]); + $response = $this->fbClient->sendRequest($fbRequest); + + static::assertInstanceOf(Response::class, $response); + static::assertEquals(200, $response->getHttpStatusCode()); + static::assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody()); + } + + public function testAFacebookBatchRequestEntityCanBeUsedToSendABatchRequestToGraph(): void + { + $fbRequests = [ + new Request($this->fbApp, 'token', 'GET', '/foo'), + new Request($this->fbApp, 'token', 'POST', '/bar'), + ]; + $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests); + + $fbBatchClient = new Client(new MyFooBatchClientHandler()); + $response = $fbBatchClient->sendBatchRequest($fbBatchRequest); + + static::assertInstanceOf(BatchResponse::class, $response); + static::assertEquals('GET', $response[0]->getRequest()->getMethod()); + static::assertEquals('POST', $response[1]->getRequest()->getMethod()); + } + + public function testAFacebookBatchRequestWillProperlyBatchFiles(): void + { + $fbRequests = [ + new Request($this->fbApp, 'token', 'POST', '/photo', [ + 'message' => 'foobar', + 'source' => new File(__DIR__ . '/foo.txt'), + ]), + new Request($this->fbApp, 'token', 'POST', '/video', [ + 'message' => 'foobar', + 'source' => new Video(__DIR__ . '/foo.txt'), + ]), + ]; + $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests); + $fbBatchRequest->prepareRequestsForBatch(); + + list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest); + + static::assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url); + static::assertEquals('POST', $method); + static::assertStringContainsString('multipart/form-data; boundary=', $headers['Content-Type']); + static::assertStringContainsString('Content-Disposition: form-data; name="batch"', $body); + static::assertStringContainsString('Content-Disposition: form-data; name="include_headers"', $body); + static::assertStringContainsString('"name":0,"attached_files":', $body); + static::assertStringContainsString('"name":1,"attached_files":', $body); + static::assertStringContainsString('"; filename="foo.txt"', $body); + } + + public function testARequestOfParamsWillBeUrlEncoded(): void + { + $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']); + $response = $this->fbClient->sendRequest($fbRequest); + + $headersSent = $response->getRequest()->getHeaders(); + + static::assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']); + } + + public function testARequestWithFilesWillBeMultipart(): void + { + $myFile = new File(__DIR__ . '/foo.txt'); + $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]); + $response = $this->fbClient->sendRequest($fbRequest); + + $headersSent = $response->getRequest()->getHeaders(); + + static::assertStringContainsString('multipart/form-data; boundary=', $headersSent['Content-Type']); + } + + public function testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided(): void + { + $this->expectException(FacebookSDKException::class); + + $fbRequest = new Request($this->fbApp, null, 'GET', '/foo'); + $this->fbClient->sendRequest($fbRequest); + } + + /** + * @group integration + */ + public function testCanCreateATestUserAndGetTheProfileAndThenDeleteTheTestUser(): void + { + $this->initializeTestApp(); + + // Create a test user + $testUserPath = '/' . FacebookTestCredential::$appId . '/accounts/test-users'; + $params = [ + 'installed' => true, + 'name' => 'Foo Phpunit User', + 'locale' => 'en_US', + 'permissions' => implode(',', ['read_stream', 'user_photos']), + ]; + + $request = new Request( + static::$testFacebookApp, + static::$testFacebookApp->getAccessToken(), + 'POST', + $testUserPath, + $params + ); + $response = static::$testFacebookClient->sendRequest($request)->getGraphNode(); + + $testUserId = $response->getField('id'); + $testUserAccessToken = $response->getField('access_token'); + + // Get the test user's profile + $request = new Request( + static::$testFacebookApp, + $testUserAccessToken, + 'GET', + '/me' + ); + $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode(); + + static::assertInstanceOf(GraphNode::class, $graphNode); + static::assertNotNull($graphNode->getField('id')); + static::assertEquals('Foo Phpunit User', $graphNode->getField('name')); + + // Delete test user + $request = new Request( + static::$testFacebookApp, + static::$testFacebookApp->getAccessToken(), + 'DELETE', + '/' . $testUserId + ); + $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode(); + + static::assertTrue($graphNode->getField('success')); + } + + public function initializeTestApp() + { + if (!file_exists(__DIR__ . '/FacebookTestCredentials.php')) { + throw new FacebookSDKException( + 'You must create a FacebookTestCredentials.php file from FacebookTestCredentials.php.dist' + ); + } + + if (!strlen(FacebookTestCredentials::$appId) || + !strlen(FacebookTestCredentials::$appSecret) + ) { + throw new FacebookSDKException( + 'You must fill out FacebookTestCredentials.php' + ); + } + static::$testFacebookApp = new Application( + FacebookTestCredentials::$appId, + FacebookTestCredentials::$appSecret + ); + + // Use default client + $client = null; + + // Uncomment to enable curl implementation. + //$client = new FacebookCurlHttpClient(); + + // Uncomment to enable stream wrapper implementation. + //$client = new FacebookStreamHttpClient(); + + // Uncomment to enable Guzzle implementation. + //$client = new FacebookGuzzleHttpClient(); + + static::$testFacebookClient = new Client($client); + } +} diff --git a/tests/Exceptions/FacebookResponseExceptionTest.php b/tests/Exceptions/FacebookResponseExceptionTest.php deleted file mode 100644 index ae18fdec8..000000000 --- a/tests/Exceptions/FacebookResponseExceptionTest.php +++ /dev/null @@ -1,278 +0,0 @@ -request = new FacebookRequest(new FacebookApp('123', 'foo')); - } - - public function testAuthenticationExceptions() - { - $params = [ - 'error' => [ - 'code' => 100, - 'message' => 'errmsg', - 'error_subcode' => 0, - 'type' => 'exception' - ], - ]; - - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(100, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(401, $exception->getHttpStatusCode()); - - $params['error']['code'] = 102; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(102, $exception->getCode()); - - $params['error']['code'] = 190; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(190, $exception->getCode()); - - $params['error']['type'] = 'OAuthException'; - $params['error']['code'] = 0; - $params['error']['error_subcode'] = 458; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(458, $exception->getSubErrorCode()); - - $params['error']['error_subcode'] = 460; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(460, $exception->getSubErrorCode()); - - $params['error']['error_subcode'] = 463; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(463, $exception->getSubErrorCode()); - - $params['error']['error_subcode'] = 467; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(467, $exception->getSubErrorCode()); - - $params['error']['error_subcode'] = 0; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(0, $exception->getSubErrorCode()); - } - - public function testServerExceptions() - { - $params = [ - 'error' => [ - 'code' => 1, - 'message' => 'errmsg', - 'error_subcode' => 0, - 'type' => 'exception' - ], - ]; - - $response = new FacebookResponse($this->request, json_encode($params), 500); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookServerException', $exception->getPrevious()); - $this->assertEquals(1, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(500, $exception->getHttpStatusCode()); - - $params['error']['code'] = 2; - $response = new FacebookResponse($this->request, json_encode($params), 500); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookServerException', $exception->getPrevious()); - $this->assertEquals(2, $exception->getCode()); - } - - public function testThrottleExceptions() - { - $params = [ - 'error' => [ - 'code' => 4, - 'message' => 'errmsg', - 'error_subcode' => 0, - 'type' => 'exception' - ], - ]; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookThrottleException', $exception->getPrevious()); - $this->assertEquals(4, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(401, $exception->getHttpStatusCode()); - - $params['error']['code'] = 17; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookThrottleException', $exception->getPrevious()); - $this->assertEquals(17, $exception->getCode()); - - $params['error']['code'] = 341; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookThrottleException', $exception->getPrevious()); - $this->assertEquals(341, $exception->getCode()); - } - - public function testUserIssueExceptions() - { - $params = [ - 'error' => [ - 'code' => 230, - 'message' => 'errmsg', - 'error_subcode' => 459, - 'type' => 'exception' - ], - ]; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(230, $exception->getCode()); - $this->assertEquals(459, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(401, $exception->getHttpStatusCode()); - - $params['error']['error_subcode'] = 464; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthenticationException', $exception->getPrevious()); - $this->assertEquals(464, $exception->getSubErrorCode()); - } - - public function testAuthorizationExceptions() - { - $params = [ - 'error' => [ - 'code' => 10, - 'message' => 'errmsg', - 'error_subcode' => 0, - 'type' => 'exception' - ], - ]; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthorizationException', $exception->getPrevious()); - $this->assertEquals(10, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(401, $exception->getHttpStatusCode()); - - $params['error']['code'] = 200; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthorizationException', $exception->getPrevious()); - $this->assertEquals(200, $exception->getCode()); - - $params['error']['code'] = 250; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthorizationException', $exception->getPrevious()); - $this->assertEquals(250, $exception->getCode()); - - $params['error']['code'] = 299; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookAuthorizationException', $exception->getPrevious()); - $this->assertEquals(299, $exception->getCode()); - } - - public function testClientExceptions() - { - $params = [ - 'error' => [ - 'code' => 506, - 'message' => 'errmsg', - 'error_subcode' => 0, - 'type' => 'exception' - ], - ]; - $response = new FacebookResponse($this->request, json_encode($params), 401); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookClientException', $exception->getPrevious()); - $this->assertEquals(506, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('exception', $exception->getErrorType()); - $this->assertEquals('errmsg', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(401, $exception->getHttpStatusCode()); - } - - public function testOtherException() - { - $params = [ - 'error' => [ - 'code' => 42, - 'message' => 'ship love', - 'error_subcode' => 0, - 'type' => 'feature' - ], - ]; - $response = new FacebookResponse($this->request, json_encode($params), 200); - $exception = FacebookResponseException::create($response); - $this->assertInstanceOf('Facebook\Exceptions\FacebookOtherException', $exception->getPrevious()); - $this->assertEquals(42, $exception->getCode()); - $this->assertEquals(0, $exception->getSubErrorCode()); - $this->assertEquals('feature', $exception->getErrorType()); - $this->assertEquals('ship love', $exception->getMessage()); - $this->assertEquals(json_encode($params), $exception->getRawResponse()); - $this->assertEquals(200, $exception->getHttpStatusCode()); - } -} diff --git a/tests/Exceptions/ResponseExceptionTest.php b/tests/Exceptions/ResponseExceptionTest.php new file mode 100644 index 000000000..89528324f --- /dev/null +++ b/tests/Exceptions/ResponseExceptionTest.php @@ -0,0 +1,291 @@ +request = new Request(new Application('123', 'foo')); + } + + public function testAuthenticationExceptions() + { + $params = [ + 'error' => [ + 'code' => 100, + 'message' => 'errmsg', + 'error_subcode' => 0, + 'type' => 'exception' + ], + ]; + + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(100, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(401, $exception->getHttpStatusCode()); + + $params['error']['code'] = 102; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(102, $exception->getCode()); + + $params['error']['code'] = 190; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(190, $exception->getCode()); + + $params['error']['type'] = 'OAuthException'; + $params['error']['code'] = 0; + $params['error']['error_subcode'] = 458; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(458, $exception->getSubErrorCode()); + + $params['error']['error_subcode'] = 460; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(460, $exception->getSubErrorCode()); + + $params['error']['error_subcode'] = 463; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(463, $exception->getSubErrorCode()); + + $params['error']['error_subcode'] = 467; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(467, $exception->getSubErrorCode()); + + $params['error']['error_subcode'] = 0; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(0, $exception->getSubErrorCode()); + } + + public function testServerExceptions() + { + $params = [ + 'error' => [ + 'code' => 1, + 'message' => 'errmsg', + 'error_subcode' => 0, + 'type' => 'exception' + ], + ]; + + $response = new Response($this->request, json_encode($params), 500); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookServerException::class, $exception->getPrevious()); + static::assertEquals(1, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(500, $exception->getHttpStatusCode()); + + $params['error']['code'] = 2; + $response = new Response($this->request, json_encode($params), 500); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookServerException::class, $exception->getPrevious()); + static::assertEquals(2, $exception->getCode()); + } + + public function testThrottleExceptions() + { + $params = [ + 'error' => [ + 'code' => 4, + 'message' => 'errmsg', + 'error_subcode' => 0, + 'type' => 'exception' + ], + ]; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookThrottleException::class, $exception->getPrevious()); + static::assertEquals(4, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(401, $exception->getHttpStatusCode()); + + $params['error']['code'] = 17; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookThrottleException::class, $exception->getPrevious()); + static::assertEquals(17, $exception->getCode()); + + $params['error']['code'] = 341; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookThrottleException::class, $exception->getPrevious()); + static::assertEquals(341, $exception->getCode()); + } + + public function testUserIssueExceptions() + { + $params = [ + 'error' => [ + 'code' => 230, + 'message' => 'errmsg', + 'error_subcode' => 459, + 'type' => 'exception' + ], + ]; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(230, $exception->getCode()); + static::assertEquals(459, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(401, $exception->getHttpStatusCode()); + + $params['error']['error_subcode'] = 464; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthenticationException::class, $exception->getPrevious()); + static::assertEquals(464, $exception->getSubErrorCode()); + } + + public function testAuthorizationExceptions() + { + $params = [ + 'error' => [ + 'code' => 10, + 'message' => 'errmsg', + 'error_subcode' => 0, + 'type' => 'exception' + ], + ]; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthorizationException::class, $exception->getPrevious()); + static::assertEquals(10, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(401, $exception->getHttpStatusCode()); + + $params['error']['code'] = 200; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthorizationException::class, $exception->getPrevious()); + static::assertEquals(200, $exception->getCode()); + + $params['error']['code'] = 250; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthorizationException::class, $exception->getPrevious()); + static::assertEquals(250, $exception->getCode()); + + $params['error']['code'] = 299; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookAuthorizationException::class, $exception->getPrevious()); + static::assertEquals(299, $exception->getCode()); + } + + public function testClientExceptions() + { + $params = [ + 'error' => [ + 'code' => 506, + 'message' => 'errmsg', + 'error_subcode' => 0, + 'type' => 'exception' + ], + ]; + $response = new Response($this->request, json_encode($params), 401); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookClientException::class, $exception->getPrevious()); + static::assertEquals(506, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('exception', $exception->getErrorType()); + static::assertEquals('errmsg', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(401, $exception->getHttpStatusCode()); + } + + public function testOtherException() + { + $params = [ + 'error' => [ + 'code' => 42, + 'message' => 'ship love', + 'error_subcode' => 0, + 'type' => 'feature' + ], + ]; + $response = new Response($this->request, json_encode($params), 200); + $exception = FacebookResponseException::create($response); + static::assertInstanceOf(FacebookOtherException::class, $exception->getPrevious()); + static::assertEquals(42, $exception->getCode()); + static::assertEquals(0, $exception->getSubErrorCode()); + static::assertEquals('feature', $exception->getErrorType()); + static::assertEquals('ship love', $exception->getMessage()); + static::assertEquals(json_encode($params), $exception->getRawResponse()); + static::assertEquals(200, $exception->getHttpStatusCode()); + } +} diff --git a/tests/FacebookClientTest.php b/tests/FacebookClientTest.php deleted file mode 100644 index 9a08fb6e8..000000000 --- a/tests/FacebookClientTest.php +++ /dev/null @@ -1,294 +0,0 @@ -fbApp = new FacebookApp('id', 'shhhh!'); - $this->fbClient = new FacebookClient(new MyFooClientHandler()); - } - - public function testACustomHttpClientCanBeInjected() - { - $handler = new MyFooClientHandler(); - $client = new FacebookClient($handler); - $httpHandler = $client->getHttpClientHandler(); - - $this->assertInstanceOf('Facebook\Tests\Fixtures\MyFooClientHandler', $httpHandler); - } - - public function testTheHttpClientWillFallbackToDefault() - { - $client = new FacebookClient(); - $httpHandler = $client->getHttpClientHandler(); - - if (function_exists('curl_init')) { - $this->assertInstanceOf('Facebook\HttpClients\FacebookCurlHttpClient', $httpHandler); - } else { - $this->assertInstanceOf('Facebook\HttpClients\FacebookStreamHttpClient', $httpHandler); - } - } - - public function testBetaModeCanBeDisabledOrEnabledViaConstructor() - { - $client = new FacebookClient(null, false); - $url = $client->getBaseGraphUrl(); - $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url); - - $client = new FacebookClient(null, true); - $url = $client->getBaseGraphUrl(); - $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url); - } - - public function testBetaModeCanBeDisabledOrEnabledViaMethod() - { - $client = new FacebookClient(); - $client->enableBetaMode(false); - $url = $client->getBaseGraphUrl(); - $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url); - - $client->enableBetaMode(true); - $url = $client->getBaseGraphUrl(); - $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url); - } - - public function testGraphVideoUrlCanBeSet() - { - $client = new FacebookClient(); - $client->enableBetaMode(false); - $url = $client->getBaseGraphUrl($postToVideoUrl = true); - $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL, $url); - - $client->enableBetaMode(true); - $url = $client->getBaseGraphUrl($postToVideoUrl = true); - $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL_BETA, $url); - } - - public function testAFacebookRequestEntityCanBeUsedToSendARequestToGraph() - { - $fbRequest = new FacebookRequest($this->fbApp, 'token', 'GET', '/foo'); - $response = $this->fbClient->sendRequest($fbRequest); - - $this->assertInstanceOf('Facebook\FacebookResponse', $response); - $this->assertEquals(200, $response->getHttpStatusCode()); - $this->assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody()); - } - - public function testAFacebookBatchRequestEntityCanBeUsedToSendABatchRequestToGraph() - { - $fbRequests = [ - new FacebookRequest($this->fbApp, 'token', 'GET', '/foo'), - new FacebookRequest($this->fbApp, 'token', 'POST', '/bar'), - ]; - $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests); - - $fbBatchClient = new FacebookClient(new MyFooBatchClientHandler()); - $response = $fbBatchClient->sendBatchRequest($fbBatchRequest); - - $this->assertInstanceOf('Facebook\FacebookBatchResponse', $response); - $this->assertEquals('GET', $response[0]->getRequest()->getMethod()); - $this->assertEquals('POST', $response[1]->getRequest()->getMethod()); - } - - public function testAFacebookBatchRequestWillProperlyBatchFiles() - { - $fbRequests = [ - new FacebookRequest($this->fbApp, 'token', 'POST', '/photo', [ - 'message' => 'foobar', - 'source' => new FacebookFile(__DIR__ . '/foo.txt'), - ]), - new FacebookRequest($this->fbApp, 'token', 'POST', '/video', [ - 'message' => 'foobar', - 'source' => new FacebookVideo(__DIR__ . '/foo.txt'), - ]), - ]; - $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests); - $fbBatchRequest->prepareRequestsForBatch(); - - list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest); - - $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL . '/' . Facebook::DEFAULT_GRAPH_VERSION, $url); - $this->assertEquals('POST', $method); - $this->assertContains('multipart/form-data; boundary=', $headers['Content-Type']); - $this->assertContains('Content-Disposition: form-data; name="batch"', $body); - $this->assertContains('Content-Disposition: form-data; name="include_headers"', $body); - $this->assertContains('"name":0,"attached_files":', $body); - $this->assertContains('"name":1,"attached_files":', $body); - $this->assertContains('"; filename="foo.txt"', $body); - } - - public function testARequestOfParamsWillBeUrlEncoded() - { - $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']); - $response = $this->fbClient->sendRequest($fbRequest); - - $headersSent = $response->getRequest()->getHeaders(); - - $this->assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']); - } - - public function testARequestWithFilesWillBeMultipart() - { - $myFile = new FacebookFile(__DIR__ . '/foo.txt'); - $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]); - $response = $this->fbClient->sendRequest($fbRequest); - - $headersSent = $response->getRequest()->getHeaders(); - - $this->assertContains('multipart/form-data; boundary=', $headersSent['Content-Type']); - } - - public function testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided() - { - $this->setExpectedException('Facebook\Exceptions\FacebookSDKException'); - - $fbRequest = new FacebookRequest($this->fbApp, null, 'GET', '/foo'); - $this->fbClient->sendRequest($fbRequest); - } - - /** - * @group integration - */ - public function testCanCreateATestUserAndGetTheProfileAndThenDeleteTheTestUser() - { - $this->initializeTestApp(); - - // Create a test user - $testUserPath = '/' . FacebookTestCredentials::$appId . '/accounts/test-users'; - $params = [ - 'installed' => true, - 'name' => 'Foo Phpunit User', - 'locale' => 'en_US', - 'permissions' => implode(',', ['read_stream', 'user_photos']), - ]; - - $request = new FacebookRequest( - static::$testFacebookApp, - static::$testFacebookApp->getAccessToken(), - 'POST', - $testUserPath, - $params - ); - $response = static::$testFacebookClient->sendRequest($request)->getGraphNode(); - - $testUserId = $response->getField('id'); - $testUserAccessToken = $response->getField('access_token'); - - // Get the test user's profile - $request = new FacebookRequest( - static::$testFacebookApp, - $testUserAccessToken, - 'GET', - '/me' - ); - $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode(); - - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphNode); - $this->assertNotNull($graphNode->getField('id')); - $this->assertEquals('Foo Phpunit User', $graphNode->getField('name')); - - // Delete test user - $request = new FacebookRequest( - static::$testFacebookApp, - static::$testFacebookApp->getAccessToken(), - 'DELETE', - '/' . $testUserId - ); - $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode(); - - $this->assertTrue($graphNode->getField('success')); - } - - public function initializeTestApp() - { - if (!file_exists(__DIR__ . '/FacebookTestCredentials.php')) { - throw new FacebookSDKException( - 'You must create a FacebookTestCredentials.php file from FacebookTestCredentials.php.dist' - ); - } - - if (!strlen(FacebookTestCredentials::$appId) || - !strlen(FacebookTestCredentials::$appSecret) - ) { - throw new FacebookSDKException( - 'You must fill out FacebookTestCredentials.php' - ); - } - static::$testFacebookApp = new FacebookApp( - FacebookTestCredentials::$appId, - FacebookTestCredentials::$appSecret - ); - - // Use default client - $client = null; - - // Uncomment to enable curl implementation. - //$client = new FacebookCurlHttpClient(); - - // Uncomment to enable stream wrapper implementation. - //$client = new FacebookStreamHttpClient(); - - // Uncomment to enable Guzzle implementation. - //$client = new FacebookGuzzleHttpClient(); - - static::$testFacebookClient = new FacebookClient($client); - } -} diff --git a/tests/FacebookRequestTest.php b/tests/FacebookRequestTest.php deleted file mode 100755 index 697fd94ca..000000000 --- a/tests/FacebookRequestTest.php +++ /dev/null @@ -1,207 +0,0 @@ -assertInstanceOf('Facebook\FacebookRequest', $request); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAMissingAccessTokenWillThrow() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app); - - $request->validateAccessToken(); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAMissingMethodWillThrow() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app); - - $request->validateMethod(); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAnInvalidMethodWillThrow() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, 'foo_token', 'FOO'); - - $request->validateMethod(); - } - - public function testGetHeadersWillAutoAppendETag() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, null, 'GET', '/foo', [], 'fooETag'); - - $headers = $request->getHeaders(); - - $expectedHeaders = FacebookRequest::getDefaultHeaders(); - $expectedHeaders['If-None-Match'] = 'fooETag'; - - $this->assertEquals($expectedHeaders, $headers); - } - - public function testGetParamsWillAutoAppendAccessTokenAndAppSecretProof() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, 'foo_token', 'POST', '/foo', ['foo' => 'bar']); - - $params = $request->getParams(); - - $this->assertEquals([ - 'foo' => 'bar', - 'access_token' => 'foo_token', - 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', - ], $params); - } - - public function testAnAccessTokenCanBeSetFromTheParams() - { - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, null, 'POST', '/me', ['access_token' => 'bar_token']); - - $accessToken = $request->getAccessToken(); - - $this->assertEquals('bar_token', $accessToken); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAccessTokenConflictsWillThrow() - { - $app = new FacebookApp('123', 'foo_secret'); - new FacebookRequest($app, 'foo_token', 'POST', '/me', ['access_token' => 'bar_token']); - } - - public function testAProperUrlWillBeGenerated() - { - $app = new FacebookApp('123', 'foo_secret'); - $getRequest = new FacebookRequest($app, 'foo_token', 'GET', '/foo', ['foo' => 'bar']); - - $getUrl = $getRequest->getUrl(); - $expectedParams = 'foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9'; - $expectedUrl = '/' . Facebook::DEFAULT_GRAPH_VERSION . '/foo?' . $expectedParams; - - $this->assertEquals($expectedUrl, $getUrl); - - $postRequest = new FacebookRequest($app, 'foo_token', 'POST', '/bar', ['foo' => 'bar']); - - $postUrl = $postRequest->getUrl(); - $expectedUrl = '/' . Facebook::DEFAULT_GRAPH_VERSION . '/bar'; - - $this->assertEquals($expectedUrl, $postUrl); - } - - public function testAuthenticationParamsAreStrippedAndReapplied() - { - $app = new FacebookApp('123', 'foo_secret'); - - $request = new FacebookRequest( - $app, - $accessToken = 'foo_token', - $method = 'GET', - $endpoint = '/foo', - $params = [ - 'access_token' => 'foo_token', - 'appsecret_proof' => 'bar_app_secret', - 'bar' => 'baz', - ] - ); - - $url = $request->getUrl(); - - $expectedParams = 'bar=baz&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9'; - $expectedUrl = '/' . Facebook::DEFAULT_GRAPH_VERSION . '/foo?' . $expectedParams; - $this->assertEquals($expectedUrl, $url); - - $params = $request->getParams(); - - $expectedParams = [ - 'access_token' => 'foo_token', - 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', - 'bar' => 'baz', - ]; - $this->assertEquals($expectedParams, $params); - } - - public function testAFileCanBeAddedToParams() - { - $myFile = new FacebookFile(__DIR__ . '/foo.txt'); - $params = [ - 'name' => 'Foo Bar', - 'source' => $myFile, - ]; - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, 'foo_token', 'POST', '/foo/photos', $params); - - $actualParams = $request->getParams(); - - $this->assertTrue($request->containsFileUploads()); - $this->assertFalse($request->containsVideoUploads()); - $this->assertTrue(!isset($actualParams['source'])); - $this->assertEquals('Foo Bar', $actualParams['name']); - } - - public function testAVideoCanBeAddedToParams() - { - $myFile = new FacebookVideo(__DIR__ . '/foo.txt'); - $params = [ - 'name' => 'Foo Bar', - 'source' => $myFile, - ]; - $app = new FacebookApp('123', 'foo_secret'); - $request = new FacebookRequest($app, 'foo_token', 'POST', '/foo/videos', $params); - - $actualParams = $request->getParams(); - - $this->assertTrue($request->containsFileUploads()); - $this->assertTrue($request->containsVideoUploads()); - $this->assertTrue(!isset($actualParams['source'])); - $this->assertEquals('Foo Bar', $actualParams['name']); - } -} diff --git a/tests/FacebookTest.php b/tests/FacebookTest.php index 035e8d70f..a61d8588e 100644 --- a/tests/FacebookTest.php +++ b/tests/FacebookTest.php @@ -21,107 +21,94 @@ * DEALINGS IN THE SOFTWARE. * */ + namespace Facebook\Tests; +use Facebook\BatchRequest; +use Facebook\Exceptions\FacebookSDKException as FacebookSDKExceptionAlias; use Facebook\Facebook; -use Facebook\FacebookClient; -use Facebook\FacebookRequest; +use Facebook\Client; +use Facebook\GraphNodes\GraphUser; +use Facebook\PersistentData\FacebookMemoryPersistentDataHandler; +use Facebook\Request; use Facebook\Authentication\AccessToken; use Facebook\GraphNodes\GraphEdge; +use Facebook\Response; use Facebook\Tests\Fixtures\FakeGraphApiForResumableUpload; -use Facebook\Tests\Fixtures\FooBarPseudoRandomStringGenerator; use Facebook\Tests\Fixtures\FooClientInterface; use Facebook\Tests\Fixtures\FooPersistentDataInterface; use Facebook\Tests\Fixtures\FooUrlDetectionInterface; +use Facebook\Url\UrlDetectionHandler; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; -class FacebookTest extends \PHPUnit_Framework_TestCase +/** + * + */ +class FacebookTest extends TestCase { - protected $config = [ + protected array $config = [ 'app_id' => '1337', 'app_secret' => 'foo_secret', + 'default_graph_version' => 'v0.0', ]; - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testInstantiatingWithoutAppIdThrows() { + $this->expectException(FacebookSDKExceptionAlias::class); // unset value so there is no fallback to test expected Exception - putenv(Facebook::APP_ID_ENV_NAME.'='); + putenv(Facebook::APP_ID_ENV_NAME . '='); $config = [ 'app_secret' => 'foo_secret', + 'default_graph_version' => 'v0.0', ]; new Facebook($config); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testInstantiatingWithoutAppSecretThrows() { + $this->expectException(FacebookSDKExceptionAlias::class); // unset value so there is no fallback to test expected Exception - putenv(Facebook::APP_SECRET_ENV_NAME.'='); + putenv(Facebook::APP_SECRET_ENV_NAME . '='); $config = [ 'app_id' => 'foo_id', + 'default_graph_version' => 'v0.0', ]; new Facebook($config); } - /** - * @expectedException \InvalidArgumentException - */ - public function testSettingAnInvalidHttpClientHandlerThrows() + public function testInstantiatingWithoutDefaultGraphVersionThrows(): void { - $config = array_merge($this->config, [ - 'http_client_handler' => 'foo_handler', - ]); + $this->expectException(InvalidArgumentException::class); + $config = [ + 'app_id' => 'foo_id', + 'app_secret' => 'foo_secret', + ]; new Facebook($config); } - public function testCurlHttpClientHandlerCanBeForced() + public function testSettingAnInvalidHttpClientTypeThrows(): void { - if (!extension_loaded('curl')) { - $this->markTestSkipped('cURL must be installed to test cURL client handler.'); - } + $this->expectException(InvalidArgumentException::class); $config = array_merge($this->config, [ - 'http_client_handler' => 'curl' + 'http_client' => 'foo_client', ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\HttpClients\FacebookCurlHttpClient', - $fb->getClient()->getHttpClientHandler() - ); + new Facebook($config); } - public function testStreamHttpClientHandlerCanBeForced() - { - $config = array_merge($this->config, [ - 'http_client_handler' => 'stream' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\HttpClients\FacebookStreamHttpClient', - $fb->getClient()->getHttpClientHandler() - ); - } - public function testGuzzleHttpClientHandlerCanBeForced() + public function testSettingAnInvalidHttpClientClassThrows(): void { + $this->expectException(InvalidArgumentException::class); $config = array_merge($this->config, [ - 'http_client_handler' => 'guzzle' + 'http_client' => new \stdClass(), ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\HttpClients\FacebookGuzzleHttpClient', - $fb->getClient()->getHttpClientHandler() - ); + new Facebook($config); } - /** - * @expectedException \InvalidArgumentException - */ public function testSettingAnInvalidPersistentDataHandlerThrows() { + $this->expectException(InvalidArgumentException::class); $config = array_merge($this->config, [ 'persistent_data_handler' => 'foo_handler', ]); @@ -134,20 +121,15 @@ public function testPersistentDataHandlerCanBeForced() 'persistent_data_handler' => 'memory' ]); $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\PersistentData\FacebookMemoryPersistentDataHandler', + static::assertInstanceOf( + FacebookMemoryPersistentDataHandler::class, $fb->getRedirectLoginHelper()->getPersistentDataHandler() ); } - public function testSettingAnInvalidUrlHandlerThrows() + public function testSettingAnInvalidUrlHandlerThrows(): void { - $expectedException = (PHP_MAJOR_VERSION > 5 && class_exists('TypeError')) - ? 'TypeError' - : 'PHPUnit_Framework_Error'; - - $this->setExpectedException($expectedException); - + $this->expectError(); $config = array_merge($this->config, [ 'url_detection_handler' => 'foo_handler', ]); @@ -157,7 +139,7 @@ public function testSettingAnInvalidUrlHandlerThrows() public function testTheUrlHandlerWillDefaultToTheFacebookImplementation() { $fb = new Facebook($this->config); - $this->assertInstanceOf('Facebook\Url\FacebookUrlDetectionHandler', $fb->getUrlDetectionHandler()); + static::assertInstanceOf(UrlDetectionHandler::class, $fb->getUrlDetectionHandler()); } public function testAnAccessTokenCanBeSetAsAString() @@ -166,8 +148,8 @@ public function testAnAccessTokenCanBeSetAsAString() $fb->setDefaultAccessToken('foo_token'); $accessToken = $fb->getDefaultAccessToken(); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('foo_token', (string)$accessToken); + static::assertInstanceOf(AccessToken::class, $accessToken); + static::assertEquals('foo_token', (string)$accessToken); } public function testAnAccessTokenCanBeSetAsAnAccessTokenEntity() @@ -176,108 +158,13 @@ public function testAnAccessTokenCanBeSetAsAnAccessTokenEntity() $fb->setDefaultAccessToken(new AccessToken('bar_token')); $accessToken = $fb->getDefaultAccessToken(); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('bar_token', (string)$accessToken); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testSettingAnInvalidPseudoRandomStringGeneratorThrows() - { - $config = array_merge($this->config, [ - 'pseudo_random_string_generator' => 'foo_generator', - ]); - new Facebook($config); + static::assertInstanceOf(AccessToken::class, $accessToken); + static::assertEquals('bar_token', (string)$accessToken); } - public function testRandomBytesCsprgCanBeForced() - { - if (!function_exists('random_bytes')) { - $this->markTestSkipped( - 'Must have PHP 7 or paragonie/random_compat installed to test random_bytes().' - ); - } - - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'memory', // To keep session errors from happening - 'pseudo_random_string_generator' => 'random_bytes' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\PseudoRandomString\RandomBytesPseudoRandomStringGenerator', - $fb->getRedirectLoginHelper()->getPseudoRandomStringGenerator() - ); - } - - public function testMcryptCsprgCanBeForced() - { - if (!function_exists('mcrypt_create_iv')) { - $this->markTestSkipped( - 'Mcrypt must be installed to test mcrypt_create_iv().' - ); - } - - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'memory', // To keep session errors from happening - 'pseudo_random_string_generator' => 'mcrypt' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\PseudoRandomString\McryptPseudoRandomStringGenerator', - $fb->getRedirectLoginHelper()->getPseudoRandomStringGenerator() - ); - } - - public function testOpenSslCsprgCanBeForced() - { - if (!function_exists('openssl_random_pseudo_bytes')) { - $this->markTestSkipped( - 'The OpenSSL extension must be enabled to test openssl_random_pseudo_bytes().' - ); - } - - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'memory', // To keep session errors from happening - 'pseudo_random_string_generator' => 'openssl' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\PseudoRandomString\OpenSslPseudoRandomStringGenerator', - $fb->getRedirectLoginHelper()->getPseudoRandomStringGenerator() - ); - } - - public function testUrandomCsprgCanBeForced() - { - if (ini_get('open_basedir')) { - $this->markTestSkipped( - 'Cannot test /dev/urandom generator due to open_basedir constraint.' - ); - } - - if (!is_readable('/dev/urandom')) { - $this->markTestSkipped( - '/dev/urandom not found or is not readable.' - ); - } - - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'memory', // To keep session errors from happening - 'pseudo_random_string_generator' => 'urandom' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\PseudoRandomString\UrandomPseudoRandomStringGenerator', - $fb->getRedirectLoginHelper()->getPseudoRandomStringGenerator() - ); - } - - /** - * @expectedException \InvalidArgumentException - */ public function testSettingAnAccessThatIsNotStringOrAccessTokenThrows() { + $this->expectException(InvalidArgumentException::class); $config = array_merge($this->config, [ 'default_access_token' => 123, ]); @@ -294,12 +181,12 @@ public function testCreatingANewRequestWillDefaultToTheProperConfig() $fb = new Facebook($config); $request = $fb->request('FOO_VERB', '/foo'); - $this->assertEquals('1337', $request->getApp()->getId()); - $this->assertEquals('foo_secret', $request->getApp()->getSecret()); - $this->assertEquals('foo_token', (string)$request->getAccessToken()); - $this->assertEquals('v1337', $request->getGraphVersion()); - $this->assertEquals( - FacebookClient::BASE_GRAPH_URL_BETA, + static::assertEquals('1337', $request->getApplication()->getId()); + static::assertEquals('foo_secret', $request->getApplication()->getSecret()); + static::assertEquals('foo_token', (string)$request->getAccessToken()); + static::assertEquals('v1337', $request->getGraphVersion()); + static::assertEquals( + Client::BASE_GRAPH_URL_BETA, $fb->getClient()->getBaseGraphUrl() ); } @@ -314,16 +201,16 @@ public function testCreatingANewBatchRequestWillDefaultToTheProperConfig() $fb = new Facebook($config); $batchRequest = $fb->newBatchRequest(); - $this->assertEquals('1337', $batchRequest->getApp()->getId()); - $this->assertEquals('foo_secret', $batchRequest->getApp()->getSecret()); - $this->assertEquals('foo_token', (string)$batchRequest->getAccessToken()); - $this->assertEquals('v1337', $batchRequest->getGraphVersion()); - $this->assertEquals( - FacebookClient::BASE_GRAPH_URL_BETA, + static::assertEquals('1337', $batchRequest->getApplication()->getId()); + static::assertEquals('foo_secret', $batchRequest->getApplication()->getSecret()); + static::assertEquals('foo_token', (string)$batchRequest->getAccessToken()); + static::assertEquals('v1337', $batchRequest->getGraphVersion()); + static::assertEquals( + Client::BASE_GRAPH_URL_BETA, $fb->getClient()->getBaseGraphUrl() ); - $this->assertInstanceOf('Facebook\FacebookBatchRequest', $batchRequest); - $this->assertEquals(0, count($batchRequest->getRequests())); + static::assertInstanceOf(BatchRequest::class, $batchRequest); + static::assertCount(0, $batchRequest->getRequests()); } public function testCanInjectCustomHandlers() @@ -332,36 +219,31 @@ public function testCanInjectCustomHandlers() 'http_client_handler' => new FooClientInterface(), 'persistent_data_handler' => new FooPersistentDataInterface(), 'url_detection_handler' => new FooUrlDetectionInterface(), - 'pseudo_random_string_generator' => new FooBarPseudoRandomStringGenerator(), ]); $fb = new Facebook($config); - $this->assertInstanceOf( - 'Facebook\Tests\Fixtures\FooClientInterface', - $fb->getClient()->getHttpClientHandler() + static::assertInstanceOf( + FooClientInterface::class, + $fb->getClient()->getHttpCllient() ); - $this->assertInstanceOf( - 'Facebook\Tests\Fixtures\FooPersistentDataInterface', + static::assertInstanceOf( + FooPersistentDataInterface::class, $fb->getRedirectLoginHelper()->getPersistentDataHandler() ); - $this->assertInstanceOf( - 'Facebook\Tests\Fixtures\FooUrlDetectionInterface', + static::assertInstanceOf( + FooUrlDetectionInterface::class, $fb->getRedirectLoginHelper()->getUrlDetectionHandler() ); - $this->assertInstanceOf( - 'Facebook\Tests\Fixtures\FooBarPseudoRandomStringGenerator', - $fb->getRedirectLoginHelper()->getPseudoRandomStringGenerator() - ); } public function testPaginationReturnsProperResponse() { $config = array_merge($this->config, [ - 'http_client_handler' => new FooClientInterface(), + 'http_client' => new FooClientInterface(), ]); $fb = new Facebook($config); - $request = new FacebookRequest($fb->getApp(), 'foo_token', 'GET'); + $request = new Request($fb->getApplication(), 'foo_token', 'GET'); $graphEdge = new GraphEdge( $request, [], @@ -376,44 +258,42 @@ public function testPaginationReturnsProperResponse() ] ], '/1337/photos', - '\Facebook\GraphNodes\GraphUser' + GraphUser::class ); $nextPage = $fb->next($graphEdge); - $this->assertInstanceOf('Facebook\GraphNodes\GraphEdge', $nextPage); - $this->assertInstanceOf('Facebook\GraphNodes\GraphUser', $nextPage[0]); - $this->assertEquals('Foo', $nextPage[0]['name']); + static::assertInstanceOf(GraphEdge::class, $nextPage); + static::assertInstanceOf(GraphUser::class, $nextPage[0]); + static::assertEquals('Foo', $nextPage[0]['name']); $lastResponse = $fb->getLastResponse(); - $this->assertInstanceOf('Facebook\FacebookResponse', $lastResponse); - $this->assertEquals(1337, $lastResponse->getHttpStatusCode()); + static::assertInstanceOf(Response::class, $lastResponse); + static::assertEquals(1337, $lastResponse->getHttpStatusCode()); } public function testCanGetSuccessfulTransferWithMaxTries() { $config = array_merge($this->config, [ - 'http_client_handler' => new FakeGraphApiForResumableUpload(), + 'http_client' => new FakeGraphApiForResumableUpload(), ]); $fb = new Facebook($config); - $response = $fb->uploadVideo('me', __DIR__.'/foo.txt', [], 'foo-token', 3); - $this->assertEquals([ - 'video_id' => '1337', - 'success' => true, + $response = $fb->uploadVideo('me', __DIR__ . '/foo.txt', [], 'foo-token', 3); + static::assertEquals([ + 'video_id' => '1337', + 'success' => true, ], $response); } - /** - * @expectedException \Facebook\Exceptions\FacebookResponseException - */ - public function testMaxingOutRetriesWillThrow() + public function testMaxingOutRetriesWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookResponseException::class); $client = new FakeGraphApiForResumableUpload(); $client->failOnTransfer(); $config = array_merge($this->config, [ - 'http_client_handler' => $client, + 'http_client' => $client, ]); $fb = new Facebook($config); - $fb->uploadVideo('4', __DIR__.'/foo.txt', [], 'foo-token', 3); + $fb->uploadVideo('4', __DIR__ . '/foo.txt', [], 'foo-token', 3); } } diff --git a/tests/FileUpload/FacebookFileTest.php b/tests/FileUpload/FileTest.php similarity index 71% rename from tests/FileUpload/FacebookFileTest.php rename to tests/FileUpload/FileTest.php index 8ef741708..32e465985 100644 --- a/tests/FileUpload/FacebookFileTest.php +++ b/tests/FileUpload/FileTest.php @@ -23,38 +23,41 @@ */ namespace Facebook\Tests\FileUpload; -use Facebook\FileUpload\FacebookFile; +use Facebook\Exceptions\FacebookSDKException; +use Facebook\FileUpload\File; +use PHPUnit\Framework\TestCase; -class FacebookFileTest extends \PHPUnit_Framework_TestCase +/** + * Class FileTest + */ +class FileTest extends TestCase { - protected $testFile = ''; + protected string $testFile = ''; - protected function setUp() + protected function setUp(): void { $this->testFile = __DIR__ . '/../foo.txt'; } public function testCanOpenAndReadAndCloseAFile() { - $file = new FacebookFile($this->testFile); + $file = new File($this->testFile); $fileContents = $file->getContents(); - $this->assertEquals('This is a text file used for testing. Let\'s dance.', $fileContents); + static::assertEquals('This is a text file used for testing. Let\'s dance.', $fileContents); } public function testPartialFilesCanBeCreated() { - $file = new FacebookFile($this->testFile, 14, 5); + $file = new File($this->testFile, 14, 5); $fileContents = $file->getContents(); - $this->assertEquals('is a text file', $fileContents); + static::assertEquals('is a text file', $fileContents); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testTryingToOpenAFileThatDoesntExistsThrows() { - new FacebookFile('does_not_exist.file'); + $this->expectException(FacebookSDKException::class); + new File('does_not_exist.file'); } } diff --git a/tests/FileUpload/MimetypesTest.php b/tests/FileUpload/MimetypesTest.php index 14fc2b9dd..ec3062bf2 100644 --- a/tests/FileUpload/MimetypesTest.php +++ b/tests/FileUpload/MimetypesTest.php @@ -24,8 +24,12 @@ namespace Facebook\Tests\FileUpload; use Facebook\FileUpload\Mimetypes; +use PHPUnit\Framework\TestCase; -class MimetypesTest extends \PHPUnit_Framework_TestCase +/** + * Class MimetypesTest + */ +class MimetypesTest extends TestCase { /** @@ -35,21 +39,21 @@ class MimetypesTest extends \PHPUnit_Framework_TestCase */ public function testGetsFromExtension() { - $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromExtension('php')); + static::assertEquals('text/x-php', Mimetypes::getInstance()->fromExtension('php')); } public function testGetsFromFilename() { - $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(__FILE__)); + static::assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(__FILE__)); } public function testGetsFromCaseInsensitiveFilename() { - $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(strtoupper(__FILE__))); + static::assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(strtoupper(__FILE__))); } public function testReturnsNullWhenNoMatchFound() { - $this->assertNull(Mimetypes::getInstance()->fromExtension('foobar')); + static::assertNull(Mimetypes::getInstance()->fromExtension('foobar')); } } diff --git a/tests/FileUpload/FacebookResumableUploaderTest.php b/tests/FileUpload/ResumableUploaderTest.php similarity index 55% rename from tests/FileUpload/FacebookResumableUploaderTest.php rename to tests/FileUpload/ResumableUploaderTest.php index dfdbe6f41..16036aac7 100644 --- a/tests/FileUpload/FacebookResumableUploaderTest.php +++ b/tests/FileUpload/ResumableUploaderTest.php @@ -24,67 +24,70 @@ namespace Facebook\Tests\FileUpload; -use Facebook\FileUpload\FacebookFile; -use Facebook\FacebookApp; -use Facebook\FacebookClient; -use Facebook\FileUpload\FacebookResumableUploader; -use Facebook\FileUpload\FacebookTransferChunk; +use Facebook\Exceptions\FacebookResponseException; +use Facebook\FileUpload\File; +use Facebook\Application; +use Facebook\Client; +use Facebook\FileUpload\ResumableUploader; +use Facebook\FileUpload\TransferChunk; use Facebook\Tests\Fixtures\FakeGraphApiForResumableUpload; +use PHPUnit\Framework\TestCase; -class FacebookResumableUploaderTest extends \PHPUnit_Framework_TestCase +/** + * Class ResumableUploaderTest + */ +class ResumableUploaderTest extends TestCase { /** - * @var FacebookApp + * @var Application */ - private $fbApp; + private Application $fbApp; /** - * @var FacebookClient + * @var Client */ - private $client; + private Client $client; /** * @var FakeGraphApiForResumableUpload */ - private $graphApi; + private FakeGraphApiForResumableUpload $graphApi; /** - * @var FacebookFile + * @var File */ - private $file; + private File $file; - protected function setUp() + protected function setUp(): void { - $this->fbApp = new FacebookApp('app_id', 'app_secret'); + $this->fbApp = new Application('app_id', 'app_secret'); $this->graphApi = new FakeGraphApiForResumableUpload(); - $this->client = new FacebookClient($this->graphApi); - $this->file = new FacebookFile(__DIR__.'/../foo.txt'); + $this->client = new Client($this->graphApi); + $this->file = new File(__DIR__ . '/../foo.txt'); } public function testResumableUploadCanStartTransferAndFinish() { - $uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); + $uploader = new ResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); $endpoint = '/me/videos'; $chunk = $uploader->start($endpoint, $this->file); - $this->assertInstanceOf('Facebook\FileUpload\FacebookTransferChunk', $chunk); - $this->assertEquals('42', $chunk->getUploadSessionId()); - $this->assertEquals('1337', $chunk->getVideoId()); + static::assertInstanceOf(TransferChunk::class, $chunk); + static::assertEquals('42', $chunk->getUploadSessionId()); + static::assertEquals('1337', $chunk->getVideoId()); $newChunk = $uploader->transfer($endpoint, $chunk); - $this->assertEquals(20, $newChunk->getStartOffset()); - $this->assertNotSame($newChunk, $chunk); + static::assertEquals(20, $newChunk->getStartOffset()); + static::assertNotSame($newChunk, $chunk); $finalResponse = $uploader->finish($endpoint, $chunk->getUploadSessionId(), []); - $this->assertTrue($finalResponse); + static::assertTrue($finalResponse); } - /** - * @expectedException \Facebook\Exceptions\FacebookResponseException - */ public function testStartWillLetErrorResponsesThrow() { + $this->expectException(FacebookResponseException::class); $this->graphApi->failOnStart(); - $uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); + $uploader = new ResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); $uploader->start('/me/videos', $this->file); } @@ -92,21 +95,21 @@ public function testStartWillLetErrorResponsesThrow() public function testFailedResumableTransferWillNotThrowAndReturnSameChunk() { $this->graphApi->failOnTransfer(); - $uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); + $uploader = new ResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); - $chunk = new FacebookTransferChunk($this->file, '1', '2', '3', '4'); + $chunk = new TransferChunk($this->file, '1', '2', '3', '4'); $newChunk = $uploader->transfer('/me/videos', $chunk); - $this->assertSame($newChunk, $chunk); + static::assertSame($newChunk, $chunk); } public function testFailedResumableTransferWillNotThrowAndReturnNewChunk() { $this->graphApi->failOnTransferAndUploadNewChunk(); - $uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); + $uploader = new ResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4'); - $chunk = new FacebookTransferChunk($this->file, '1', '2', '3', '4'); + $chunk = new TransferChunk($this->file, '1', '2', '3', '4'); $newChunk = $uploader->transfer('/me/videos', $chunk); - $this->assertEquals(40, $newChunk->getStartOffset()); - $this->assertEquals(50, $newChunk->getEndOffset()); + static::assertEquals(40, $newChunk->getStartOffset()); + static::assertEquals(50, $newChunk->getEndOffset()); } } diff --git a/tests/Fixtures/FakeGraphApiForResumableUpload.php b/tests/Fixtures/FakeGraphApiForResumableUpload.php index 29f56446c..ae841597a 100644 --- a/tests/Fixtures/FakeGraphApiForResumableUpload.php +++ b/tests/Fixtures/FakeGraphApiForResumableUpload.php @@ -1,4 +1,6 @@ respondWith = 'FAIL_ON_TRANSFER_AND_UPLOAD_NEW_CHUNK'; } - public function send($url, $method, $body, array $headers, $timeOut) + /** + * Send an HTTP request. + * + * @param RequestInterface $request Request to send + * @param array $options + * + * @return \Psr\Http\Message\ResponseInterface + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface { + $body = $request->getBody()->__toString(); // Could be start, transfer or finish - if (strpos($body, 'transfer') !== false) { + if (str_contains($body, 'transfer')) { return $this->respondTransfer(); - } elseif (strpos($body, 'finish') !== false) { + } elseif (str_contains($body, 'finish')) { return $this->respondFinish(); } return $this->respondStart(); } - private function respondStart() + private function respondStart(): Response { if ($this->respondWith == 'FAIL_ON_START') { - return new GraphRawResponse( - "HTTP/1.1 500 OK\r\nFoo: Bar", + return new Response( + 200, + ['Foo' => 'Bar'], '{"error":{"message":"Error validating access token: Session has expired on Monday, ' . '10-Aug-15 01:00:00 PDT. The current time is Monday, 10-Aug-15 01:14:23 PDT.",' . '"type":"OAuthException","code":190,"error_subcode":463}}' ); } - return new GraphRawResponse( - "HTTP/1.1 200 OK\r\nFoo: Bar", + return new Response( + 200, + ['Foo' => 'Bar'], '{"video_id":"1337","start_offset":"0","end_offset":"20","upload_session_id":"42"}' ); } - private function respondTransfer() + private function respondTransfer(): Response { if ($this->respondWith == 'FAIL_ON_TRANSFER') { - return new GraphRawResponse( - "HTTP/1.1 500 OK\r\nFoo: Bar", - '{"error":{"message":"There was a problem uploading your video. Please try uploading it again.",' . - '"type":"FacebookApiException","code":6000,"error_subcode":1363019}}' - ); - } - - if ($this->respondWith == 'FAIL_ON_TRANSFER_AND_UPLOAD_NEW_CHUNK') { - return new GraphRawResponse( - "HTTP/1.1 500 OK\r\nFoo: Bar", + return new Response( + 500, + ['Foo' => 'Bar'], '{"error":{"message":"There was a problem uploading your video. Please try uploading it again.",' . - '"type":"OAuthException","code":6001,"error_subcode":1363037,' . - '"error_data":{"start_offset":40,"end_offset":50}}}' + '"type":"ApiException","code":6000,"error_subcode":1363019}}', ); } - switch ($this->transferCount) { - case 0: - $data = ['start_offset' => 20, 'end_offset' => 40]; - break; - case 1: - $data = ['start_offset' => 40, 'end_offset' => 50]; - break; - default: - $data = ['start_offset' => 50, 'end_offset' => 50]; - break; - } + $data = match ($this->transferCount) { + 0 => ['start_offset' => 20, 'end_offset' => 40], + 1 => ['start_offset' => 40, 'end_offset' => 50], + default => ['start_offset' => 50, 'end_offset' => 50], + }; $this->transferCount++; - return new GraphRawResponse( - "HTTP/1.1 200 OK\r\nFoo: Bar", - json_encode($data) - ); + return new Response(200, ['Foo' => 'Bar'], json_encode($data)); } - private function respondFinish() + private function respondFinish(): Response { - return new GraphRawResponse( - "HTTP/1.1 200 OK\r\nFoo: Bar", - '{"success":true}' - ); + return new Response(500, ['Foo' => 'Bar'], '{"success":true}'); } } diff --git a/tests/Fixtures/FooBarPseudoRandomStringGenerator.php b/tests/Fixtures/FooBarPseudoRandomStringGenerator.php deleted file mode 100644 index 17448b6eb..000000000 --- a/tests/Fixtures/FooBarPseudoRandomStringGenerator.php +++ /dev/null @@ -1,34 +0,0 @@ - 'Mon, 19 May 2014 18:37:17 GMT'], + '{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', + '1.1', + 'OK', ); } } diff --git a/tests/Fixtures/FooPersistentDataInterface.php b/tests/Fixtures/FooPersistentDataInterface.php index 5ff57938b..ce380c0e1 100644 --- a/tests/Fixtures/FooPersistentDataInterface.php +++ b/tests/Fixtures/FooPersistentDataInterface.php @@ -1,4 +1,6 @@ getParams(); $rawResponse = json_encode([ 'access_token' => 'foo_access_token_from:' . $params['code'], ]); - return new FacebookResponse($request, $rawResponse, 200); + return new Response($request, $rawResponse, 200); } } diff --git a/tests/Fixtures/FooUrlDetectionInterface.php b/tests/Fixtures/FooUrlDetectionInterface.php index 8ee70c303..df03d602d 100644 --- a/tests/Fixtures/FooUrlDetectionInterface.php +++ b/tests/Fixtures/FooUrlDetectionInterface.php @@ -1,4 +1,6 @@ 'Mon, 19 May 2014 18:37:17 GMT'], + '[{"code":"123","body":"Foo"},{"code":"1337","body":"Bar"}]', ); } } diff --git a/tests/Fixtures/MyFooClientHandler.php b/tests/Fixtures/MyFooClientHandler.php index 346da9e1e..5e3eb35ca 100644 --- a/tests/Fixtures/MyFooClientHandler.php +++ b/tests/Fixtures/MyFooClientHandler.php @@ -1,4 +1,6 @@ 'Mon, 19 May 2014 18:37:17 GMT'], + '{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', ); } } diff --git a/tests/Fixtures/MyFooGraphNode.php b/tests/Fixtures/MyFooGraphNode.php index 40d3a9145..f02c9778c 100644 --- a/tests/Fixtures/MyFooGraphNode.php +++ b/tests/Fixtures/MyFooGraphNode.php @@ -1,4 +1,6 @@ '\Facebook\Tests\Fixtures\MyFooSubClassGraphNode', + protected static array $graphNodeMap = [ + 'foo_object' => MyFooSubClassGraphNode::class, ]; } diff --git a/tests/Fixtures/MyFooSubClassGraphNode.php b/tests/Fixtures/MyFooSubClassGraphNode.php index d03b308b8..a1448f79b 100644 --- a/tests/Fixtures/MyFooSubClassGraphNode.php +++ b/tests/Fixtures/MyFooSubClassGraphNode.php @@ -1,4 +1,6 @@ responseMock = m::mock('\Facebook\FacebookResponse'); + $this->responseMock = $this->prophesize(Response::class); } - protected function makeFactoryWithData($data) + /** + * @param $data + * + * @return \Facebook\GraphNodes\GraphNodeFactory + */ + protected function makeFactoryWithData($data): GraphNodeFactory { - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($data); + $this->responseMock->getDecodedBody()->willReturn($data); - return new GraphNodeFactory($this->responseMock); + return new GraphNodeFactory($this->responseMock->reveal()); } } diff --git a/tests/GraphNodes/CollectionTest.php b/tests/GraphNodes/CollectionTest.php index 14af47684..a4f798206 100755 --- a/tests/GraphNodes/CollectionTest.php +++ b/tests/GraphNodes/CollectionTest.php @@ -1,4 +1,6 @@ 'bar']); $field = $graphNode->getField('foo'); - $this->assertEquals('bar', $field); - - // @todo v6: Remove this assertion - $property = $graphNode->getProperty('foo'); - $this->assertEquals('bar', $property); + static::assertEquals('bar', $field); } public function testAMissingPropertyWillReturnNull() @@ -45,7 +47,7 @@ public function testAMissingPropertyWillReturnNull() $graphNode = new Collection(['foo' => 'bar']); $field = $graphNode->getField('baz'); - $this->assertNull($field, 'Expected the property to return null.'); + static::assertNull($field, 'Expected the property to return null.'); } public function testAMissingPropertyWillReturnTheDefault() @@ -53,11 +55,7 @@ public function testAMissingPropertyWillReturnTheDefault() $graphNode = new Collection(['foo' => 'bar']); $field = $graphNode->getField('baz', 'faz'); - $this->assertEquals('faz', $field); - - // @todo v6: Remove this assertion - $property = $graphNode->getProperty('baz', 'faz'); - $this->assertEquals('faz', $property); + static::assertEquals('faz', $field); } public function testFalseDefaultsWillReturnSameType() @@ -65,13 +63,13 @@ public function testFalseDefaultsWillReturnSameType() $graphNode = new Collection(['foo' => 'bar']); $field = $graphNode->getField('baz', ''); - $this->assertSame('', $field); + static::assertSame('', $field); $field = $graphNode->getField('baz', 0); - $this->assertSame(0, $field); + static::assertSame(0, $field); $field = $graphNode->getField('baz', false); - $this->assertSame(false, $field); + static::assertSame(false, $field); } public function testTheKeysFromTheCollectionCanBeReturned() @@ -83,17 +81,13 @@ public function testTheKeysFromTheCollectionCanBeReturned() ]); $fieldNames = $graphNode->getFieldNames(); - $this->assertEquals(['key1', 'key2', 'key3'], $fieldNames); - - // @todo v6: Remove this assertion - $propertyNames = $graphNode->getPropertyNames(); - $this->assertEquals(['key1', 'key2', 'key3'], $propertyNames); + static::assertEquals(['key1', 'key2', 'key3'], $fieldNames); } public function testAnArrayCanBeInjectedViaTheConstructor() { $collection = new Collection(['foo', 'bar']); - $this->assertEquals(['foo', 'bar'], $collection->asArray()); + static::assertEquals(['foo', 'bar'], $collection->asArray()); } public function testACollectionCanBeConvertedToProperJson() @@ -102,7 +96,7 @@ public function testACollectionCanBeConvertedToProperJson() $collectionAsString = $collection->asJson(); - $this->assertEquals('["foo","bar",123]', $collectionAsString); + static::assertEquals('["foo","bar",123]', $collectionAsString); } public function testACollectionCanBeCounted() @@ -111,22 +105,22 @@ public function testACollectionCanBeCounted() $collectionCount = count($collection); - $this->assertEquals(3, $collectionCount); + static::assertEquals(3, $collectionCount); } public function testACollectionCanBeAccessedAsAnArray() { $collection = new Collection(['foo' => 'bar', 'faz' => 'baz']); - $this->assertEquals('bar', $collection['foo']); - $this->assertEquals('baz', $collection['faz']); + static::assertEquals('bar', $collection['foo']); + static::assertEquals('baz', $collection['faz']); } public function testACollectionCanBeIteratedOver() { $collection = new Collection(['foo' => 'bar', 'faz' => 'baz']); - $this->assertInstanceOf('IteratorAggregate', $collection); + static::assertInstanceOf('IteratorAggregate', $collection); $newArray = []; @@ -134,6 +128,6 @@ public function testACollectionCanBeIteratedOver() $newArray[$k] = $v; } - $this->assertEquals(['foo' => 'bar', 'faz' => 'baz'], $newArray); + static::assertEquals(['foo' => 'bar', 'faz' => 'baz'], $newArray); } } diff --git a/tests/GraphNodes/GraphAchievementTest.php b/tests/GraphNodes/GraphAchievementTest.php index 5be1140fd..78e0da521 100644 --- a/tests/GraphNodes/GraphAchievementTest.php +++ b/tests/GraphNodes/GraphAchievementTest.php @@ -1,4 +1,6 @@ getId(); - $this->assertEquals($dataFromGraph['id'], $id); + static::assertEquals($dataFromGraph['id'], $id); } public function testTypeIsAlwaysString() @@ -51,7 +59,7 @@ public function testTypeIsAlwaysString() $type = $graphNode->getType(); - $this->assertEquals('game.achievement', $type); + static::assertEquals('game.achievement', $type); } public function testNoFeedStoryIsBoolean() @@ -65,7 +73,7 @@ public function testNoFeedStoryIsBoolean() $isNoFeedStory = $graphNode->isNoFeedStory(); - $this->assertTrue(is_bool($isNoFeedStory)); + static::assertTrue(is_bool($isNoFeedStory)); } public function testDatesGetCastToDateTime() @@ -79,7 +87,7 @@ public function testDatesGetCastToDateTime() $publishTime = $graphNode->getPublishTime(); - $this->assertInstanceOf('DateTime', $publishTime); + static::assertInstanceOf('DateTime', $publishTime); } public function testFromGetsCastAsGraphUser() @@ -96,7 +104,7 @@ public function testFromGetsCastAsGraphUser() $from = $graphNode->getFrom(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphUser', $from); + static::assertInstanceOf(GraphNode::class, $from); } public function testApplicationGetsCastAsGraphApplication() @@ -112,6 +120,6 @@ public function testApplicationGetsCastAsGraphApplication() $app = $graphNode->getApplication(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphApplication', $app); + static::assertInstanceOf(GraphNode::class, $app); } } diff --git a/tests/GraphNodes/GraphAlbumTest.php b/tests/GraphNodes/GraphAlbumTest.php index 0c4eab5ef..769c7d4e2 100644 --- a/tests/GraphNodes/GraphAlbumTest.php +++ b/tests/GraphNodes/GraphAlbumTest.php @@ -1,4 +1,6 @@ responseMock = m::mock('\\Facebook\\FacebookResponse'); + parent::setUp(); + $this->responseMock = $this->prophesize(Response::class); } public function testDatesGetCastToDateTime() @@ -48,18 +61,15 @@ public function testDatesGetCastToDateTime() 'name' => 'Bar', ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphNode = $factory->makeGraphAlbum(); $createdTime = $graphNode->getCreatedTime(); $updatedTime = $graphNode->getUpdatedTime(); - $this->assertInstanceOf('DateTime', $createdTime); - $this->assertInstanceOf('DateTime', $updatedTime); + static::assertInstanceOf('DateTime', $createdTime); + static::assertInstanceOf('DateTime', $updatedTime); } public function testFromGetsCastAsGraphUser() @@ -72,16 +82,13 @@ public function testFromGetsCastAsGraphUser() ], ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphNode = $factory->makeGraphAlbum(); $from = $graphNode->getFrom(); - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphUser', $from); + static::assertInstanceOf(GraphNode::class, $from); } public function testPlacePropertyWillGetCastAsGraphPageObject() @@ -95,15 +102,12 @@ public function testPlacePropertyWillGetCastAsGraphPageObject() ] ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphNode = $factory->makeGraphAlbum(); $place = $graphNode->getPlace(); - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPage', $place); + static::assertInstanceOf(GraphNode::class, $place); } } diff --git a/tests/GraphNodes/GraphEdgeTest.php b/tests/GraphNodes/GraphEdgeTest.php index 3afaf9cfb..eb96080d4 100644 --- a/tests/GraphNodes/GraphEdgeTest.php +++ b/tests/GraphNodes/GraphEdgeTest.php @@ -1,4 +1,6 @@ 'https://graph.facebook.com/v7.12/998899/photos?pretty=0&limit=25&after=foo_after_cursor', 'previous' => 'https://graph.facebook.com/v7.12/998899/photos?pretty=0&limit=25&before=foo_before_cursor', ]; - protected function setUp() + protected function setUp(): void { - $app = new FacebookApp('123', 'foo_app_secret'); - $this->request = new FacebookRequest( + $app = new Application('123', 'foo_app_secret'); + $this->request = new Request( $app, 'foo_token', 'GET', @@ -55,17 +61,15 @@ protected function setUp() ); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testNonGetRequestsWillThrow() + public function testNonGetRequestsWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); $this->request->setMethod('POST'); $graphEdge = new GraphEdge($this->request); $graphEdge->validateForPagination(); } - public function testCanReturnGraphGeneratedPaginationEndpoints() + public function testCanReturnGraphGeneratedPaginationEndpoints(): void { $graphEdge = new GraphEdge( $this->request, @@ -75,11 +79,11 @@ public function testCanReturnGraphGeneratedPaginationEndpoints() $nextPage = $graphEdge->getPaginationUrl('next'); $prevPage = $graphEdge->getPaginationUrl('previous'); - $this->assertEquals('/998899/photos?pretty=0&limit=25&after=foo_after_cursor', $nextPage); - $this->assertEquals('/998899/photos?pretty=0&limit=25&before=foo_before_cursor', $prevPage); + static::assertEquals('/998899/photos?pretty=0&limit=25&after=foo_after_cursor', $nextPage); + static::assertEquals('/998899/photos?pretty=0&limit=25&before=foo_before_cursor', $prevPage); } - public function testCanInstantiateNewPaginationRequest() + public function testCanInstantiateNewPaginationRequest(): void { $graphEdge = new GraphEdge( $this->request, @@ -90,41 +94,142 @@ public function testCanInstantiateNewPaginationRequest() $nextPage = $graphEdge->getNextPageRequest(); $prevPage = $graphEdge->getPreviousPageRequest(); - $this->assertInstanceOf('Facebook\FacebookRequest', $nextPage); - $this->assertInstanceOf('Facebook\FacebookRequest', $prevPage); - $this->assertNotSame($this->request, $nextPage); - $this->assertNotSame($this->request, $prevPage); - $this->assertEquals('/v1337/998899/photos?access_token=foo_token&after=foo_after_cursor&appsecret_proof=857d5f035a894f16b4180f19966e055cdeab92d4d53017b13dccd6d43b6497af&foo=bar&limit=25&pretty=0', $nextPage->getUrl()); - $this->assertEquals('/v1337/998899/photos?access_token=foo_token&appsecret_proof=857d5f035a894f16b4180f19966e055cdeab92d4d53017b13dccd6d43b6497af&before=foo_before_cursor&foo=bar&limit=25&pretty=0', $prevPage->getUrl()); + static::assertInstanceOf(Request::class, $nextPage); + static::assertInstanceOf(Request::class, $prevPage); + static::assertNotSame($this->request, $nextPage); + static::assertNotSame($this->request, $prevPage); + static::assertEquals('/v1337/998899/photos?access_token=foo_token&after=foo_after_cursor&appsecret_proof=857d5f035a894f16b4180f19966e055cdeab92d4d53017b13dccd6d43b6497af&foo=bar&limit=25&pretty=0', $nextPage->getUrl()); + static::assertEquals('/v1337/998899/photos?access_token=foo_token&appsecret_proof=857d5f035a894f16b4180f19966e055cdeab92d4d53017b13dccd6d43b6497af&before=foo_before_cursor&foo=bar&limit=25&pretty=0', $prevPage->getUrl()); } - public function testCanMapOverNodes() + public function testCanMapOverNodes(): void { $graphEdge = new GraphEdge( $this->request, [ - new GraphNode(['name' => 'dummy']), - new GraphNode(['name' => 'dummy']), + new GraphNode(['name' => 'dummy1']), + new GraphNode(['name' => 'dummy2']), ], ['paging' => $this->pagination], - '/1234567890/likes' + '/1234567890/likes', ); - $graphEdge = $graphEdge->map(function (GraphNode $node) { - $node['name'] = str_replace('dummy', 'foo', $node['name']); - return $node; + $output = ''; + + $graphEdge->map(function (GraphNode $node) use (&$output) { + $output .= $node->getField('name'); }); - $graphEdgeToCompare = new GraphEdge( + static::assertEquals('dummy1dummy2', $output); + } + + + public function testAnExistingPropertyCanBeAccessed(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar']); + + $field = $graphEdge->getField('foo'); + static::assertEquals('bar', $field); + } + + + public function testAMissingPropertyWillReturnNull(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar']); + $field = $graphEdge->getField('baz'); + + static::assertNull($field, 'Expected the property to return null.'); + } + + + public function testAMissingPropertyWillReturnTheDefault(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar']); + + $field = $graphEdge->getField('baz', 'faz'); + static::assertEquals('faz', $field); + } + + + public function testFalseDefaultsWillReturnSameType(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar']); + + $field = $graphEdge->getField('baz', ''); + static::assertSame('', $field); + + $field = $graphEdge->getField('baz', 0); + static::assertSame(0, $field); + + $field = $graphEdge->getField('baz', false); + static::assertFalse($field); + } + + + public function testTheKeysFromTheCollectionCanBeReturned(): void + { + $graphEdge = new GraphEdge( $this->request, [ - new GraphNode(['name' => 'foo']), - new GraphNode(['name' => 'foo']) + 'key1' => 'foo', + 'key2' => 'bar', + 'key3' => 'baz', ], - ['paging' => $this->pagination], - '/1234567890/likes' ); - $this->assertEquals($graphEdgeToCompare, $graphEdge); + $fieldNames = $graphEdge->getFieldNames(); + static::assertEquals(['key1', 'key2', 'key3'], $fieldNames); + } + + + public function testAnArrayCanBeInjectedViaTheConstructor(): void + { + $graphEdge = new GraphEdge($this->request, ['foo', 'bar']); + static::assertEquals(['foo', 'bar'], $graphEdge->asArray()); + } + + + public function testACollectionCanBeConvertedToProperJson(): void + { + $graphEdge = new GraphEdge($this->request, ['foo', 'bar', 123]); + + $graphEdgeAsString = $graphEdge->asJson(); + + static::assertEquals('["foo","bar",123]', $graphEdgeAsString); + } + + + public function testACollectionCanBeCounted(): void + { + $graphEdge = new GraphEdge($this->request, ['foo', 'bar', 'baz']); + + $graphEdgeCount = count($graphEdge); + + static::assertEquals(3, $graphEdgeCount); + } + + + public function testACollectionCanBeAccessedAsAnArray(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar', 'faz' => 'baz']); + + static::assertEquals('bar', $graphEdge['foo']); + static::assertEquals('baz', $graphEdge['faz']); + } + + + public function testACollectionCanBeIteratedOver(): void + { + $graphEdge = new GraphEdge($this->request, ['foo' => 'bar', 'faz' => 'baz']); + + static::assertInstanceOf(\IteratorAggregate::class, $graphEdge); + + $newArray = []; + + foreach ($graphEdge as $k => $v) { + $newArray[$k] = $v; + } + + static::assertEquals(['foo' => 'bar', 'faz' => 'baz'], $newArray); } } diff --git a/tests/GraphNodes/GraphEventTest.php b/tests/GraphNodes/GraphEventTest.php index 7c6f12708..bd62286ec 100644 --- a/tests/GraphNodes/GraphEventTest.php +++ b/tests/GraphNodes/GraphEventTest.php @@ -1,4 +1,6 @@ responseMock = m::mock('\Facebook\FacebookResponse'); + parent::setUp(); + $this->responseMock = $this->prophesize(Response::class); } - public function testCoverGetsCastAsGraphCoverPhoto() + public function testCoverGetsCastAsGraphCoverPhoto(): void { $dataFromGraph = [ 'cover' => ['id' => '1337'] ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphObject = $factory->makeGraphEvent(); $cover = $graphObject->getCover(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphCoverPhoto', $cover); + static::assertInstanceOf(GraphNode::class, $cover); } - public function testPlaceGetsCastAsGraphPage() + public function testPlaceGetsCastAsGraphPage(): void { $dataFromGraph = [ 'place' => ['id' => '1337'] ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphObject = $factory->makeGraphEvent(); $place = $graphObject->getPlace(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphPage', $place); + static::assertInstanceOf(GraphNode::class, $place); } - public function testPictureGetsCastAsGraphPicture() + public function testPictureGetsCastAsGraphPicture(): void { $dataFromGraph = [ 'picture' => ['id' => '1337'] ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphObject = $factory->makeGraphEvent(); $picture = $graphObject->getPicture(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphPicture', $picture); + static::assertInstanceOf(GraphNode::class, $picture); } - public function testParentGroupGetsCastAsGraphGroup() + public function testParentGroupGetsCastAsGraphGroup(): void { $dataFromGraph = [ 'parent_group' => ['id' => '1337'] ]; - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); + $this->responseMock->getDecodedBody()->willReturn($dataFromGraph); + $factory = new GraphNodeFactory($this->responseMock->reveal()); $graphObject = $factory->makeGraphEvent(); $parentGroup = $graphObject->getParentGroup(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphGroup', $parentGroup); + static::assertInstanceOf(GraphNode::class, $parentGroup); } } diff --git a/tests/GraphNodes/GraphGroupTest.php b/tests/GraphNodes/GraphGroupTest.php deleted file mode 100644 index c62d50fb0..000000000 --- a/tests/GraphNodes/GraphGroupTest.php +++ /dev/null @@ -1,75 +0,0 @@ -responseMock = m::mock('\Facebook\FacebookResponse'); - } - - public function testCoverGetsCastAsGraphCoverPhoto() - { - $dataFromGraph = [ - 'cover' => ['id' => '1337'] - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphGroup(); - - $cover = $graphNode->getCover(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphCoverPhoto', $cover); - } - - public function testVenueGetsCastAsGraphLocation() - { - $dataFromGraph = [ - 'venue' => ['id' => '1337'] - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphGroup(); - - $venue = $graphNode->getVenue(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphLocation', $venue); - } -} diff --git a/tests/GraphNodes/GraphNodeFactoryTest.php b/tests/GraphNodes/GraphNodeFactoryTest.php index 5772c0ad5..273edcebe 100644 --- a/tests/GraphNodes/GraphNodeFactoryTest.php +++ b/tests/GraphNodes/GraphNodeFactoryTest.php @@ -1,4 +1,6 @@ request = new FacebookRequest( + $app = new Application('123', 'foo_app_secret'); + $this->request = new Request( $app, 'foo_token', 'GET', @@ -49,99 +61,98 @@ protected function setUp() ); } - public function testAValidGraphNodeResponseWillNotThrow() + public function testAValidGraphNodeResponseWillNotThrow(): void { $data = '{"id":"123","name":"foo"}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $factory->validateResponseCastableAsGraphNode(); + + static::assertTrue(true); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testANonGraphNodeResponseWillThrow() + public function testANonGraphNodeResponseWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); $data = '{"data":[{"id":"123","name":"foo"},{"id":"1337","name":"bar"}]}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $factory->validateResponseCastableAsGraphNode(); } - public function testAValidGraphEdgeResponseWillNotThrow() + public function testAValidGraphEdgeResponseWillNotThrow(): void { $data = '{"data":[{"id":"123","name":"foo"},{"id":"1337","name":"bar"}]}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $factory->validateResponseCastableAsGraphEdge(); + + static::assertTrue(true); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testANonGraphEdgeResponseWillThrow() + public function testANonGraphEdgeResponseWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); $data = '{"id":"123","name":"foo"}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $factory->validateResponseCastableAsGraphEdge(); } - public function testOnlyNumericArraysAreCastableAsAGraphEdge() + public function testOnlyNumericArraysAreCastableAsAGraphEdge(): void { $shouldPassOne = GraphNodeFactory::isCastableAsGraphEdge([]); $shouldPassTwo = GraphNodeFactory::isCastableAsGraphEdge(['foo', 'bar']); $shouldFail = GraphNodeFactory::isCastableAsGraphEdge(['faz' => 'baz']); - $this->assertTrue($shouldPassOne, 'Expected the given array to be castable as a GraphEdge.'); - $this->assertTrue($shouldPassTwo, 'Expected the given array to be castable as a GraphEdge.'); - $this->assertFalse($shouldFail, 'Expected the given array to not be castable as a GraphEdge.'); + static::assertTrue($shouldPassOne, 'Expected the given array to be castable as a GraphEdge.'); + static::assertTrue($shouldPassTwo, 'Expected the given array to be castable as a GraphEdge.'); + static::assertFalse($shouldFail, 'Expected the given array to not be castable as a GraphEdge.'); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testInvalidSubClassesWillThrow() + public function testInvalidSubClassesWillThrow(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); GraphNodeFactory::validateSubclass('FooSubClass'); } - public function testValidSubClassesWillNotThrow() + public function testValidSubClassesWillNotThrow(): void { - GraphNodeFactory::validateSubclass('\Facebook\GraphNodes\GraphNode'); - GraphNodeFactory::validateSubclass('\Facebook\GraphNodes\GraphAlbum'); - GraphNodeFactory::validateSubclass('\Facebook\Tests\Fixtures\MyFooGraphNode'); + GraphNodeFactory::validateSubclass(GraphNode::class); + GraphNodeFactory::validateSubclass(GraphAlbum::class); + GraphNodeFactory::validateSubclass(MyFooGraphNode::class); + static::assertTrue(true); } - public function testCastingAsASubClassObjectWillInstantiateTheSubClass() + public function testCastingAsASubClassObjectWillInstantiateTheSubClass(): void { $data = '{"id":"123","name":"foo"}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); - $mySubClassObject = $factory->makeGraphNode('\Facebook\Tests\Fixtures\MyFooGraphNode'); + $mySubClassObject = $factory->makeGraphNode(MyFooGraphNode::class); - $this->assertInstanceOf('\Facebook\Tests\Fixtures\MyFooGraphNode', $mySubClassObject); + static::assertInstanceOf(MyFooGraphNode::class, $mySubClassObject); } - public function testASubClassMappingWillAutomaticallyInstantiateSubClass() + public function testASubClassMappingWillAutomaticallyInstantiateSubClass(): void { $data = '{"id":"123","name":"Foo Name","foo_object":{"id":"1337","name":"Should be sub classed!"}}'; - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); - $mySubClassObject = $factory->makeGraphNode('\Facebook\Tests\Fixtures\MyFooGraphNode'); + $mySubClassObject = $factory->makeGraphNode(MyFooGraphNode::class); $fooObject = $mySubClassObject->getField('foo_object'); - $this->assertInstanceOf('\Facebook\Tests\Fixtures\MyFooGraphNode', $mySubClassObject); - $this->assertInstanceOf('\Facebook\Tests\Fixtures\MyFooSubClassGraphNode', $fooObject); + static::assertInstanceOf(MyFooGraphNode::class, $mySubClassObject); + static::assertInstanceOf(MyFooSubClassGraphNode::class, $fooObject); } - public function testAnUnknownGraphNodeWillBeCastAsAGenericGraphNode() + public function testAnUnknownGraphNodeWillBeCastAsAGenericGraphNode(): void { $data = json_encode([ 'id' => '123', @@ -151,19 +162,19 @@ public function testAnUnknownGraphNodeWillBeCastAsAGenericGraphNode() 'name' => 'Should be generic!', ], ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); - $mySubClassObject = $factory->makeGraphNode('\Facebook\Tests\Fixtures\MyFooGraphNode'); + $mySubClassObject = $factory->makeGraphNode(MyFooGraphNode::class); $unknownObject = $mySubClassObject->getField('unknown_object'); - $this->assertInstanceOf('\Facebook\Tests\Fixtures\MyFooGraphNode', $mySubClassObject); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $unknownObject); - $this->assertNotInstanceOf('\Facebook\Tests\Fixtures\MyFooGraphNode', $unknownObject); + static::assertInstanceOf(MyFooGraphNode::class, $mySubClassObject); + static::assertInstanceOf(GraphNode::class, $unknownObject); + static::assertNotInstanceOf(MyFooGraphNode::class, $unknownObject); } - public function testAListFromGraphWillBeCastAsAGraphEdge() + public function testAListFromGraphWillBeCastAsAGraphEdge(): void { $data = json_encode([ 'data' => [ @@ -183,47 +194,46 @@ public function testAListFromGraphWillBeCastAsAGraphEdge() 'previous' => 'http://facebook/prev', ], ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphEdge = $factory->makeGraphEdge(); $graphData = $graphEdge->asArray(); - - $this->assertInstanceOf('\Facebook\GraphNodes\GraphEdge', $graphEdge); - $this->assertEquals([ + static::assertInstanceOf(GraphEdge::class, $graphEdge); + static::assertEquals([ 'id' => '123', 'name' => 'Foo McBar', 'link' => 'http://facebook/foo', - ], $graphData[0]); - $this->assertEquals([ + ], $graphData[0]->getFields()); + static::assertEquals([ 'id' => '1337', 'name' => 'Bar McBaz', 'link' => 'http://facebook/bar', - ], $graphData[1]); + ], $graphData[1]->getFields()); } - public function testAGraphNodeWillBeCastAsAGraphNode() + public function testAGraphNodeWillBeCastAsAGraphNode(): void { $data = json_encode([ 'id' => '123', 'name' => 'Foo McBar', 'link' => 'http://facebook/foo', ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphNode = $factory->makeGraphNode(); $graphData = $graphNode->asArray(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $graphNode); - $this->assertEquals([ + static::assertInstanceOf(GraphNode::class, $graphNode); + static::assertEquals([ 'id' => '123', 'name' => 'Foo McBar', 'link' => 'http://facebook/foo', ], $graphData); } - public function testAGraphNodeWithARootDataKeyWillBeCastAsAGraphNode() + public function testAGraphNodeWithARootDataKeyWillBeCastAsAGraphNode(): void { $data = json_encode([ 'data' => [ @@ -233,21 +243,21 @@ public function testAGraphNodeWithARootDataKeyWillBeCastAsAGraphNode() ], ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphNode = $factory->makeGraphNode(); $graphData = $graphNode->asArray(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $graphNode); - $this->assertEquals([ + static::assertInstanceOf(GraphNode::class, $graphNode); + static::assertEquals([ 'id' => '123', 'name' => 'Foo McBar', 'link' => 'http://facebook/foo', ], $graphData); } - public function testAGraphNodeWithARootDataKeyWillConserveRootKeys() + public function testAGraphNodeWithARootDataKeyWillConserveRootKeys(): void { $data = json_encode([ 'id' => '123', @@ -258,15 +268,15 @@ public function testAGraphNodeWithARootDataKeyWillConserveRootKeys() ], ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphNode = $factory->makeGraphNode(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $graphNode); + static::assertInstanceOf(GraphNode::class, $graphNode); $graphData = $graphNode->asArray(); - $this->assertEquals([ + static::assertEquals([ 'id' => '123', 'foo' => 'bar', 'name' => 'Foo McBar', @@ -274,7 +284,7 @@ public function testAGraphNodeWithARootDataKeyWillConserveRootKeys() ], $graphData); } - public function testAGraphEdgeWillBeCastRecursively() + public function testAGraphEdgeWillBeCastRecursively(): void { $someUser = [ 'id' => '123', @@ -356,31 +366,31 @@ public function testAGraphEdgeWillBeCastRecursively() ], ]; $data = json_encode($dataFromGraph); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphNode = $factory->makeGraphEdge(); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphEdge', $graphNode); + static::assertInstanceOf(GraphEdge::class, $graphNode); // Story $storyObject = $graphNode[0]; - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $storyObject['from']); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphEdge', $storyObject['likes']); - $this->assertInstanceOf('\Facebook\GraphNodes\GraphEdge', $storyObject['comments']); + static::assertInstanceOf(GraphNode::class, $storyObject->getField('from')); + static::assertInstanceOf(GraphEdge::class, $storyObject->getField('likes')); + static::assertInstanceOf(GraphEdge::class, $storyObject->getField('comments')); // Story Comments - $storyComments = $storyObject['comments']; + $storyComments = $storyObject->getField('comments'); $firstStoryComment = $storyComments[0]; - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $firstStoryComment['from']); + static::assertInstanceOf(GraphNode::class, $firstStoryComment->getField('from')); // Message $messageObject = $graphNode[1]; - $this->assertInstanceOf('\Facebook\GraphNodes\GraphEdge', $messageObject['to']); - $toUsers = $messageObject['to']; - $this->assertInstanceOf('\Facebook\GraphNodes\GraphNode', $toUsers[0]); + static::assertInstanceOf(GraphEdge::class, $messageObject->getField('to')); + $toUsers = $messageObject->getField('to'); + static::assertInstanceOf(GraphNode::class, $toUsers[0]); } - public function testAGraphEdgeWillGenerateTheProperParentGraphEdges() + public function testAGraphEdgeWillGenerateTheProperParentGraphEdges(): void { $likesList = [ 'data' => [ @@ -433,20 +443,20 @@ public function testAGraphEdgeWillGenerateTheProperParentGraphEdges() 'previous' => 'http://facebook/prev', ], ]); - $res = new FacebookResponse($this->request, $data); + $res = new Response($this->request, $data); $factory = new GraphNodeFactory($res); $graphEdge = $factory->makeGraphEdge(); $topGraphEdge = $graphEdge->getParentGraphEdge(); - $childGraphEdgeOne = $graphEdge[0]['likes']->getParentGraphEdge(); - $childGraphEdgeTwo = $graphEdge[1]['likes']->getParentGraphEdge(); - $childGraphEdgeThree = $graphEdge[1]['photos']->getParentGraphEdge(); - $childGraphEdgeFour = $graphEdge[1]['photos'][0]['likes']->getParentGraphEdge(); - - $this->assertNull($topGraphEdge); - $this->assertEquals('/111/likes', $childGraphEdgeOne); - $this->assertEquals('/222/likes', $childGraphEdgeTwo); - $this->assertEquals('/222/photos', $childGraphEdgeThree); - $this->assertEquals('/777/likes', $childGraphEdgeFour); + $childGraphEdgeOne = $graphEdge[0]->getField('likes')->getParentGraphEdge(); + $childGraphEdgeTwo = $graphEdge[1]->getField('likes')->getParentGraphEdge(); + $childGraphEdgeThree = $graphEdge[1]->getField('photos')->getParentGraphEdge(); + $childGraphEdgeFour = $graphEdge[1]->getField('photos')[0]->getField('likes')->getParentGraphEdge(); + + static::assertNull($topGraphEdge); + static::assertEquals('/111/likes', $childGraphEdgeOne); + static::assertEquals('/222/likes', $childGraphEdgeTwo); + static::assertEquals('/222/photos', $childGraphEdgeThree); + static::assertEquals('/777/likes', $childGraphEdgeFour); } } diff --git a/tests/GraphNodes/GraphNodeTest.php b/tests/GraphNodes/GraphNodeTest.php index 67444fae8..5f1750650 100644 --- a/tests/GraphNodes/GraphNodeTest.php +++ b/tests/GraphNodes/GraphNodeTest.php @@ -1,4 +1,6 @@ asArray(); - $this->assertEquals([], $backingData); + static::assertEquals([], $backingData); } - public function testAGraphNodeCanInstantiateWithData() + public function testAGraphNodeCanInstantiateWithData(): void { $graphNode = new GraphNode(['foo' => 'bar']); $backingData = $graphNode->asArray(); - $this->assertEquals(['foo' => 'bar'], $backingData); + static::assertEquals(['foo' => 'bar'], $backingData); } - public function testDatesThatShouldBeCastAsDateTimeObjectsAreDetected() + /** + * @dataProvider provideDateTimeFieldNames + */ + public function testCastDateTimeFieldsToDateTime($fieldName): void { - $graphNode = new GraphNode(); + $graphNode = new GraphNode([$fieldName => '1989-11-02']); + + static::assertInstanceOf(DateTime::class, $graphNode->getField($fieldName)); + } - // Should pass - $shouldPass = $graphNode->isIso8601DateString('1985-10-26T01:21:00+0000'); - $this->assertTrue($shouldPass, 'Expected the valid ISO 8601 formatted date from Back To The Future to pass.'); + public static function provideDateTimeFieldNames(): Iterator + { + yield ['created_time']; + yield ['updated_time']; + yield ['start_time']; + yield ['stop_time']; + yield ['end_time']; + yield ['backdated_time']; + yield ['issued_at']; + yield ['expires_at']; + yield ['publish_time']; + } - $shouldPass = $graphNode->isIso8601DateString('1999-12-31'); - $this->assertTrue($shouldPass, 'Expected the valid ISO 8601 formatted date to party like it\'s 1999.'); + /** + * @dataProvider provideValidDateTimeFieldValues + */ + public function testCastDateTimeFieldValueToDateTime($value, $message, $prettyDate = null): void + { + $graphNode = new GraphNode(['created_time' => $value]); - $shouldPass = $graphNode->isIso8601DateString('2009-05-19T14:39Z'); - $this->assertTrue($shouldPass, 'Expected the valid ISO 8601 formatted date to pass.'); + static::assertInstanceOf(DateTime::class, $graphNode->getField('created_time'), $message); - $shouldPass = $graphNode->isIso8601DateString('2014-W36'); - $this->assertTrue($shouldPass, 'Expected the valid ISO 8601 formatted date to pass.'); + if ($prettyDate !== null) { + static::assertEquals($prettyDate, $graphNode->getField('created_time')->format(DateTimeInterface::RFC1036)); + } + } - // Should fail - $shouldFail = $graphNode->isIso8601DateString('2009-05-19T14a39r'); - $this->assertFalse($shouldFail, 'Expected the invalid ISO 8601 format to fail.'); - $shouldFail = $graphNode->isIso8601DateString('foo_time'); - $this->assertFalse($shouldFail, 'Expected the invalid ISO 8601 format to fail.'); + public static function provideValidDateTimeFieldValues(): Iterator + { + yield ['1985-10-26T01:21:00+0000', 'Expected the valid ISO 8601 formatted date from Back To The Future to pass.']; + yield ['2014-07-15T03:44:53+0000', 'Expected the valid ISO 8601 formatted date to pass.', 'Tue, 15 Jul 14 03:44:53 +0000']; + yield ['1999-12-31', 'Expected the valid ISO 8601 formatted date to party like it\'s 1999.']; + yield ['2009-05-19T14:39Z', 'Expected the valid ISO 8601 formatted date to pass.']; + yield ['2014-W36', 'Expected the valid ISO 8601 formatted date to pass.']; + yield [1_405_547_020, 'Expected the valid timestamp to pass.', 'Wed, 16 Jul 14 23:43:40 +0200']; } - public function testATimeStampCanBeConvertedToADateTimeObject() + + /** + * @dataProvider provideInvalidDateTimeFieldValues + */ + public function testNotCastDateTimeFieldValueToDateTime($value, $message): void { - $someTimeStampFromGraph = 1405547020; - $graphNode = new GraphNode(); - $dateTime = $graphNode->castToDateTime($someTimeStampFromGraph); - $prettyDate = $dateTime->format(\DateTime::RFC1036); - $timeStamp = $dateTime->getTimestamp(); + $graphNode = new GraphNode(['created_time' => $value]); - $this->assertInstanceOf('DateTime', $dateTime); - $this->assertEquals('Wed, 16 Jul 14 23:43:40 +0200', $prettyDate); - $this->assertEquals(1405547020, $timeStamp); + static::assertNotInstanceOf(DateTime::class, $graphNode->getField('created_time'), $message); } - public function testAGraphDateStringCanBeConvertedToADateTimeObject() + + public static function provideInvalidDateTimeFieldValues(): Iterator { - $someDateStringFromGraph = '2014-07-15T03:44:53+0000'; - $graphNode = new GraphNode(); - $dateTime = $graphNode->castToDateTime($someDateStringFromGraph); - $prettyDate = $dateTime->format(\DateTime::RFC1036); - $timeStamp = $dateTime->getTimestamp(); + yield ['2009-05-19T14a39r', 'Expected the invalid ISO 8601 format to fail.']; + yield ['foo_time', 'Expected the invalid ISO 8601 format to fail.']; + } + - $this->assertInstanceOf('DateTime', $dateTime); - $this->assertEquals('Tue, 15 Jul 14 03:44:53 +0000', $prettyDate); - $this->assertEquals(1405395893, $timeStamp); + public function testCastBirthdayFieldValueToBirthday(): void + { + $graphNode = new GraphNode(['birthday' => '11/02/1989']); + + static::assertInstanceOf(Birthday::class, $graphNode->getField('birthday')); } - public function testUncastingAGraphNodeWillUncastTheDateTimeObject() + + public function testGettingGraphNodeAsAnArrayWillNotUncastTheDateTimeObject(): void { - $collectionOne = new GraphNode(['foo', 'bar']); - $collectionTwo = new GraphNode([ + $graphNode = new GraphNode([ 'id' => '123', - 'date' => new \DateTime('2014-07-15T03:44:53+0000'), - 'some_collection' => $collectionOne, + 'created_time' => '2014-07-15T03:44:53+0000', ]); - $uncastArray = $collectionTwo->uncastItems(); + $graphNodeAsArray = $graphNode->asArray(); - $this->assertEquals([ - 'id' => '123', - 'date' => '2014-07-15T03:44:53+0000', - 'some_collection' => ['foo', 'bar'], - ], $uncastArray); + static::assertInstanceOf(DateTime::class, $graphNodeAsArray['created_time']); } - public function testGettingGraphNodeAsAnArrayWillNotUncastTheDateTimeObject() + + public function testGettingAGraphNodeAsAStringWillSafelyRepresentDateTimes(): void { - $collection = new GraphNode([ + $graphNode = new GraphNode([ 'id' => '123', - 'date' => new \DateTime('2014-07-15T03:44:53+0000'), + 'created_time' => '2014-07-15T03:44:53+0000', ]); - $collectionAsArray = $collection->asArray(); + $graphNodeAsString = (string) $graphNode; - $this->assertInstanceOf('DateTime', $collectionAsArray['date']); + static::assertEquals('{"id":"123","created_time":"2014-07-15T03:44:53+0000"}', $graphNodeAsString); } - public function testReturningACollectionAsJasonWillSafelyRepresentDateTimes() + + public function testAnExistingFieldCanBeAccessed(): void { - $collection = new GraphNode([ - 'id' => '123', - 'date' => new \DateTime('2014-07-15T03:44:53+0000'), + $graphNode = new GraphNode(['foo' => 'bar']); + + $field = $graphNode->getField('foo'); + static::assertEquals('bar', $field); + } + + + public function testAMissingFieldWillReturnNull(): void + { + $graphNode = new GraphNode(['foo' => 'bar']); + $field = $graphNode->getField('baz'); + + static::assertNull($field, 'Expected the property to return null.'); + } + + + public function testAMissingFieldWillReturnTheDefault(): void + { + $graphNode = new GraphNode(['foo' => 'bar']); + + $field = $graphNode->getField('baz', 'faz'); + static::assertEquals('faz', $field); + } + + + public function testFalseDefaultsWillReturnSameType(): void + { + $graphNode = new GraphNode(['foo' => 'bar']); + + $field = $graphNode->getField('baz', ''); + static::assertSame('', $field); + + $field = $graphNode->getField('baz', 0); + static::assertSame(0, $field); + + $field = $graphNode->getField('baz', false); + static::assertFalse($field); + } + + + public function testTheFieldsFromTheGraphNodeCanBeReturned(): void + { + $graphNode = new GraphNode([ + 'field1' => 'foo', + 'field2' => 'bar', + 'field3' => 'baz', ]); - $collectionAsString = $collection->asJson(); + $fieldNames = $graphNode->getFieldNames(); + static::assertEquals(['field1', 'field2', 'field3'], $fieldNames); + } + + + public function testAGraphNodeCanBeConvertedToAString(): void + { + $graphNode = new GraphNode(['foo', 'bar', 123]); + + $graphNodeAsString = (string) $graphNode; - $this->assertEquals('{"id":"123","date":"2014-07-15T03:44:53+0000"}', $collectionAsString); + static::assertEquals('["foo","bar",123]', $graphNodeAsString); } } diff --git a/tests/GraphNodes/GraphObjectFactoryTest.php b/tests/GraphNodes/GraphObjectFactoryTest.php deleted file mode 100644 index 3ef1d0bc1..000000000 --- a/tests/GraphNodes/GraphObjectFactoryTest.php +++ /dev/null @@ -1,114 +0,0 @@ -request = new FacebookRequest( - $app, - 'foo_token', - 'GET', - '/me/photos?keep=me', - ['foo' => 'bar'], - 'foo_eTag', - 'v1337' - ); - } - - public function testAGraphNodeWillBeCastAsAGraphNode() - { - $data = json_encode([ - 'id' => '123', - 'name' => 'Foo McBar', - 'link' => 'http://facebook/foo', - ]); - $res = new FacebookResponse($this->request, $data); - - $factory = new GraphObjectFactory($res); - $graphObject = $factory->makeGraphObject(); - $graphData = $graphObject->asArray(); - - $this->assertInstanceOf('\Facebook\GraphNodes\GraphObject', $graphObject); - $this->assertEquals([ - 'id' => '123', - 'name' => 'Foo McBar', - 'link' => 'http://facebook/foo', - ], $graphData); - } - - public function testAListFromGraphWillBeCastAsAGraphEdge() - { - $data = json_encode([ - 'data' => [ - [ - 'id' => '123', - 'name' => 'Foo McBar', - 'link' => 'http://facebook/foo', - ], - [ - 'id' => '1337', - 'name' => 'Bar McBaz', - 'link' => 'http://facebook/bar', - ], - ], - 'paging' => [ - 'next' => 'http://facebook/next', - 'previous' => 'http://facebook/prev', - ], - ]); - $res = new FacebookResponse($this->request, $data); - - $factory = new GraphObjectFactory($res); - $graphList = $factory->makeGraphList(); - $graphData = $graphList->asArray(); - - $this->assertInstanceOf('\Facebook\GraphNodes\GraphList', $graphList); - $this->assertEquals([ - 'id' => '123', - 'name' => 'Foo McBar', - 'link' => 'http://facebook/foo', - ], $graphData[0]); - $this->assertEquals([ - 'id' => '1337', - 'name' => 'Bar McBaz', - 'link' => 'http://facebook/bar', - ], $graphData[1]); - } -} diff --git a/tests/GraphNodes/GraphPageTest.php b/tests/GraphNodes/GraphPageTest.php deleted file mode 100644 index c7ce163c9..000000000 --- a/tests/GraphNodes/GraphPageTest.php +++ /dev/null @@ -1,95 +0,0 @@ -responseMock = m::mock('\\Facebook\\FacebookResponse'); - } - - public function testPagePropertiesReturnGraphPageObjects() - { - $dataFromGraph = [ - 'id' => '123', - 'name' => 'Foo Page', - 'best_page' => [ - 'id' => '1', - 'name' => 'Bar Page', - ], - 'global_brand_parent_page' => [ - 'id' => '2', - 'name' => 'Faz Page', - ], - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphPage(); - - $bestPage = $graphNode->getBestPage(); - $globalBrandParentPage = $graphNode->getGlobalBrandParentPage(); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPage', $bestPage); - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPage', $globalBrandParentPage); - } - - public function testLocationPropertyWillGetCastAsGraphLocationObject() - { - $dataFromGraph = [ - 'id' => '123', - 'name' => 'Foo Page', - 'location' => [ - 'city' => 'Washington', - 'country' => 'United States', - 'latitude' => 38.881634205431, - 'longitude' => -77.029121075722, - 'state' => 'DC', - ], - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphPage(); - - $location = $graphNode->getLocation(); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphLocation', $location); - } -} diff --git a/tests/GraphNodes/GraphSessionInfoTest.php b/tests/GraphNodes/GraphSessionInfoTest.php deleted file mode 100644 index b2e56faed..000000000 --- a/tests/GraphNodes/GraphSessionInfoTest.php +++ /dev/null @@ -1,62 +0,0 @@ -responseMock = m::mock('\\Facebook\\FacebookResponse'); - } - - public function testDatesGetCastToDateTime() - { - $dataFromGraph = [ - 'expires_at' => 123, - 'issued_at' => 1337, - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - - $graphNode = $factory->makeGraphSessionInfo(); - - $expires = $graphNode->getExpiresAt(); - $issuedAt = $graphNode->getIssuedAt(); - - $this->assertInstanceOf('DateTime', $expires); - $this->assertInstanceOf('DateTime', $issuedAt); - } -} diff --git a/tests/GraphNodes/GraphUserTest.php b/tests/GraphNodes/GraphUserTest.php deleted file mode 100644 index a3230fa36..000000000 --- a/tests/GraphNodes/GraphUserTest.php +++ /dev/null @@ -1,204 +0,0 @@ -responseMock = m::mock('\\Facebook\\FacebookResponse'); - } - - public function testDatesGetCastToDateTime() - { - $dataFromGraph = [ - 'updated_time' => '2016-04-26 13:22:05', - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $updatedTime = $graphNode->getField('updated_time'); - - $this->assertInstanceOf('DateTime', $updatedTime); - } - - public function testBirthdaysGetCastToBirthday() - { - $dataFromGraph = [ - 'birthday' => '1984/01/01', - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $birthday = $graphNode->getBirthday(); - - // Test to ensure BC - $this->assertInstanceOf('DateTime', $birthday); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\Birthday', $birthday); - $this->assertTrue($birthday->hasDate()); - $this->assertTrue($birthday->hasYear()); - $this->assertEquals('1984/01/01', $birthday->format('Y/m/d')); - } - - public function testBirthdayCastHandlesDateWithoutYear() - { - $dataFromGraph = [ - 'birthday' => '03/21', - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $birthday = $graphNode->getBirthday(); - - $this->assertTrue($birthday->hasDate()); - $this->assertFalse($birthday->hasYear()); - $this->assertEquals('03/21', $birthday->format('m/d')); - } - - public function testBirthdayCastHandlesYearWithoutDate() - { - $dataFromGraph = [ - 'birthday' => '1984', - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $birthday = $graphNode->getBirthday(); - - $this->assertTrue($birthday->hasYear()); - $this->assertFalse($birthday->hasDate()); - $this->assertEquals('1984', $birthday->format('Y')); - } - - public function testPagePropertiesWillGetCastAsGraphPageObjects() - { - $dataFromGraph = [ - 'id' => '123', - 'name' => 'Foo User', - 'hometown' => [ - 'id' => '1', - 'name' => 'Foo Place', - ], - 'location' => [ - 'id' => '2', - 'name' => 'Bar Place', - ], - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $hometown = $graphNode->getHometown(); - $location = $graphNode->getLocation(); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPage', $hometown); - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPage', $location); - } - - public function testUserPropertiesWillGetCastAsGraphUserObjects() - { - $dataFromGraph = [ - 'id' => '123', - 'name' => 'Foo User', - 'significant_other' => [ - 'id' => '1337', - 'name' => 'Bar User', - ], - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $significantOther = $graphNode->getSignificantOther(); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphUser', $significantOther); - } - - public function testPicturePropertiesWillGetCastAsGraphPictureObjects() - { - $dataFromGraph = [ - 'id' => '123', - 'name' => 'Foo User', - 'picture' => [ - 'is_silhouette' => true, - 'url' => 'http://foo.bar', - 'width' => 200, - 'height' => 200, - ], - ]; - - $this->responseMock - ->shouldReceive('getDecodedBody') - ->once() - ->andReturn($dataFromGraph); - $factory = new GraphNodeFactory($this->responseMock); - $graphNode = $factory->makeGraphUser(); - - $Picture = $graphNode->getPicture(); - - $this->assertInstanceOf('\\Facebook\\GraphNodes\\GraphPicture', $Picture); - $this->assertTrue($Picture->isSilhouette()); - $this->assertEquals(200, $Picture->getWidth()); - $this->assertEquals(200, $Picture->getHeight()); - $this->assertEquals('http://foo.bar', $Picture->getUrl()); - } -} diff --git a/tests/Helpers/FacebookCanvasHelperTest.php b/tests/Helpers/CanvasHelperTest.php similarity index 64% rename from tests/Helpers/FacebookCanvasHelperTest.php rename to tests/Helpers/CanvasHelperTest.php index f03d66fbc..967d8cd5d 100644 --- a/tests/Helpers/FacebookCanvasHelperTest.php +++ b/tests/Helpers/CanvasHelperTest.php @@ -1,4 +1,6 @@ helper = new FacebookCanvasHelper($app, new FacebookClient()); + $app = new Application('123', 'foo_app_secret'); + $this->helper = new CanvasHelper($app, new Client(), 'v0.0'); } - public function testSignedRequestDataCanBeRetrievedFromPostData() + public function testSignedRequestDataCanBeRetrievedFromPostData(): void { $_POST['signed_request'] = $this->rawSignedRequestAuthorized; $rawSignedRequest = $this->helper->getRawSignedRequest(); - $this->assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); + static::assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); } } diff --git a/tests/Helpers/FacebookJavaScriptHelperTest.php b/tests/Helpers/JavaScriptHelperTest.php similarity index 66% rename from tests/Helpers/FacebookJavaScriptHelperTest.php rename to tests/Helpers/JavaScriptHelperTest.php index 521875885..97170e340 100644 --- a/tests/Helpers/FacebookJavaScriptHelperTest.php +++ b/tests/Helpers/JavaScriptHelperTest.php @@ -1,4 +1,6 @@ rawSignedRequestAuthorized; - $app = new FacebookApp('123', 'foo_app_secret'); - $helper = new FacebookJavaScriptHelper($app, new FacebookClient()); + $app = new Application('123', 'foo_app_secret'); + $helper = new JavaScriptHelper($app, new Client(), 'v0.0'); $rawSignedRequest = $helper->getRawSignedRequest(); - $this->assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); + static::assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); } } diff --git a/tests/Helpers/FacebookPageTabHelperTest.php b/tests/Helpers/PageTabHelperTest.php similarity index 56% rename from tests/Helpers/FacebookPageTabHelperTest.php rename to tests/Helpers/PageTabHelperTest.php index 5c27f488a..c60c8c73c 100644 --- a/tests/Helpers/FacebookPageTabHelperTest.php +++ b/tests/Helpers/PageTabHelperTest.php @@ -1,4 +1,6 @@ rawSignedRequestAuthorized; - $app = new FacebookApp('123', 'foo_app_secret'); - $helper = new FacebookPageTabHelper($app, new FacebookClient()); + $app = new Application('123', 'foo_app_secret'); + $helper = new PageTabHelper($app, new Client(), 'v0.0'); - $this->assertFalse($helper->isAdmin()); - $this->assertEquals('42', $helper->getPageId()); - $this->assertEquals('42', $helper->getPageData('id')); - $this->assertEquals('default', $helper->getPageData('foo', 'default')); + static::assertFalse($helper->isAdmin()); + static::assertEquals('42', $helper->getPageId()); + static::assertEquals('42', $helper->getPageData('id')); + static::assertEquals('default', $helper->getPageData('foo', 'default')); } } diff --git a/tests/Helpers/FacebookRedirectLoginHelperTest.php b/tests/Helpers/RedirectLoginHelperTest.php similarity index 63% rename from tests/Helpers/FacebookRedirectLoginHelperTest.php rename to tests/Helpers/RedirectLoginHelperTest.php index be31689a2..cb5a94ddc 100644 --- a/tests/Helpers/FacebookRedirectLoginHelperTest.php +++ b/tests/Helpers/RedirectLoginHelperTest.php @@ -1,4 +1,6 @@ persistentDataHandler = new FacebookMemoryPersistentDataHandler(); - $app = new FacebookApp('123', 'foo_app_secret'); - $oAuth2Client = new FooRedirectLoginOAuth2Client($app, new FacebookClient(), 'v1337'); - $this->redirectLoginHelper = new FacebookRedirectLoginHelper($oAuth2Client, $this->persistentDataHandler); + $app = new Application('123', 'foo_app_secret'); + $oAuth2Client = new FooRedirectLoginOAuth2Client($app, new Client(), 'v1337'); + $this->redirectLoginHelper = new RedirectLoginHelper($oAuth2Client, $this->persistentDataHandler); } - public function testLoginURL() + public function testLoginURL(): void { $scope = ['foo', 'bar']; $loginUrl = $this->redirectLoginHelper->getLoginUrl(self::REDIRECT_URL, $scope); $expectedUrl = 'https://www.facebook.com/v1337/dialog/oauth?'; - $this->assertTrue(strpos($loginUrl, $expectedUrl) === 0, 'Unexpected base login URL returned from getLoginUrl().'); + static::assertStringStartsWith($expectedUrl, $loginUrl, 'Unexpected base login URL returned from getLoginUrl().'); $params = [ 'client_id' => '123', @@ -74,28 +80,26 @@ public function testLoginURL() 'scope' => implode(',', $scope), ]; foreach ($params as $key => $value) { - $this->assertContains($key . '=' . urlencode($value), $loginUrl); + static::assertStringContainsString($key . '=' . urlencode($value), $loginUrl); } } - public function testLogoutURL() + public function testLogoutURL(): void { $logoutUrl = $this->redirectLoginHelper->getLogoutUrl('foo_token', self::REDIRECT_URL); $expectedUrl = 'https://www.facebook.com/logout.php?'; - $this->assertTrue(strpos($logoutUrl, $expectedUrl) === 0, 'Unexpected base logout URL returned from getLogoutUrl().'); + static::assertStringStartsWith($expectedUrl, $logoutUrl, 'Unexpected base logout URL returned from getLogoutUrl().'); $params = [ 'next' => self::REDIRECT_URL, 'access_token' => 'foo_token', ]; foreach ($params as $key => $value) { - $this->assertTrue( - strpos($logoutUrl, $key . '=' . urlencode($value)) !== false - ); + static::assertStringContainsString($key . '=' . urlencode($value), $logoutUrl); } } - public function testAnAccessTokenCanBeObtainedFromRedirect() + public function testAnAccessTokenCanBeObtainedFromRedirect(): void { $this->persistentDataHandler->set('state', static::FOO_STATE); @@ -111,26 +115,6 @@ public function testAnAccessTokenCanBeObtainedFromRedirect() $expectedUrl = self::REDIRECT_URL . '?' . static::FOO_PARAM; $expectedString = 'foo_token_from_code|' . static::FOO_CODE . '|' . $expectedUrl; - $this->assertEquals($expectedString, $accessToken->getValue()); - } - - public function testACustomCsprsgCanBeInjected() - { - $app = new FacebookApp('123', 'foo_app_secret'); - $accessTokenClient = new FooRedirectLoginOAuth2Client($app, new FacebookClient(), 'v1337'); - $fooPrsg = new FooPseudoRandomStringGenerator(); - $helper = new FacebookRedirectLoginHelper($accessTokenClient, $this->persistentDataHandler, null, $fooPrsg); - - $loginUrl = $helper->getLoginUrl(self::REDIRECT_URL); - - $this->assertContains('state=csprs123', $loginUrl); - } - - public function testThePseudoRandomStringGeneratorWillAutoDetectCsprsg() - { - $this->assertInstanceOf( - 'Facebook\PseudoRandomString\PseudoRandomStringGeneratorInterface', - $this->redirectLoginHelper->getPseudoRandomStringGenerator() - ); + static::assertEquals($expectedString, $accessToken->getValue()); } } diff --git a/tests/Helpers/FacebookSignedRequestFromInputHelperTest.php b/tests/Helpers/SignedRequestFromInputHelperTest.php similarity index 58% rename from tests/Helpers/FacebookSignedRequestFromInputHelperTest.php rename to tests/Helpers/SignedRequestFromInputHelperTest.php index ffaa5e329..ea92f0393 100644 --- a/tests/Helpers/FacebookSignedRequestFromInputHelperTest.php +++ b/tests/Helpers/SignedRequestFromInputHelperTest.php @@ -1,4 +1,6 @@ helper = new FooSignedRequestHelper($app, new FooSignedRequestHelperFacebookClient()); + $app = new Application('123', 'foo_app_secret'); + $this->helper = new FooSignedRequestHelper($app, new FooSignedRequestHelperClient(), 'v0.0'); } - public function testSignedRequestDataCanBeRetrievedFromPostData() + public function testSignedRequestDataCanBeRetrievedFromPostData(): void { $_POST['signed_request'] = 'foo_signed_request'; $rawSignedRequest = $this->helper->getRawSignedRequestFromPost(); - $this->assertEquals('foo_signed_request', $rawSignedRequest); + static::assertEquals('foo_signed_request', $rawSignedRequest); } - public function testSignedRequestDataCanBeRetrievedFromCookieData() + public function testSignedRequestDataCanBeRetrievedFromCookieData(): void { $_COOKIE['fbsr_123'] = 'foo_signed_request'; $rawSignedRequest = $this->helper->getRawSignedRequestFromCookie(); - $this->assertEquals('foo_signed_request', $rawSignedRequest); + static::assertEquals('foo_signed_request', $rawSignedRequest); } - public function testAccessTokenWillBeNullWhenAUserHasNotYetAuthorizedTheApp() + public function testAccessTokenWillBeNullWhenAUserHasNotYetAuthorizedTheApp(): void { $this->helper->instantiateSignedRequest($this->rawSignedRequestUnauthorized); $accessToken = $this->helper->getAccessToken(); - $this->assertNull($accessToken); + static::assertNull($accessToken); } - public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsAnAccessToken() + public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsAnAccessToken(): void { $this->helper->instantiateSignedRequest($this->rawSignedRequestAuthorizedWithAccessToken); $accessToken = $this->helper->getAccessToken(); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('foo_token', $accessToken->getValue()); + static::assertInstanceOf(AccessToken::class, $accessToken); + static::assertEquals('foo_token', $accessToken->getValue()); } - public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsACode() + public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsACode(): void { $this->helper->instantiateSignedRequest($this->rawSignedRequestAuthorizedWithCode); $accessToken = $this->helper->getAccessToken(); - $this->assertInstanceOf('Facebook\Authentication\AccessToken', $accessToken); - $this->assertEquals('foo_access_token_from:foo_code', $accessToken->getValue()); + static::assertInstanceOf(AccessToken::class, $accessToken); + static::assertEquals('foo_access_token_from:foo_code', $accessToken->getValue()); } } diff --git a/tests/Http/GraphRawResponseTest.php b/tests/Http/GraphRawResponseTest.php index fcb71f480..6946b3233 100644 --- a/tests/Http/GraphRawResponseTest.php +++ b/tests/Http/GraphRawResponseTest.php @@ -1,4 +1,6 @@ '"9d86b21aa74d74e574bbb35ba13524a52deb96e3"', 'Content-Type' => 'text/javascript; charset=UTF-8', 'X-FB-Rev' => '9244768', @@ -48,10 +54,10 @@ class GraphRawResponseTest extends \PHPUnit_Framework_TestCase 'Access-Control-Allow-Origin' => '*', ]; - protected $jsonFakeHeader = 'x-fb-ads-insights-throttle: {"app_id_util_pct": 0.00,"acc_id_util_pct": 0.00}'; - protected $jsonFakeHeaderAsArray = ['x-fb-ads-insights-throttle' => '{"app_id_util_pct": 0.00,"acc_id_util_pct": 0.00}']; + protected string $jsonFakeHeader = 'x-fb-ads-insights-throttle: {"app_id_util_pct": 0.00,"acc_id_util_pct": 0.00}'; + protected array $jsonFakeHeaderAsArray = ['x-fb-ads-insights-throttle' => '{"app_id_util_pct": 0.00,"acc_id_util_pct": 0.00}']; - public function testCanSetTheHeadersFromAnArray() + public function testCanSetTheHeadersFromAnArray(): void { $myHeaders = [ 'foo' => 'bar', @@ -60,51 +66,51 @@ public function testCanSetTheHeadersFromAnArray() $response = new GraphRawResponse($myHeaders, ''); $headers = $response->getHeaders(); - $this->assertEquals($myHeaders, $headers); + static::assertEquals($myHeaders, $headers); } - public function testCanSetTheHeadersFromAString() + public function testCanSetTheHeadersFromAString(): void { $response = new GraphRawResponse($this->fakeRawHeader, ''); $headers = $response->getHeaders(); $httpResponseCode = $response->getHttpResponseCode(); - $this->assertEquals($this->fakeHeadersAsArray, $headers); - $this->assertEquals(200, $httpResponseCode); + static::assertEquals($this->fakeHeadersAsArray, $headers); + static::assertEquals(200, $httpResponseCode); } - public function testWillIgnoreProxyHeaders() + public function testWillIgnoreProxyHeaders(): void { $response = new GraphRawResponse($this->fakeRawProxyHeader . $this->fakeRawHeader, ''); $headers = $response->getHeaders(); $httpResponseCode = $response->getHttpResponseCode(); - $this->assertEquals($this->fakeHeadersAsArray, $headers); - $this->assertEquals(200, $httpResponseCode); + static::assertEquals($this->fakeHeadersAsArray, $headers); + static::assertEquals(200, $httpResponseCode); } - public function testCanTransformJsonHeaderValues() + public function testCanTransformJsonHeaderValues(): void { $response = new GraphRawResponse($this->jsonFakeHeader, ''); $headers = $response->getHeaders(); - $this->assertEquals($this->jsonFakeHeaderAsArray['x-fb-ads-insights-throttle'], $headers['x-fb-ads-insights-throttle']); + static::assertEquals($this->jsonFakeHeaderAsArray['x-fb-ads-insights-throttle'], $headers['x-fb-ads-insights-throttle']); } - public function testHttpResponseCode() + public function testHttpResponseCode(): void { // HTTP/1.0 $headers = str_replace('HTTP/1.1', 'HTTP/1.0', $this->fakeRawHeader); $response = new GraphRawResponse($headers, ''); - $this->assertEquals(200, $response->getHttpResponseCode()); + static::assertEquals(200, $response->getHttpResponseCode()); // HTTP/1.1 $response = new GraphRawResponse($this->fakeRawHeader, ''); - $this->assertEquals(200, $response->getHttpResponseCode()); + static::assertEquals(200, $response->getHttpResponseCode()); // HTTP/2 $headers = str_replace('HTTP/1.1', 'HTTP/2', $this->fakeRawHeader); $response = new GraphRawResponse($headers, ''); - $this->assertEquals(200, $response->getHttpResponseCode()); + static::assertEquals(200, $response->getHttpResponseCode()); } } diff --git a/tests/Http/RequestBodyMultipartTest.php b/tests/Http/RequestBodyMultipartTest.php index 1a23c469f..682521e86 100644 --- a/tests/Http/RequestBodyMultipartTest.php +++ b/tests/Http/RequestBodyMultipartTest.php @@ -1,4 +1,6 @@ 'bar', @@ -42,12 +48,12 @@ public function testCanProperlyEncodeAnArrayOfParams() $expectedBody .= "Content-Disposition: form-data; name=\"scawy_vawues\"\r\n\r\n@FooBar is a real twitter handle.\r\n"; $expectedBody .= "--foo_boundary--\r\n"; - $this->assertEquals($expectedBody, $body); + static::assertEquals($expectedBody, $body); } - public function testCanProperlyEncodeFilesAndParams() + public function testCanProperlyEncodeFilesAndParams(): void { - $file = new FacebookFile(__DIR__ . '/../foo.txt'); + $file = new File(__DIR__ . '/../foo.txt'); $message = new RequestBodyMultipart([ 'foo' => 'bar', ], [ @@ -62,10 +68,10 @@ public function testCanProperlyEncodeFilesAndParams() $expectedBody .= "Content-Type: text/plain\r\n\r\nThis is a text file used for testing. Let's dance.\r\n"; $expectedBody .= "--foo_boundary--\r\n"; - $this->assertEquals($expectedBody, $body); + static::assertEquals($expectedBody, $body); } - public function testSupportsMultidimensionalParams() + public function testSupportsMultidimensionalParams(): void { $message = new RequestBodyMultipart([ 'foo' => 'bar', @@ -77,9 +83,9 @@ public function testSupportsMultidimensionalParams() 'call_to_action' => [ 'type' => 'LEARN_MORE', 'value' => [ - 'link' => 'http://example.com', + 'link' => 'https://example.com', 'sponsorship' => [ - 'image' => 'http://example.com/bar.jpg', + 'image' => 'https://example.com/bar.jpg', ], ], ], @@ -101,11 +107,11 @@ public function testSupportsMultidimensionalParams() $expectedBody .= "--foo_boundary\r\n"; $expectedBody .= "Content-Disposition: form-data; name=\"call_to_action[type]\"\r\n\r\nLEARN_MORE\r\n"; $expectedBody .= "--foo_boundary\r\n"; - $expectedBody .= "Content-Disposition: form-data; name=\"call_to_action[value][link]\"\r\n\r\nhttp://example.com\r\n"; + $expectedBody .= "Content-Disposition: form-data; name=\"call_to_action[value][link]\"\r\n\r\nhttps://example.com\r\n"; $expectedBody .= "--foo_boundary\r\n"; - $expectedBody .= "Content-Disposition: form-data; name=\"call_to_action[value][sponsorship][image]\"\r\n\r\nhttp://example.com/bar.jpg\r\n"; + $expectedBody .= "Content-Disposition: form-data; name=\"call_to_action[value][sponsorship][image]\"\r\n\r\nhttps://example.com/bar.jpg\r\n"; $expectedBody .= "--foo_boundary--\r\n"; - $this->assertEquals($expectedBody, $body); + static::assertEquals($expectedBody, $body); } } diff --git a/tests/Http/RequestUrlEncodedTest.php b/tests/Http/RequestUrlEncodedTest.php index 2b4f67f9b..65bfa13ea 100644 --- a/tests/Http/RequestUrlEncodedTest.php +++ b/tests/Http/RequestUrlEncodedTest.php @@ -1,4 +1,6 @@ 'bar', @@ -35,10 +41,10 @@ public function testCanProperlyEncodeAnArrayOfParams() ]); $body = $message->getBody(); - $this->assertEquals('foo=bar&scawy_vawues=%40FooBar+is+a+real+twitter+handle.', $body); + static::assertEquals('foo=bar&scawy_vawues=%40FooBar+is+a+real+twitter+handle.', $body); } - public function testSupportsMultidimensionalParams() + public function testSupportsMultidimensionalParams(): void { $message = new RequestBodyUrlEncoded([ 'foo' => 'bar', @@ -50,15 +56,15 @@ public function testSupportsMultidimensionalParams() 'call_to_action' => [ 'type' => 'LEARN_MORE', 'value' => [ - 'link' => 'http://example.com', + 'link' => 'https://example.com', 'sponsorship' => [ - 'image' => 'http://example.com/bar.jpg', + 'image' => 'https://example.com/bar.jpg', ], ], ], ]); $body = $message->getBody(); - $this->assertEquals('foo=bar&faz%5B0%5D=1&faz%5B1%5D=2&faz%5B2%5D=3&targeting%5Bcountries%5D=US%2CGB&targeting%5Bage_min%5D=13&call_to_action%5Btype%5D=LEARN_MORE&call_to_action%5Bvalue%5D%5Blink%5D=http%3A%2F%2Fexample.com&call_to_action%5Bvalue%5D%5Bsponsorship%5D%5Bimage%5D=http%3A%2F%2Fexample.com%2Fbar.jpg', $body); + static::assertEquals('foo=bar&faz%5B0%5D=1&faz%5B1%5D=2&faz%5B2%5D=3&targeting%5Bcountries%5D=US%2CGB&targeting%5Bage_min%5D=13&call_to_action%5Btype%5D=LEARN_MORE&call_to_action%5Bvalue%5D%5Blink%5D=https%3A%2F%2Fexample.com&call_to_action%5Bvalue%5D%5Bsponsorship%5D%5Bimage%5D=https%3A%2F%2Fexample.com%2Fbar.jpg', $body); } } diff --git a/tests/HttpClients/AbstractTestHttpClient.php b/tests/HttpClients/AbstractTestHttpClient.php deleted file mode 100644 index a87005216..000000000 --- a/tests/HttpClients/AbstractTestHttpClient.php +++ /dev/null @@ -1,60 +0,0 @@ - '"9d86b21aa74d74e574bbb35ba13524a52deb96e3"', - 'Content-Type' => 'text/javascript; charset=UTF-8', - 'X-FB-Rev' => '9244768', - 'Pragma' => 'no-cache', - 'Expires' => 'Sat, 01 Jan 2000 00:00:00 GMT', - 'Connection' => 'close', - 'Date' => 'Mon, 19 May 2014 18:37:17 GMT', - 'X-FB-Debug' => '02QQiffE7JG2rV6i/Agzd0gI2/OOQ2lk5UW0=', - 'Content-Length' => '29', - 'Cache-Control' => 'private, no-cache, no-store, must-revalidate', - 'Access-Control-Allow-Origin' => '*', - ]; -} diff --git a/tests/HttpClients/FacebookCurlHttpClientTest.php b/tests/HttpClients/FacebookCurlHttpClientTest.php deleted file mode 100644 index 47cc0274e..000000000 --- a/tests/HttpClients/FacebookCurlHttpClientTest.php +++ /dev/null @@ -1,283 +0,0 @@ -markTestSkipped('cURL must be installed to test cURL client handler.'); - } - $this->curlMock = m::mock('Facebook\HttpClients\FacebookCurl'); - $this->curlClient = new FacebookCurlHttpClient($this->curlMock); - } - - public function testCanOpenGetCurlConnection() - { - $this->curlMock - ->shouldReceive('init') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('setoptArray') - ->with(m::on(function ($arg) { - - // array_diff() will sometimes trigger error on child-arrays - if (['X-Foo-Header: X-Bar'] !== $arg[CURLOPT_HTTPHEADER]) { - return false; - } - unset($arg[CURLOPT_HTTPHEADER]); - - $caInfo = array_diff($arg, [ - CURLOPT_CUSTOMREQUEST => 'GET', - CURLOPT_URL => 'http://foo.com', - CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_TIMEOUT => 123, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_HEADER => true, - CURLOPT_SSL_VERIFYHOST => 2, - CURLOPT_SSL_VERIFYPEER => true, - ]); - - if (count($caInfo) !== 1) { - return false; - } - - if (1 !== preg_match('/.+\/certs\/DigiCertHighAssuranceEVRootCA\.pem$/', $caInfo[CURLOPT_CAINFO])) { - return false; - } - - return true; - })) - ->once() - ->andReturn(null); - - $this->curlClient->openConnection('http://foo.com', 'GET', 'foo_body', ['X-Foo-Header' => 'X-Bar'], 123); - } - - public function testCanOpenCurlConnectionWithPostBody() - { - $this->curlMock - ->shouldReceive('init') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('setoptArray') - ->with(m::on(function ($arg) { - - // array_diff() will sometimes trigger error on child-arrays - if ([] !== $arg[CURLOPT_HTTPHEADER]) { - return false; - } - unset($arg[CURLOPT_HTTPHEADER]); - - $caInfo = array_diff($arg, [ - CURLOPT_CUSTOMREQUEST => 'POST', - CURLOPT_URL => 'http://bar.com', - CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_TIMEOUT => 60, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_HEADER => true, - CURLOPT_SSL_VERIFYHOST => 2, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_POSTFIELDS => 'baz=bar', - ]); - - if (count($caInfo) !== 1) { - return false; - } - - if (1 !== preg_match('/.+\/certs\/DigiCertHighAssuranceEVRootCA\.pem$/', $caInfo[CURLOPT_CAINFO])) { - return false; - } - - return true; - })) - ->once() - ->andReturn(null); - - $this->curlClient->openConnection('http://bar.com', 'POST', 'baz=bar', [], 60); - } - - public function testCanCloseConnection() - { - $this->curlMock - ->shouldReceive('close') - ->once() - ->andReturn(null); - - $this->curlClient->closeConnection(); - } - - public function testIsolatesTheHeaderAndBody() - { - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($this->fakeRawHeader . $this->fakeRawBody); - - $this->curlClient->sendRequest(); - list($rawHeader, $rawBody) = $this->curlClient->extractResponseHeadersAndBody(); - - $this->assertEquals($rawHeader, trim($this->fakeRawHeader)); - $this->assertEquals($rawBody, $this->fakeRawBody); - } - - public function testProperlyHandlesProxyHeaders() - { - $rawHeader = $this->fakeRawProxyHeader . $this->fakeRawHeader; - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($rawHeader . $this->fakeRawBody); - - $this->curlClient->sendRequest(); - list($rawHeaders, $rawBody) = $this->curlClient->extractResponseHeadersAndBody(); - - $this->assertEquals($rawHeaders, trim($rawHeader)); - $this->assertEquals($rawBody, $this->fakeRawBody); - } - - public function testProperlyHandlesProxyHeadersWithCurlBug() - { - $rawHeader = $this->fakeRawProxyHeader . $this->fakeRawHeader; - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($rawHeader . $this->fakeRawBody); - - $this->curlClient->sendRequest(); - list($rawHeaders, $rawBody) = $this->curlClient->extractResponseHeadersAndBody(); - - $this->assertEquals($rawHeaders, trim($rawHeader)); - $this->assertEquals($rawBody, $this->fakeRawBody); - } - - public function testProperlyHandlesProxyHeadersWithCurlBug2() - { - $rawHeader = $this->fakeRawProxyHeader2 . $this->fakeRawHeader; - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($rawHeader . $this->fakeRawBody); - - $this->curlClient->sendRequest(); - list($rawHeaders, $rawBody) = $this->curlClient->extractResponseHeadersAndBody(); - - $this->assertEquals($rawHeaders, trim($rawHeader)); - $this->assertEquals($rawBody, $this->fakeRawBody); - } - - public function testProperlyHandlesRedirectHeaders() - { - $rawHeader = $this->fakeRawRedirectHeader . $this->fakeRawHeader; - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($rawHeader . $this->fakeRawBody); - - $this->curlClient->sendRequest(); - list($rawHeaders, $rawBody) = $this->curlClient->extractResponseHeadersAndBody(); - - $this->assertEquals($rawHeaders, trim($rawHeader)); - $this->assertEquals($rawBody, $this->fakeRawBody); - } - - public function testCanSendNormalRequest() - { - $this->curlMock - ->shouldReceive('init') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('setoptArray') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn($this->fakeRawHeader . $this->fakeRawBody); - $this->curlMock - ->shouldReceive('errno') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('close') - ->once() - ->andReturn(null); - - $response = $this->curlClient->send('http://foo.com/', 'GET', '', [], 60); - - $this->assertInstanceOf('Facebook\Http\GraphRawResponse', $response); - $this->assertEquals($this->fakeRawBody, $response->getBody()); - $this->assertEquals($this->fakeHeadersAsArray, $response->getHeaders()); - $this->assertEquals(200, $response->getHttpResponseCode()); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testThrowsExceptionOnClientError() - { - $this->curlMock - ->shouldReceive('init') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('setoptArray') - ->once() - ->andReturn(null); - $this->curlMock - ->shouldReceive('exec') - ->once() - ->andReturn(false); - $this->curlMock - ->shouldReceive('errno') - ->once() - ->andReturn(123); - $this->curlMock - ->shouldReceive('error') - ->once() - ->andReturn('Foo error'); - - $this->curlClient->send('http://foo.com/', 'GET', '', [], 60); - } -} diff --git a/tests/HttpClients/FacebookGuzzleHttpClientTest.php b/tests/HttpClients/FacebookGuzzleHttpClientTest.php deleted file mode 100644 index f14ad96a0..000000000 --- a/tests/HttpClients/FacebookGuzzleHttpClientTest.php +++ /dev/null @@ -1,143 +0,0 @@ -guzzleMock = m::mock('GuzzleHttp\Client'); - $this->guzzleClient = new FacebookGuzzleHttpClient($this->guzzleMock); - } - - public function testCanSendNormalRequest() - { - $request = new Request('GET', 'http://foo.com'); - - $body = Stream::factory($this->fakeRawBody); - $response = new Response(200, $this->fakeHeadersAsArray, $body); - - $this->guzzleMock - ->shouldReceive('createRequest') - ->once() - ->with('GET', 'http://foo.com/', m::on(function ($arg) { - - // array_diff_assoc() will sometimes trigger error on child-arrays - if (['X-foo' => 'bar'] !== $arg['headers']) { - return false; - } - unset($arg['headers']); - - $caInfo = array_diff_assoc($arg, [ - 'body' => 'foo_body', - 'timeout' => 123, - 'connect_timeout' => 10, - ]); - - if (count($caInfo) !== 1) { - return false; - } - - if (1 !== preg_match('/.+\/certs\/DigiCertHighAssuranceEVRootCA\.pem$/', $caInfo['verify'])) { - return false; - } - - return true; - })) - ->andReturn($request); - $this->guzzleMock - ->shouldReceive('send') - ->once() - ->with($request) - ->andReturn($response); - - $response = $this->guzzleClient->send('http://foo.com/', 'GET', 'foo_body', ['X-foo' => 'bar'], 123); - - $this->assertInstanceOf('Facebook\Http\GraphRawResponse', $response); - $this->assertEquals($this->fakeRawBody, $response->getBody()); - $this->assertEquals($this->fakeHeadersAsArray, $response->getHeaders()); - $this->assertEquals(200, $response->getHttpResponseCode()); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testThrowsExceptionOnClientError() - { - $request = new Request('GET', 'http://foo.com'); - - $this->guzzleMock - ->shouldReceive('createRequest') - ->once() - ->with('GET', 'http://foo.com/', m::on(function ($arg) { - - // array_diff_assoc() will sometimes trigger error on child-arrays - if ([] !== $arg['headers']) { - return false; - } - unset($arg['headers']); - - $caInfo = array_diff_assoc($arg, [ - 'body' => 'foo_body', - 'timeout' => 60, - 'connect_timeout' => 10, - ]); - - if (count($caInfo) !== 1) { - return false; - } - - if (1 !== preg_match('/.+\/certs\/DigiCertHighAssuranceEVRootCA\.pem$/', $caInfo['verify'])) { - return false; - } - - return true; - })) - ->andReturn($request); - $this->guzzleMock - ->shouldReceive('send') - ->once() - ->with($request) - ->andThrow(new RequestException('Foo', $request)); - - $this->guzzleClient->send('http://foo.com/', 'GET', 'foo_body', [], 60); - } -} diff --git a/tests/HttpClients/FacebookStreamHttpClientTest.php b/tests/HttpClients/FacebookStreamHttpClientTest.php deleted file mode 100644 index 3749960e1..000000000 --- a/tests/HttpClients/FacebookStreamHttpClientTest.php +++ /dev/null @@ -1,134 +0,0 @@ -streamMock = m::mock('Facebook\HttpClients\FacebookStream'); - $this->streamClient = new FacebookStreamHttpClient($this->streamMock); - } - - public function testCanCompileHeader() - { - $headers = [ - 'X-foo' => 'bar', - 'X-bar' => 'faz', - ]; - $header = $this->streamClient->compileHeader($headers); - $this->assertEquals("X-foo: bar\r\nX-bar: faz", $header); - } - - public function testCanSendNormalRequest() - { - $this->streamMock - ->shouldReceive('streamContextCreate') - ->once() - ->with(m::on(function ($arg) { - if (!isset($arg['http']) || !isset($arg['ssl'])) { - return false; - } - - if ($arg['http'] !== [ - 'method' => 'GET', - 'header' => 'X-foo: bar', - 'content' => 'foo_body', - 'timeout' => 123, - 'ignore_errors' => true, - ] - ) { - return false; - } - - $caInfo = array_diff_assoc($arg['ssl'], [ - 'verify_peer' => true, - 'verify_peer_name' => true, - 'allow_self_signed' => true, - ]); - - if (count($caInfo) !== 1) { - return false; - } - - if (1 !== preg_match('/.+\/certs\/DigiCertHighAssuranceEVRootCA\.pem$/', $caInfo['cafile'])) { - return false; - } - - return true; - })) - ->andReturn(null); - $this->streamMock - ->shouldReceive('getResponseHeaders') - ->once() - ->andReturn(explode("\n", trim($this->fakeRawHeader))); - $this->streamMock - ->shouldReceive('fileGetContents') - ->once() - ->with('http://foo.com/') - ->andReturn($this->fakeRawBody); - - $response = $this->streamClient->send('http://foo.com/', 'GET', 'foo_body', ['X-foo' => 'bar'], 123); - - $this->assertInstanceOf('Facebook\Http\GraphRawResponse', $response); - $this->assertEquals($this->fakeRawBody, $response->getBody()); - $this->assertEquals($this->fakeHeadersAsArray, $response->getHeaders()); - $this->assertEquals(200, $response->getHttpResponseCode()); - } - - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testThrowsExceptionOnClientError() - { - $this->streamMock - ->shouldReceive('streamContextCreate') - ->once() - ->andReturn(null); - $this->streamMock - ->shouldReceive('getResponseHeaders') - ->once() - ->andReturn(null); - $this->streamMock - ->shouldReceive('fileGetContents') - ->once() - ->with('http://foo.com/') - ->andReturn(false); - - $this->streamClient->send('http://foo.com/', 'GET', 'foo_body', [], 60); - } -} diff --git a/tests/HttpClients/HttpClientsFactoryTest.php b/tests/HttpClients/HttpClientsFactoryTest.php deleted file mode 100644 index 4d49489b9..000000000 --- a/tests/HttpClients/HttpClientsFactoryTest.php +++ /dev/null @@ -1,72 +0,0 @@ -assertInstanceOf(self::COMMON_INTERFACE, $httpClient); - $this->assertInstanceOf($expected, $httpClient); - } - - /** - * @return array - */ - public function httpClientsProvider() - { - $clients = [ - ['guzzle', self::COMMON_NAMESPACE . 'FacebookGuzzleHttpClient'], - ['stream', self::COMMON_NAMESPACE . 'FacebookStreamHttpClient'], - [new Client(), self::COMMON_NAMESPACE . 'FacebookGuzzleHttpClient'], - [new FacebookGuzzleHttpClient(), self::COMMON_NAMESPACE . 'FacebookGuzzleHttpClient'], - [new FacebookStreamHttpClient(), self::COMMON_NAMESPACE . 'FacebookStreamHttpClient'], - [null, self::COMMON_INTERFACE], - ]; - if (extension_loaded('curl')) { - $clients[] = ['curl', self::COMMON_NAMESPACE . 'FacebookCurlHttpClient']; - $clients[] = [new FacebookCurlHttpClient(), self::COMMON_NAMESPACE . 'FacebookCurlHttpClient']; - } - - return $clients; - } -} diff --git a/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php b/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php index 752d275de..8f305e2e4 100644 --- a/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php +++ b/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php @@ -1,4 +1,6 @@ expectException(\Facebook\Exceptions\FacebookSDKException::class); new FacebookSessionPersistentDataHandler(); } - public function testCanSetAValue() + public function testCanSetAValue(): void { - $handler = new FacebookSessionPersistentDataHandler($enableSessionCheck = false); + $handler = new FacebookSessionPersistentDataHandler(false); $handler->set('foo', 'bar'); - $this->assertEquals('bar', $_SESSION['FBRLH_foo']); + static::assertEquals('bar', $_SESSION['FBRLH_foo']); } - public function testCanGetAValue() + public function testCanGetAValue(): void { $_SESSION['FBRLH_faz'] = 'baz'; - $handler = new FacebookSessionPersistentDataHandler($enableSessionCheck = false); + $handler = new FacebookSessionPersistentDataHandler(false); $value = $handler->get('faz'); - $this->assertEquals('baz', $value); + static::assertEquals('baz', $value); } - public function testGettingAValueThatDoesntExistWillReturnNull() + public function testGettingAValueThatDoesntExistWillReturnNull(): void { - $handler = new FacebookSessionPersistentDataHandler($enableSessionCheck = false); + $handler = new FacebookSessionPersistentDataHandler(false); $value = $handler->get('does_not_exist'); - $this->assertNull($value); + static::assertNull($value); } } diff --git a/tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php b/tests/PersistentData/MemoryPersistentDataHandlerTest.php similarity index 83% rename from tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php rename to tests/PersistentData/MemoryPersistentDataHandlerTest.php index 89717f831..cddc3fe7c 100644 --- a/tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php +++ b/tests/PersistentData/MemoryPersistentDataHandlerTest.php @@ -1,4 +1,6 @@ set('foo', 'bar'); $value = $handler->get('foo'); - $this->assertEquals('bar', $value); + static::assertEquals('bar', $value); } - public function testGettingAValueThatDoesntExistWillReturnNull() + public function testGettingAValueThatDoesntExistWillReturnNull(): void { $handler = new FacebookMemoryPersistentDataHandler(); $value = $handler->get('does_not_exist'); - $this->assertNull($value); + static::assertNull($value); } } diff --git a/tests/PersistentData/PersistentDataFactoryTest.php b/tests/PersistentData/PersistentDataFactoryTest.php index d6206fcdc..464a742c2 100644 --- a/tests/PersistentData/PersistentDataFactoryTest.php +++ b/tests/PersistentData/PersistentDataFactoryTest.php @@ -1,4 +1,6 @@ assertInstanceOf(self::COMMON_INTERFACE, $persistentDataHandler); - $this->assertInstanceOf($expected, $persistentDataHandler); + static::assertInstanceOf(self::COMMON_INTERFACE, $persistentDataHandler); + static::assertInstanceOf($expected, $persistentDataHandler); } /** * @return array */ - public function persistentDataHandlerProviders() + public function persistentDataHandlerProviders(): array { $handlers = [ ['memory', self::COMMON_NAMESPACE . 'FacebookMemoryPersistentDataHandler'], diff --git a/tests/PseudoRandomString/McryptPseudoRandomStringGeneratorTest.php b/tests/PseudoRandomString/McryptPseudoRandomStringGeneratorTest.php deleted file mode 100644 index f5e033675..000000000 --- a/tests/PseudoRandomString/McryptPseudoRandomStringGeneratorTest.php +++ /dev/null @@ -1,48 +0,0 @@ -=')) { - $this->markTestSkipped('Skipping test mcrypt is deprecated from 7.1'); - } - - if (!function_exists('mcrypt_create_iv')) { - $this->markTestSkipped( - 'Mcrypt must be installed to test mcrypt_create_iv().' - ); - } - - $prsg = new McryptPseudoRandomStringGenerator(); - $randomString = $prsg->getPseudoRandomString(10); - - $this->assertEquals(1, preg_match('/^([0-9a-f]+)$/', $randomString)); - $this->assertEquals(10, mb_strlen($randomString)); - } -} diff --git a/tests/PseudoRandomString/OpenSslPseudoRandomStringGeneratorTest.php b/tests/PseudoRandomString/OpenSslPseudoRandomStringGeneratorTest.php deleted file mode 100644 index 3ab4edc93..000000000 --- a/tests/PseudoRandomString/OpenSslPseudoRandomStringGeneratorTest.php +++ /dev/null @@ -1,44 +0,0 @@ -markTestSkipped( - 'The OpenSSL extension must be enabled to test openssl_random_pseudo_bytes().' - ); - } - - $prsg = new OpenSslPseudoRandomStringGenerator(); - $randomString = $prsg->getPseudoRandomString(10); - - $this->assertEquals(1, preg_match('/^([0-9a-f]+)$/', $randomString)); - $this->assertEquals(10, mb_strlen($randomString)); - } -} diff --git a/tests/PseudoRandomString/PseudoRandomStringFactoryTest.php b/tests/PseudoRandomString/PseudoRandomStringFactoryTest.php deleted file mode 100644 index 9dc679e66..000000000 --- a/tests/PseudoRandomString/PseudoRandomStringFactoryTest.php +++ /dev/null @@ -1,71 +0,0 @@ -assertInstanceOf(self::COMMON_INTERFACE, $pseudoRandomStringGenerator); - $this->assertInstanceOf($expected, $pseudoRandomStringGenerator); - } - - /** - * @return array - */ - public function csprngProvider() - { - $providers = [ - [null, self::COMMON_INTERFACE], - ]; - if (function_exists('random_bytes')) { - $providers[] = ['random_bytes', self::COMMON_NAMESPACE . 'RandomBytesPseudoRandomStringGenerator']; - } - if (function_exists('mcrypt_create_iv')) { - $providers[] = ['mcrypt', self::COMMON_NAMESPACE . 'McryptPseudoRandomStringGenerator']; - } - if (function_exists('openssl_random_pseudo_bytes')) { - $providers[] = ['openssl', self::COMMON_NAMESPACE . 'OpenSslPseudoRandomStringGenerator']; - } - if (!ini_get('open_basedir') && is_readable('/dev/urandom')) { - $providers[] = ['urandom', self::COMMON_NAMESPACE . 'UrandomPseudoRandomStringGenerator']; - } - - return $providers; - } -} diff --git a/tests/PseudoRandomString/PseudoRandomStringGeneratorTraitTest.php b/tests/PseudoRandomString/PseudoRandomStringGeneratorTraitTest.php deleted file mode 100644 index 16165d98c..000000000 --- a/tests/PseudoRandomString/PseudoRandomStringGeneratorTraitTest.php +++ /dev/null @@ -1,47 +0,0 @@ -validateLength('foo_len'); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testALengthThatIsNotAtLeastOneCharacterWillThrow() - { - $prsg = new MyFooBarPseudoRandomStringGenerator(); - $prsg->validateLength(0); - } -} diff --git a/tests/PseudoRandomString/RandomBytesPseudoRandomStringGeneratorTest.php b/tests/PseudoRandomString/RandomBytesPseudoRandomStringGeneratorTest.php deleted file mode 100644 index 61f2a46a2..000000000 --- a/tests/PseudoRandomString/RandomBytesPseudoRandomStringGeneratorTest.php +++ /dev/null @@ -1,44 +0,0 @@ -markTestSkipped( - 'Must have PHP 7 or paragonie/random_compat installed to test random_bytes().' - ); - } - - $csprng = new RandomBytesPseudoRandomStringGenerator; - $randomString = $csprng->getPseudoRandomString(10); - - $this->assertEquals(1, preg_match('/^([0-9a-f]+)$/', $randomString)); - $this->assertEquals(10, strlen($randomString)); - } -} diff --git a/tests/PseudoRandomString/UrandomPseudoRandomStringGeneratorTest.php b/tests/PseudoRandomString/UrandomPseudoRandomStringGeneratorTest.php deleted file mode 100644 index e67136fe2..000000000 --- a/tests/PseudoRandomString/UrandomPseudoRandomStringGeneratorTest.php +++ /dev/null @@ -1,50 +0,0 @@ -markTestSkipped( - 'Cannot test /dev/urandom generator due to open_basedir constraint.' - ); - } - - if (!is_readable('/dev/urandom')) { - $this->markTestSkipped( - '/dev/urandom not found or is not readable.' - ); - } - - $prsg = new UrandomPseudoRandomStringGenerator(); - $randomString = $prsg->getPseudoRandomString(10); - - $this->assertEquals(1, preg_match('/^([0-9a-f]+)$/', $randomString)); - $this->assertEquals(10, mb_strlen($randomString)); - } -} diff --git a/tests/RequestTest.php b/tests/RequestTest.php new file mode 100644 index 000000000..8eda7ed76 --- /dev/null +++ b/tests/RequestTest.php @@ -0,0 +1,205 @@ +expectException(\Facebook\Exceptions\FacebookSDKException::class); + $app = new Application('123', 'foo_secret'); + $request = new Request($app); + + $request->validateAccessToken(); + } + + public function testAMissingMethodWillThrow(): void + { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $app = new Application('123', 'foo_secret'); + $request = new Request($app); + + $request->validateMethod(); + } + + public function testAnInvalidMethodWillThrow(): void + { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $app = new Application('123', 'foo_secret'); + $request = new Request($app, 'foo_token', 'FOO'); + + $request->validateMethod(); + } + + public function testGetHeadersWillAutoAppendETag(): void + { + $app = new Application('123', 'foo_secret'); + $request = new Request($app, null, 'GET', '/foo', [], 'fooETag'); + + $headers = $request->getHeaders(); + + $expectedHeaders = Request::getDefaultHeaders(); + $expectedHeaders['If-None-Match'] = 'fooETag'; + + static::assertEquals($expectedHeaders, $headers); + } + + public function testGetParamsWillAutoAppendAccessTokenAndAppSecretProof(): void + { + $app = new Application('123', 'foo_secret'); + $request = new Request($app, 'foo_token', 'POST', '/foo', ['foo' => 'bar']); + + $params = $request->getParams(); + + static::assertEquals([ + 'foo' => 'bar', + 'access_token' => 'foo_token', + 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', + ], $params); + } + + public function testAnAccessTokenCanBeSetFromTheParams(): void + { + $app = new Application('123', 'foo_secret'); + $request = new Request($app, null, 'POST', '/me', ['access_token' => 'bar_token']); + + $accessToken = $request->getAccessToken(); + + static::assertEquals('bar_token', $accessToken); + } + + public function testAccessTokenConflictsWillThrow(): void + { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); + $app = new Application('123', 'foo_secret'); + new Request($app, 'foo_token', 'POST', '/me', ['access_token' => 'bar_token']); + } + + public function testAProperUrlWillBeGenerated(): void + { + $app = new Application('123', 'foo_secret'); + $getRequest = new Request($app, 'foo_token', 'GET', '/foo', ['foo' => 'bar']); + + $getUrl = $getRequest->getUrl(); + $expectedParams = 'foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9'; + $expectedUrl = '/foo?' . $expectedParams; + + static::assertEquals($expectedUrl, $getUrl); + + $postRequest = new Request($app, 'foo_token', 'POST', '/bar', ['foo' => 'bar']); + + $postUrl = $postRequest->getUrl(); + $expectedUrl = '/bar'; + + static::assertEquals($expectedUrl, $postUrl); + } + + public function testAuthenticationParamsAreStrippedAndReapplied(): void + { + $app = new Application('123', 'foo_secret'); + + $request = new Request( + $app, + 'foo_token', + 'GET', + '/foo', + [ + 'access_token' => 'foo_token', + 'appsecret_proof' => 'bar_app_secret', + 'bar' => 'baz', + ] + ); + + $url = $request->getUrl(); + + $expectedParams = 'bar=baz&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9'; + $expectedUrl = '/foo?' . $expectedParams; + static::assertEquals($expectedUrl, $url); + + $params = $request->getParams(); + + $expectedParams = [ + 'access_token' => 'foo_token', + 'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', + 'bar' => 'baz', + ]; + static::assertEquals($expectedParams, $params); + } + + public function testAFileCanBeAddedToParams(): void + { + $myFile = new File(__DIR__ . '/foo.txt'); + $params = [ + 'name' => 'Foo Bar', + 'source' => $myFile, + ]; + $app = new Application('123', 'foo_secret'); + $request = new Request($app, 'foo_token', 'POST', '/foo/photos', $params); + + $actualParams = $request->getParams(); + + static::assertTrue($request->containsFileUploads()); + static::assertFalse($request->containsVideoUploads()); + static::assertTrue(!isset($actualParams['source'])); + static::assertEquals('Foo Bar', $actualParams['name']); + } + + public function testAVideoCanBeAddedToParams(): void + { + $myFile = new Video(__DIR__ . '/foo.txt'); + $params = [ + 'name' => 'Foo Bar', + 'source' => $myFile, + ]; + $app = new Application('123', 'foo_secret'); + $request = new Request($app, 'foo_token', 'POST', '/foo/videos', $params); + + $actualParams = $request->getParams(); + + static::assertTrue($request->containsFileUploads()); + static::assertTrue($request->containsVideoUploads()); + static::assertTrue(!isset($actualParams['source'])); + static::assertEquals('Foo Bar', $actualParams['name']); + } +} diff --git a/tests/FacebookResponseTest.php b/tests/ResponseTest.php old mode 100755 new mode 100644 similarity index 55% rename from tests/FacebookResponseTest.php rename to tests/ResponseTest.php index be37cbde3..45dab7e91 --- a/tests/FacebookResponseTest.php +++ b/tests/ResponseTest.php @@ -1,4 +1,6 @@ request = new FacebookRequest( + $app = new Application('123', 'foo_secret'); + $this->request = new Request( $app, 'foo_token', 'GET', @@ -48,74 +56,74 @@ protected function setUp() ); } - public function testAnETagCanBeProperlyAccessed() + public function testAnETagCanBeProperlyAccessed(): void { - $response = new FacebookResponse($this->request, '', 200, ['ETag' => 'foo_tag']); + $response = new Response($this->request, '', 200, ['ETag' => 'foo_tag']); $eTag = $response->getETag(); - $this->assertEquals('foo_tag', $eTag); + static::assertEquals('foo_tag', $eTag); } - public function testAProperAppSecretProofCanBeGenerated() + public function testAProperAppSecretProofCanBeGenerated(): void { - $response = new FacebookResponse($this->request); + $response = new Response($this->request); $appSecretProof = $response->getAppSecretProof(); - $this->assertEquals('df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', $appSecretProof); + static::assertEquals('df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9', $appSecretProof); } - public function testASuccessfulJsonResponseWillBeDecodedToAGraphNode() + public function testASuccessfulJsonResponseWillBeDecodedToAGraphNode(): void { $graphResponseJson = '{"id":"123","name":"Foo"}'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); + $response = new Response($this->request, $graphResponseJson, 200); $decodedResponse = $response->getDecodedBody(); $graphNode = $response->getGraphNode(); - $this->assertFalse($response->isError(), 'Did not expect Response to return an error.'); - $this->assertEquals([ + static::assertFalse($response->isError(), 'Did not expect Response to return an error.'); + static::assertEquals([ 'id' => '123', 'name' => 'Foo', ], $decodedResponse); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphNode); + static::assertInstanceOf(GraphNode::class, $graphNode); } - public function testASuccessfulJsonResponseWillBeDecodedToAGraphEdge() + public function testASuccessfulJsonResponseWillBeDecodedToAGraphEdge(): void { $graphResponseJson = '{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}'; - $response = new FacebookResponse($this->request, $graphResponseJson, 200); + $response = new Response($this->request, $graphResponseJson, 200); $graphEdge = $response->getGraphEdge(); - $this->assertFalse($response->isError(), 'Did not expect Response to return an error.'); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphEdge[0]); - $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphEdge[1]); + static::assertFalse($response->isError(), 'Did not expect Response to return an error.'); + static::assertInstanceOf(GraphNode::class, $graphEdge[0]); + static::assertInstanceOf(GraphNode::class, $graphEdge[1]); } - public function testASuccessfulUrlEncodedKeyValuePairResponseWillBeDecoded() + public function testASuccessfulUrlEncodedKeyValuePairResponseWillBeDecoded(): void { $graphResponseKeyValuePairs = 'id=123&name=Foo'; - $response = new FacebookResponse($this->request, $graphResponseKeyValuePairs, 200); + $response = new Response($this->request, $graphResponseKeyValuePairs, 200); $decodedResponse = $response->getDecodedBody(); - $this->assertFalse($response->isError(), 'Did not expect Response to return an error.'); - $this->assertEquals([ + static::assertFalse($response->isError(), 'Did not expect Response to return an error.'); + static::assertEquals([ 'id' => '123', 'name' => 'Foo', ], $decodedResponse); } - public function testErrorStatusCanBeCheckedWhenAnErrorResponseIsReturned() + public function testErrorStatusCanBeCheckedWhenAnErrorResponseIsReturned(): void { $graphResponse = '{"error":{"message":"Foo error.","type":"OAuthException","code":190,"error_subcode":463}}'; - $response = new FacebookResponse($this->request, $graphResponse, 401); + $response = new Response($this->request, $graphResponse, 401); $exception = $response->getThrownException(); - $this->assertTrue($response->isError(), 'Expected Response to return an error.'); - $this->assertInstanceOf('Facebook\Exceptions\FacebookResponseException', $exception); + static::assertTrue($response->isError(), 'Expected Response to return an error.'); + static::assertInstanceOf(FacebookResponseException::class, $exception); } } diff --git a/tests/SignedRequestTest.php b/tests/SignedRequestTest.php index 119f27ce1..3c59a3b63 100644 --- a/tests/SignedRequestTest.php +++ b/tests/SignedRequestTest.php @@ -1,4 +1,6 @@ 'foo_token', 'algorithm' => 'HMAC-SHA256', 'issued_at' => 321, @@ -46,12 +53,12 @@ class SignedRequestTest extends \PHPUnit_Framework_TestCase 'foo' => 'bar', ]; - protected function setUp() + protected function setUp(): void { - $this->app = new FacebookApp('123', 'foo_app_secret'); + $this->app = new Application('123', 'foo_app_secret'); } - public function testAValidSignedRequestCanBeCreated() + public function testAValidSignedRequestCanBeCreated(): void { $sr = new SignedRequest($this->app); $rawSignedRequest = $sr->make($this->payloadData); @@ -60,55 +67,47 @@ public function testAValidSignedRequestCanBeCreated() $payload = $srTwo->getPayload(); $expectedRawSignedRequest = $this->rawSignature . '.' . $this->rawPayload; - $this->assertEquals($expectedRawSignedRequest, $rawSignedRequest); - $this->assertEquals($this->payloadData, $payload); + static::assertEquals($expectedRawSignedRequest, $rawSignedRequest); + static::assertEquals($this->payloadData, $payload); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testInvalidSignedRequestsWillFailFormattingValidation() + public function testInvalidSignedRequestsWillFailFormattingValidation(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); new SignedRequest($this->app, 'invalid_signed_request'); } - public function testBase64EncodingIsUrlSafe() + public function testBase64EncodingIsUrlSafe(): void { $sr = new SignedRequest($this->app); $encodedData = $sr->base64UrlEncode('aijkoprstADIJKLOPQTUVX1256!)]-:;"<>?.|~'); - $this->assertEquals('YWlqa29wcnN0QURJSktMT1BRVFVWWDEyNTYhKV0tOjsiPD4_Lnx-', $encodedData); + static::assertEquals('YWlqa29wcnN0QURJSktMT1BRVFVWWDEyNTYhKV0tOjsiPD4_Lnx-', $encodedData); } - public function testAUrlSafeBase64EncodedStringCanBeDecoded() + public function testAUrlSafeBase64EncodedStringCanBeDecoded(): void { $sr = new SignedRequest($this->app); $decodedData = $sr->base64UrlDecode('YWlqa29wcnN0QURJSktMT1BRVFVWWDEyNTYhKV0tOjsiPD4/Lnx+'); - $this->assertEquals('aijkoprstADIJKLOPQTUVX1256!)]-:;"<>?.|~', $decodedData); + static::assertEquals('aijkoprstADIJKLOPQTUVX1256!)]-:;"<>?.|~', $decodedData); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ - public function testAnImproperlyEncodedSignatureWillThrowAnException() + public function testAnImproperlyEncodedSignatureWillThrowAnException(): void { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); new SignedRequest($this->app, 'foo_sig.' . $this->rawPayload); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testAnImproperlyEncodedPayloadWillThrowAnException() { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); new SignedRequest($this->app, $this->rawSignature . '.foo_payload'); } - /** - * @expectedException \Facebook\Exceptions\FacebookSDKException - */ public function testNonApprovedAlgorithmsWillThrowAnException() { + $this->expectException(\Facebook\Exceptions\FacebookSDKException::class); $signedRequestData = $this->payloadData; $signedRequestData['algorithm'] = 'FOO-ALGORITHM'; @@ -118,22 +117,22 @@ public function testNonApprovedAlgorithmsWillThrowAnException() new SignedRequest($this->app, $rawSignedRequest); } - public function testAsRawSignedRequestCanBeValidatedAndDecoded() + public function testAsRawSignedRequestCanBeValidatedAndDecoded(): void { $rawSignedRequest = $this->rawSignature . '.' . $this->rawPayload; $sr = new SignedRequest($this->app, $rawSignedRequest); - $this->assertEquals($this->payloadData, $sr->getPayload()); + static::assertEquals($this->payloadData, $sr->getPayload()); } - public function testARawSignedRequestCanBeValidatedAndDecoded() + public function testARawSignedRequestCanBeValidatedAndDecoded(): void { $rawSignedRequest = $this->rawSignature . '.' . $this->rawPayload; $sr = new SignedRequest($this->app, $rawSignedRequest); - $this->assertEquals($sr->getPayload(), $this->payloadData); - $this->assertEquals($sr->getRawSignedRequest(), $rawSignedRequest); - $this->assertEquals(123, $sr->getUserId()); - $this->assertTrue($sr->hasOAuthData()); + static::assertEquals($sr->getPayload(), $this->payloadData); + static::assertEquals($sr->getRawSignedRequest(), $rawSignedRequest); + static::assertEquals(123, $sr->getUserId()); + static::assertTrue($sr->hasOAuthData()); } } diff --git a/tests/Url/FacebookUrlDetectionHandlerTest.php b/tests/Url/UrlDetectionHandlerTest.php similarity index 72% rename from tests/Url/FacebookUrlDetectionHandlerTest.php rename to tests/Url/UrlDetectionHandlerTest.php index b623c0524..1a7340ed1 100644 --- a/tests/Url/FacebookUrlDetectionHandlerTest.php +++ b/tests/Url/UrlDetectionHandlerTest.php @@ -1,4 +1,6 @@ 'foo.bar', @@ -35,13 +41,13 @@ public function testProperlyGeneratesUrlFromCommonScenario() 'REQUEST_URI' => '/baz?foo=123', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('http://foo.bar/baz?foo=123', $currentUri); + static::assertEquals('http://foo.bar/baz?foo=123', $currentUri); } - public function testProperlyGeneratesSecureUrlFromCommonScenario() + public function testProperlyGeneratesSecureUrlFromCommonScenario(): void { $_SERVER = [ 'HTTP_HOST' => 'foo.bar', @@ -49,13 +55,13 @@ public function testProperlyGeneratesSecureUrlFromCommonScenario() 'REQUEST_URI' => '/baz?foo=123', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('https://foo.bar/baz?foo=123', $currentUri); + static::assertEquals('https://foo.bar/baz?foo=123', $currentUri); } - public function testProperlyGeneratesUrlFromProxy() + public function testProperlyGeneratesUrlFromProxy(): void { $_SERVER = [ 'HTTP_X_FORWARDED_PORT' => '80', @@ -65,13 +71,13 @@ public function testProperlyGeneratesUrlFromProxy() 'REQUEST_URI' => '/baz?foo=123', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('http://foo.bar/baz?foo=123', $currentUri); + static::assertEquals('http://foo.bar/baz?foo=123', $currentUri); } - public function testProperlyGeneratesSecureUrlFromProxy() + public function testProperlyGeneratesSecureUrlFromProxy(): void { $_SERVER = [ 'HTTP_X_FORWARDED_PORT' => '443', @@ -81,13 +87,13 @@ public function testProperlyGeneratesSecureUrlFromProxy() 'REQUEST_URI' => '/baz?foo=123', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('https://foo.bar/baz?foo=123', $currentUri); + static::assertEquals('https://foo.bar/baz?foo=123', $currentUri); } - public function testProperlyGeneratesUrlWithCustomPort() + public function testProperlyGeneratesUrlWithCustomPort(): void { $_SERVER = [ 'HTTP_HOST' => 'foo.bar', @@ -95,13 +101,13 @@ public function testProperlyGeneratesUrlWithCustomPort() 'REQUEST_URI' => '/foo.php', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('http://foo.bar:1337/foo.php', $currentUri); + static::assertEquals('http://foo.bar:1337/foo.php', $currentUri); } - public function testProperlyGeneratesSecureUrlWithCustomPort() + public function testProperlyGeneratesSecureUrlWithCustomPort(): void { $_SERVER = [ 'HTTP_HOST' => 'foo.bar', @@ -110,13 +116,13 @@ public function testProperlyGeneratesSecureUrlWithCustomPort() 'HTTPS' => 'On', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('https://foo.bar:1337/foo.php', $currentUri); + static::assertEquals('https://foo.bar:1337/foo.php', $currentUri); } - public function testProperlyGeneratesUrlWithCustomPortFromProxy() + public function testProperlyGeneratesUrlWithCustomPortFromProxy(): void { $_SERVER = [ 'HTTP_X_FORWARDED_PORT' => '8888', @@ -126,9 +132,9 @@ public function testProperlyGeneratesUrlWithCustomPortFromProxy() 'REQUEST_URI' => '/foo.php', ]; - $urlHandler = new FacebookUrlDetectionHandler(); + $urlHandler = new UrlDetectionHandler(); $currentUri = $urlHandler->getCurrentUrl(); - $this->assertEquals('http://foo.bar:8888/foo.php', $currentUri); + static::assertEquals('http://foo.bar:8888/foo.php', $currentUri); } } diff --git a/tests/Url/FacebookUrlManipulatorTest.php b/tests/Url/UrlManipulatorTest.php similarity index 78% rename from tests/Url/FacebookUrlManipulatorTest.php rename to tests/Url/UrlManipulatorTest.php index d92a2857a..2b15b7ecf 100644 --- a/tests/Url/FacebookUrlManipulatorTest.php +++ b/tests/Url/UrlManipulatorTest.php @@ -1,4 +1,6 @@ assertEquals($expectedCleanUrl, $currentUri); + static::assertEquals($expectedCleanUrl, $currentUri); } - public function provideUris() + public function provideUris(): array { return [ [ @@ -90,19 +96,18 @@ public function provideUris() ]; } - public function testGracefullyHandlesUrlAppending() + public function testGracefullyHandlesUrlAppending(): void { $params = []; $url = 'https://www.foo.com/'; $processed_url = FacebookUrlManipulator::appendParamsToUrl($url, $params); - $this->assertEquals('https://www.foo.com/', $processed_url); + static::assertEquals('https://www.foo.com/', $processed_url); $params = [ 'access_token' => 'foo', ]; - $url = 'https://www.foo.com/'; $processed_url = FacebookUrlManipulator::appendParamsToUrl($url, $params); - $this->assertEquals('https://www.foo.com/?access_token=foo', $processed_url); + static::assertEquals('https://www.foo.com/?access_token=foo', $processed_url); $params = [ 'access_token' => 'foo', @@ -110,17 +115,17 @@ public function testGracefullyHandlesUrlAppending() ]; $url = 'https://www.foo.com/?foo=bar'; $processed_url = FacebookUrlManipulator::appendParamsToUrl($url, $params); - $this->assertEquals('https://www.foo.com/?access_token=foo&bar=baz&foo=bar', $processed_url); + static::assertEquals('https://www.foo.com/?access_token=foo&bar=baz&foo=bar', $processed_url); $params = [ 'access_token' => 'foo', ]; $url = 'https://www.foo.com/?foo=bar&access_token=bar'; $processed_url = FacebookUrlManipulator::appendParamsToUrl($url, $params); - $this->assertEquals('https://www.foo.com/?access_token=bar&foo=bar', $processed_url); + static::assertEquals('https://www.foo.com/?access_token=bar&foo=bar', $processed_url); } - public function testSlashesAreProperlyPrepended() + public function testSlashesAreProperlyPrepended(): void { $slashTestOne = FacebookUrlManipulator::forceSlashPrefix('foo'); $slashTestTwo = FacebookUrlManipulator::forceSlashPrefix('/foo'); @@ -129,15 +134,15 @@ public function testSlashesAreProperlyPrepended() $slashTestFive = FacebookUrlManipulator::forceSlashPrefix(null); $slashTestSix = FacebookUrlManipulator::forceSlashPrefix(''); - $this->assertEquals('/foo', $slashTestOne); - $this->assertEquals('/foo', $slashTestTwo); - $this->assertEquals('/foo/bar', $slashTestThree); - $this->assertEquals('/foo/bar', $slashTestFour); - $this->assertEquals(null, $slashTestFive); - $this->assertEquals('', $slashTestSix); + static::assertEquals('/foo', $slashTestOne); + static::assertEquals('/foo', $slashTestTwo); + static::assertEquals('/foo/bar', $slashTestThree); + static::assertEquals('/foo/bar', $slashTestFour); + static::assertEquals(null, $slashTestFive); + static::assertEquals('', $slashTestSix); } - public function testParamsCanBeReturnedAsArray() + public function testParamsCanBeReturnedAsArray(): void { $paramsOne = FacebookUrlManipulator::getParamsAsArray('/foo'); $paramsTwo = FacebookUrlManipulator::getParamsAsArray('/foo?one=1&two=2'); @@ -145,11 +150,11 @@ public function testParamsCanBeReturnedAsArray() $paramsFour = FacebookUrlManipulator::getParamsAsArray('https://www.foo.com/?'); $paramsFive = FacebookUrlManipulator::getParamsAsArray('https://www.foo.com/?foo=bar'); - $this->assertEquals([], $paramsOne); - $this->assertEquals(['one' => '1', 'two' => '2'], $paramsTwo); - $this->assertEquals([], $paramsThree); - $this->assertEquals([], $paramsFour); - $this->assertEquals(['foo' => 'bar'], $paramsFive); + static::assertEquals([], $paramsOne); + static::assertEquals(['one' => '1', 'two' => '2'], $paramsTwo); + static::assertEquals([], $paramsThree); + static::assertEquals([], $paramsFour); + static::assertEquals(['foo' => 'bar'], $paramsFive); } /** @@ -159,10 +164,10 @@ public function testParamsCanBeMergedOntoUrlProperly($urlOne, $urlTwo, $expected { $result = FacebookUrlManipulator::mergeUrlParams($urlOne, $urlTwo); - $this->assertEquals($result, $expected); + static::assertEquals($result, $expected); } - public function provideMergableEndpoints() + public function provideMergableEndpoints(): array { return [ [ @@ -188,30 +193,30 @@ public function provideMergableEndpoints() ]; } - public function testGraphUrlsCanBeTrimmed() + public function testGraphUrlsCanBeTrimmed(): void { $fullGraphUrl = 'https://graph.facebook.com/'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/', $baseGraphUrl); + static::assertEquals('/', $baseGraphUrl); $fullGraphUrl = 'https://graph.facebook.com/v1.0/'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/', $baseGraphUrl); + static::assertEquals('/', $baseGraphUrl); $fullGraphUrl = 'https://graph.facebook.com/me'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/me', $baseGraphUrl); + static::assertEquals('/me', $baseGraphUrl); $fullGraphUrl = 'https://graph.beta.facebook.com/me'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/me', $baseGraphUrl); + static::assertEquals('/me', $baseGraphUrl); $fullGraphUrl = 'https://whatever-they-want.facebook.com/v2.1/me'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/me', $baseGraphUrl); + static::assertEquals('/me', $baseGraphUrl); $fullGraphUrl = 'https://graph.facebook.com/v5.301/1233?foo=bar'; $baseGraphUrl = FacebookUrlManipulator::baseGraphUrlEndpoint($fullGraphUrl); - $this->assertEquals('/1233?foo=bar', $baseGraphUrl); + static::assertEquals('/1233?foo=bar', $baseGraphUrl); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 49fba281d..69e15f62c 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,4 +1,6 @@