From fda70746212d6d43c225e2d8f903f84fc49c6fc6 Mon Sep 17 00:00:00 2001 From: Chris Tankersley Date: Fri, 10 Oct 2025 15:22:53 -0400 Subject: [PATCH 1/2] chore: Drop unsupported PHP versions and rector to 8.1 --- .github/workflows/build.yml | 2 +- .gitignore | 3 +- composer.json | 10 +- rector.php | 46 ++ rector.yaml | 5 - sample/Archiving/web/index.php | 78 +-- sample/HelloWorld/web/index.php | 24 +- sample/SipCall/web/index.php | 47 +- src/OpenTok/Archive.php | 80 +--- src/OpenTok/ArchiveList.php | 20 +- src/OpenTok/Broadcast.php | 94 +--- src/OpenTok/Connection.php | 21 +- src/OpenTok/ConnectionList.php | 29 +- .../Exception/AuthenticationException.php | 2 +- .../SignalNetworkConnectionException.php | 5 +- src/OpenTok/Layout.php | 55 +-- src/OpenTok/OpenTok.php | 323 +++++-------- src/OpenTok/Render.php | 20 +- src/OpenTok/Session.php | 15 +- src/OpenTok/SipCall.php | 16 +- src/OpenTok/Stream.php | 20 +- src/OpenTok/StreamList.php | 14 +- src/OpenTok/Util/BasicEnum.php | 12 +- src/OpenTok/Util/Client.php | 224 ++++----- src/OpenTok/Util/Validators.php | 156 +++--- tests/OpenTokTest/ArchiveTest.php | 121 +---- tests/OpenTokTest/BroadcastTest.php | 23 +- tests/OpenTokTest/LayoutTest.php | 20 +- tests/OpenTokTest/OpenTokTest.php | 445 ++++++++---------- tests/OpenTokTest/RenderTest.php | 4 +- tests/OpenTokTest/SessionTest.php | 52 +- tests/OpenTokTest/TestHelpers.php | 35 +- tests/OpenTokTest/Util/ClientTest.php | 10 +- .../OpenTokTest/Validators/ValidatorsTest.php | 7 +- 34 files changed, 843 insertions(+), 1195 deletions(-) create mode 100644 rector.php delete mode 100644 rector.yaml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ceb80c84..4f41c29e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,7 +6,7 @@ jobs: - ubuntu-latest strategy: matrix: - php: ['8.1', '8.2', '8.3', '8.4'] + php: ['8.1', '8.2', '8.3', '8.4', '8.5'] steps: - name: Configure Git if: ${{ matrix.os == 'windows-latest' }} diff --git a/.gitignore b/.gitignore index 8a74bab0..c7084b92 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ docs/ .phpdoc/ phpDocumentor* .phpunit.result.cache -.idea/* \ No newline at end of file +.idea/* +var/ \ No newline at end of file diff --git a/composer.json b/composer.json index 5f5c1db4..1cd7b8d3 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "issues": "https://github.com/opentok/Opentok-PHP-SDK/issues" }, "require": { - "php": "^7.2|^8.0", + "php": "^8.1|^8.2|^8.3|^8.4|^8.5", "ext-xml": "*", "johnstevenson/json-works": "~1.1", "firebase/php-jwt": "^6.11", @@ -37,14 +37,14 @@ "vonage/jwt": "^0.5.1" }, "require-dev": { - "phpunit/phpunit": "^7.4|^8.0", + "phpunit/phpunit": "^8.0", "php-http/mock-client": "^1.4", "helmich/phpunit-json-assert": "^3.0.0", "squizlabs/php_codesniffer": "^3.1", "php-http/guzzle7-adapter": "^1.0", - "phpstan/phpstan": "^0.12", - "rector/rector": "^0.8", - "phing/phing": "~2.16.0" + "phpstan/phpstan": "^1.10", + "phing/phing": "~2.16.0", + "rector/rector": "^1.0" }, "scripts": { "phpstan": "./vendor/bin/phpstan", diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..a9b0060c --- /dev/null +++ b/rector.php @@ -0,0 +1,46 @@ +paths([ + __DIR__ . '/src', + __DIR__ . '/examples', + __DIR__ . '/sample', + __DIR__ . '/tests', + ]); + + // Define a clear cache directory + $rectorConfig->cacheDirectory(__DIR__ . '/var/cache/rector'); + + // Here we can define what rule sets we want to apply + $rectorConfig->sets([ + LevelSetList::UP_TO_PHP_81, + SetList::CODE_QUALITY, + SetList::DEAD_CODE, + SetList::PRIVATIZATION, + SetList::TYPE_DECLARATION, + SetList::EARLY_RETURN, + ]); + + // Skip certain files or directories if needed + $rectorConfig->skip([ + __DIR__ . '/vendor', + __DIR__ . '/var', + __DIR__ . '/tools', + ]); + + // Import names (classes, functions) automatically + $rectorConfig->importNames(); + $rectorConfig->importShortClasses(); + + // Register file extensions + $rectorConfig->fileExtensions(['php']); + + // Parallel processing - adjust number based on your CPU cores + $rectorConfig->parallel(); +}; \ No newline at end of file diff --git a/rector.yaml b/rector.yaml deleted file mode 100644 index e0f26cfc..00000000 --- a/rector.yaml +++ /dev/null @@ -1,5 +0,0 @@ -parameters: - php_version_features: '7.1' - import_short_classes: false - sets: - - dead-code \ No newline at end of file diff --git a/sample/Archiving/web/index.php b/sample/Archiving/web/index.php index ec962f26..9aff6751 100644 --- a/sample/Archiving/web/index.php +++ b/sample/Archiving/web/index.php @@ -1,5 +1,7 @@ __DIR__ . '/../templates', - 'view' => new \Slim\Views\Twig(), -)); +$app = new Slim(['templates.path' => __DIR__ . '/../templates', 'view' => new Twig()]); // Intialize a cache, store it in the app container -$app->container->singleton('cache', function () { - return new Cache(); -}); +$app->container->singleton('cache', fn(): Cache => new Cache()); // Initialize OpenTok instance, store it in the app contianer -$app->container->singleton('opentok', function () { - return new OpenTok(getenv('API_KEY'), getenv('API_SECRET')); -}); +$app->container->singleton('opentok', fn(): OpenTok => new OpenTok(getenv('API_KEY'), getenv('API_SECRET'))); // Store the API Key in the app container $app->apiKey = getenv('API_KEY'); // If a sessionId has already been created, retrieve it from the cache -$sessionId = $app->cache->getOrCreate('sessionId', array(), function () use ($app) { +$sessionId = $app->cache->getOrCreate('sessionId', [], function () use ($app) { // If the sessionId hasn't been created, create it now and store it - $session = $app->opentok->createSession(array( - 'mediaMode' => MediaMode::ROUTED - )); + $session = $app->opentok->createSession(['mediaMode' => MediaMode::ROUTED]); return $session->getSessionId(); }); // Configure routes -$app->get('/', function () use ($app) { +$app->get('/', function () use ($app): void { $app->render('index.html'); }); -$app->get('/host', function () use ($app, $sessionId) { +$app->get('/host', function () use ($app, $sessionId): void { - $token = $app->opentok->generateToken($sessionId, array( - 'role' => Role::MODERATOR - )); + $token = $app->opentok->generateToken($sessionId, ['role' => Role::MODERATOR]); - $app->render('host.html', array( - 'apiKey' => $app->apiKey, - 'sessionId' => $sessionId, - 'token' => $token - )); + $app->render('host.html', ['apiKey' => $app->apiKey, 'sessionId' => $sessionId, 'token' => $token]); }); -$app->get('/participant', function () use ($app, $sessionId) { +$app->get('/participant', function () use ($app, $sessionId): void { - $token = $app->opentok->generateToken($sessionId, array( - 'role' => Role::MODERATOR - )); + $token = $app->opentok->generateToken($sessionId, ['role' => Role::MODERATOR]); - $app->render('participant.html', array( - 'apiKey' => $app->apiKey, - 'sessionId' => $sessionId, - 'token' => $token - )); + $app->render('participant.html', ['apiKey' => $app->apiKey, 'sessionId' => $sessionId, 'token' => $token]); }); -$app->get('/history', function () use ($app) { +$app->get('/history', function () use ($app): void { $page = intval($app->request->get('page')); - if (empty($page)) { + if ($page === 0) { $page = 1; } @@ -101,42 +82,31 @@ $archives = $app->opentok->listArchives($offset, 5); - $toArray = function ($archive) { - return $archive->toArray(); - }; + $toArray = fn($archive) => $archive->toArray(); - $app->render('history.html', array( - 'archives' => array_map($toArray, $archives->getItems()), - 'showPrevious' => $page > 1 ? '/history?page=' . ($page - 1) : null, - 'showNext' => $archives->totalCount() > $offset + 5 ? '/history?page=' . ($page + 1) : null - )); + $app->render('history.html', ['archives' => array_map($toArray, $archives->getItems()), 'showPrevious' => $page > 1 ? '/history?page=' . ($page - 1) : null, 'showNext' => $archives->totalCount() > $offset + 5 ? '/history?page=' . ($page + 1) : null]); }); -$app->get('/download/:archiveId', function ($archiveId) use ($app) { +$app->get('/download/:archiveId', function ($archiveId) use ($app): void { $archive = $app->opentok->getArchive($archiveId); $app->redirect($archive->url); }); -$app->post('/start', function () use ($app, $sessionId) { +$app->post('/start', function () use ($app, $sessionId): void { - $archive = $app->opentok->startArchive($sessionId, array( - 'name' => "PHP Archiving Sample App", - 'hasAudio' => ($app->request->post('hasAudio') == 'on'), - 'hasVideo' => ($app->request->post('hasVideo') == 'on'), - 'outputMode' => ($app->request->post('outputMode') == 'composed' ? OutputMode::COMPOSED : OutputMode::INDIVIDUAL) - )); + $archive = $app->opentok->startArchive($sessionId, ['name' => "PHP Archiving Sample App", 'hasAudio' => ($app->request->post('hasAudio') == 'on'), 'hasVideo' => ($app->request->post('hasVideo') == 'on'), 'outputMode' => ($app->request->post('outputMode') == 'composed' ? OutputMode::COMPOSED : OutputMode::INDIVIDUAL)]); $app->response->headers->set('Content-Type', 'application/json'); echo $archive->toJson(); }); -$app->get('/stop/:archiveId', function ($archiveId) use ($app) { +$app->get('/stop/:archiveId', function ($archiveId) use ($app): void { $archive = $app->opentok->stopArchive($archiveId); $app->response->headers->set('Content-Type', 'application/json'); echo $archive->toJson(); }); -$app->get('/delete/:archiveId', function ($archiveId) use ($app) { +$app->get('/delete/:archiveId', function ($archiveId) use ($app): void { $app->opentok->deleteArchive($archiveId); $app->redirect('/history'); }); diff --git a/sample/HelloWorld/web/index.php b/sample/HelloWorld/web/index.php index 4cb16d99..1ef8153a 100644 --- a/sample/HelloWorld/web/index.php +++ b/sample/HelloWorld/web/index.php @@ -20,7 +20,7 @@ use OpenTok\OpenTok; // PHP CLI webserver compatibility, serving static files -$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); +$filename = __DIR__ . preg_replace('#(\?.*)$#', '', (string) $_SERVER['REQUEST_URI']); if (php_sapi_name() === 'cli-server' && is_file($filename)) { return false; } @@ -31,27 +31,21 @@ } // Initialize Slim application -$app = new Slim(array( - 'templates.path' => __DIR__ . '/../templates' -)); +$app = new Slim(['templates.path' => __DIR__ . '/../templates']); // Intialize a cache, store it in the app container -$app->container->singleton('cache', function () { - return new Cache(); -}); +$app->container->singleton('cache', fn(): Cache => new Cache()); // Initialize OpenTok instance, store it in the app contianer -$app->container->singleton('opentok', function () { - return new OpenTok(getenv('API_KEY'), getenv('API_SECRET')); -}); +$app->container->singleton('opentok', fn(): OpenTok => new OpenTok(getenv('API_KEY'), getenv('API_SECRET'))); // Store the API Key in the app container $app->apiKey = getenv('API_KEY'); // Configure routes -$app->get('/', function () use ($app) { +$app->get('/', function () use ($app): void { // If a sessionId has already been created, retrieve it from the cache - $sessionId = $app->cache->getOrCreate('sessionId', array(), function () use ($app) { + $sessionId = $app->cache->getOrCreate('sessionId', [], function () use ($app) { // If the sessionId hasn't been created, create it now and store it $session = $app->opentok->createSession(); return $session->getSessionId(); @@ -60,11 +54,7 @@ // Generate a fresh token for this client $token = $app->opentok->generateToken($sessionId); - $app->render('helloworld.php', array( - 'apiKey' => $app->apiKey, - 'sessionId' => $sessionId, - 'token' => $token - )); + $app->render('helloworld.php', ['apiKey' => $app->apiKey, 'sessionId' => $sessionId, 'token' => $token]); }); $app->run(); diff --git a/sample/SipCall/web/index.php b/sample/SipCall/web/index.php index b48078bc..762a77e6 100644 --- a/sample/SipCall/web/index.php +++ b/sample/SipCall/web/index.php @@ -21,7 +21,7 @@ use OpenTok\MediaMode; // PHP CLI webserver compatibility, serving static files -$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); +$filename = __DIR__ . preg_replace('#(\?.*)$#', '', (string) $_SERVER['REQUEST_URI']); if (php_sapi_name() === 'cli-server' && is_file($filename)) { return false; } @@ -32,62 +32,43 @@ } // Initialize Slim application -$app = new Slim(array( - 'templates.path' => __DIR__ . '/../templates' -)); +$app = new Slim(['templates.path' => __DIR__ . '/../templates']); // Intialize a cache, store it in the app container -$app->container->singleton('cache', function () { - return new Cache(); -}); +$app->container->singleton('cache', fn(): Cache => new Cache()); // Initialize OpenTok instance, store it in the app contianer -$app->container->singleton('opentok', function () { - return new OpenTok(getenv('API_KEY'), getenv('API_SECRET')); -}); +$app->container->singleton('opentok', fn(): OpenTok => new OpenTok(getenv('API_KEY'), getenv('API_SECRET'))); // Store the API Key in the app container $app->apiKey = getenv('API_KEY'); -$app->sip = array( - 'uri' => getenv('SIP_URI'), - 'username' => getenv('SIP_USERNAME'), - 'password' => getenv('SIP_PASSWORD'), - 'secure' => (getenv('SIP_SECURE') === 'true'), - 'from' => getenv('SIP_FROM'), -); +$app->sip = ['uri' => getenv('SIP_URI'), 'username' => getenv('SIP_USERNAME'), 'password' => getenv('SIP_PASSWORD'), 'secure' => (getenv('SIP_SECURE') === 'true'), 'from' => getenv('SIP_FROM')]; // Configure routes -$app->get('/', function () use ($app) { +$app->get('/', function () use ($app): void { // If a sessionId has already been created, retrieve it from the cache - $sessionId = $app->cache->getOrCreate('sessionId', array(), function () use ($app) { + $sessionId = $app->cache->getOrCreate('sessionId', [], function () use ($app) { // If the sessionId hasn't been created, create it now and store it - $session = $app->opentok->createSession(array('mediaMode' => MediaMode::ROUTED)); + $session = $app->opentok->createSession(['mediaMode' => MediaMode::ROUTED]); return $session->getSessionId(); }); // Generate a fresh token for this client - $token = $app->opentok->generateToken($sessionId, array('role' => 'moderator')); + $token = $app->opentok->generateToken($sessionId, ['role' => 'moderator']); - $app->render('index.php', array( - 'apiKey' => $app->apiKey, - 'sessionId' => $sessionId, - 'token' => $token - )); + $app->render('index.php', ['apiKey' => $app->apiKey, 'sessionId' => $sessionId, 'token' => $token]); }); -$app->post('/sip/start', function () use ($app) { +$app->post('/sip/start', function () use ($app): void { $sessionId = $app->request->post('sessionId'); // generate a token - $token = $app->opentok->generateToken($sessionId, array('data' => 'sip=true')); + $token = $app->opentok->generateToken($sessionId, ['data' => 'sip=true']); // create the options parameter - $options = array( - 'secure' => $app->sip['secure'], - 'from' => $app->sip['from'], - ); + $options = ['secure' => $app->sip['secure'], 'from' => $app->sip['from']]; if ($app->sip['username'] !== false) { - $options['auth'] = array('username' => $app->sip['username'], 'password' => $app->sip['password']); + $options['auth'] = ['username' => $app->sip['username'], 'password' => $app->sip['password']]; } // make the sip call diff --git a/src/OpenTok/Archive.php b/src/OpenTok/Archive.php index 7e07a472..916ceec5 100644 --- a/src/OpenTok/Archive.php +++ b/src/OpenTok/Archive.php @@ -2,6 +2,7 @@ namespace OpenTok; +use DomainException; use OpenTok\Util\Client; use OpenTok\Util\Validators; use OpenTok\Exception\InvalidArgumentException; @@ -107,7 +108,7 @@ class Archive /** @internal */ private $data; /** @internal */ - private $isDeleted; + private ?bool $isDeleted = null; /** @internal */ private $client; /** @internal */ @@ -125,18 +126,12 @@ class Archive ]; /** @internal */ - public function __construct($archiveData, $options = array()) + public function __construct($archiveData, $options = []) { // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'apiKey' => null, - 'apiSecret' => null, - 'apiUrl' => 'https://api.opentok.com', - 'client' => null, - 'streamMode' => StreamMode::AUTO - ); + $defaults = ['apiKey' => null, 'apiSecret' => null, 'apiUrl' => 'https://api.opentok.com', 'client' => null, 'streamMode' => StreamMode::AUTO]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($apiKey, $apiSecret, $apiUrl, $client, $streamMode) = array_values($options); + [$apiKey, $apiSecret, $apiUrl, $client, $streamMode] = array_values($options); // validate params Validators::validateArchiveData($archiveData); @@ -144,7 +139,7 @@ public function __construct($archiveData, $options = array()) Validators::validateHasStreamMode($streamMode); if (isset($archiveData['maxBitrate']) && isset($archiveData['quantizationParameter'])) { - throw new \DomainException('Max Bitrate cannot be set with QuantizationParameter '); + throw new DomainException('Max Bitrate cannot be set with QuantizationParameter '); } $this->data = $archiveData; @@ -153,7 +148,7 @@ public function __construct($archiveData, $options = array()) $this->multiArchiveTag = $this->data['multiArchiveTag']; } - $this->client = isset($client) ? $client : new Client(); + $this->client = $client ?? new Client(); if (!$this->client->isConfigured()) { Validators::validateApiUrl($apiUrl); @@ -161,7 +156,7 @@ public function __construct($archiveData, $options = array()) } } - public static function getPermittedResolutions() + public static function getPermittedResolutions(): array { return self::PERMITTED_AUTO_RESOLUTIONS; } @@ -173,32 +168,11 @@ public function __get($name) // TODO: throw an logic error about not being able to stop an archive thats deleted } - switch ($name) { - case 'createdAt': - case 'duration': - case 'id': - case 'name': - case 'partnerId': - case 'reason': - case 'sessionId': - case 'size': - case 'status': - case 'url': - case 'hasVideo': - case 'hasAudio': - case 'outputMode': - case 'resolution': - case 'streamMode': - case 'maxBitrate': - case 'quantizationParameter': - case 'hasTranscription': - case 'transcription': - return $this->data[$name]; - case 'multiArchiveTag': - return $this->multiArchiveTag; - default: - return null; - } + return match ($name) { + 'createdAt', 'duration', 'id', 'name', 'partnerId', 'reason', 'sessionId', 'size', 'status', 'url', 'hasVideo', 'hasAudio', 'outputMode', 'resolution', 'streamMode', 'maxBitrate', 'quantizationParameter', 'hasTranscription', 'transcription' => $this->data[$name], + 'multiArchiveTag' => $this->multiArchiveTag, + default => null, + }; } /** @@ -209,7 +183,7 @@ public function __get($name) * * @throws Exception\ArchiveException The archive is not being recorded. */ - public function stop() + public function stop(): static { if ($this->isDeleted) { // TODO: throw an logic error about not being able to stop an archive thats deleted @@ -238,14 +212,14 @@ public function stop() * @throws Exception\ArchiveException There archive status is not "available", "updated", * or "deleted". */ - public function delete() + public function delete(): bool { if ($this->isDeleted) { // TODO: throw an logic error about not being able to stop an archive thats deleted } if ($this->client->deleteArchive($this->data['id'])) { - $this->data = array(); + $this->data = []; $this->isDeleted = true; return true; } @@ -264,7 +238,7 @@ public function toJson() * Adds a stream to a currently running archive that was started with the * the streamMode set to StreamMode.Manual. You can call the method * repeatedly with the same stream ID, to toggle the stream's audio or video in the archive. - * + * * @param String $streamId The stream ID. * @param Boolean $hasAudio Whether the archive should include the stream's audio (true, the default) * or not (false). @@ -282,23 +256,18 @@ public function addStreamToArchive(string $streamId, bool $hasAudio, bool $hasVi if ($hasAudio === false && $hasVideo === false) { throw new InvalidArgumentException('Both hasAudio and hasVideo cannot be false'); } - - if ($this->client->addStreamToArchive( + return $this->client->addStreamToArchive( $this->data['id'], $streamId, $hasVideo, $hasVideo - )) { - return true; - } - - return false; + ); } /** * Removes a stream from a currently running archive that was started with the * the streamMode set to StreamMode.Manual. - * + * * @param String $streamId The stream ID. * * @return Boolean Returns true on success. @@ -308,15 +277,10 @@ public function removeStreamFromArchive(string $streamId): bool if ($this->streamMode === StreamMode::AUTO) { throw new InvalidArgumentException('Cannot remove stream to an Archive in auto stream mode'); } - - if ($this->client->removeStreamFromArchive( + return $this->client->removeStreamFromArchive( $this->data['id'], $streamId - )) { - return true; - } - - return false; + ); } /** diff --git a/src/OpenTok/ArchiveList.php b/src/OpenTok/ArchiveList.php index d9a51bc6..56c3b358 100644 --- a/src/OpenTok/ArchiveList.php +++ b/src/OpenTok/ArchiveList.php @@ -12,7 +12,6 @@ */ class ArchiveList { - /** * @internal */ @@ -24,22 +23,17 @@ class ArchiveList /** * @internal */ - private $items; + private ?array $items = null; /** * @internal */ - public function __construct($archiveListData, $options = array()) + public function __construct($archiveListData, $options = []) { // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'apiKey' => null, - 'apiSecret' => null, - 'apiUrl' => 'https://api.opentok.com', - 'client' => null - ); + $defaults = ['apiKey' => null, 'apiSecret' => null, 'apiUrl' => 'https://api.opentok.com', 'client' => null]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($apiKey, $apiSecret, $apiUrl, $client) = array_values($options); + [$apiKey, $apiSecret, $apiUrl, $client] = array_values($options); // validate params Validators::validateArchiveListData($archiveListData); @@ -47,7 +41,7 @@ public function __construct($archiveListData, $options = array()) $this->data = $archiveListData; - $this->client = isset($client) ? $client : new Client(); + $this->client = $client ?? new Client(); if (!$this->client->isConfigured()) { Validators::validateApiUrl($apiUrl); @@ -71,9 +65,9 @@ public function totalCount() public function getItems() { if (!$this->items) { - $items = array(); + $items = []; foreach ($this->data['items'] as $archiveData) { - $items[] = new Archive($archiveData, array( 'client' => $this->client )); + $items[] = new Archive($archiveData, ['client' => $this->client]); } $this->items = $items; } diff --git a/src/OpenTok/Broadcast.php b/src/OpenTok/Broadcast.php index 0ea809fb..c616160a 100644 --- a/src/OpenTok/Broadcast.php +++ b/src/OpenTok/Broadcast.php @@ -79,7 +79,7 @@ class Broadcast /** @ignore */ private $client; /** @ignore */ - private $isHls; + private readonly bool $isHls; /** @ignore */ private $isLowLatency; /** @ignore */ @@ -97,24 +97,12 @@ class Broadcast /** @ignore */ private $maxBitRate; - public function __construct($broadcastData, $options = array()) + public function __construct($broadcastData, $options = []) { // unpack optional arguments (merging with default values) into named variables // when adding these properties like this, it's worth noting that the method that // starts a broadcast ALSO sets a load of defaults - $defaults = array( - 'apiKey' => null, - 'apiSecret' => null, - 'apiUrl' => 'https://api.opentok.com', - 'client' => null, - 'isStopped' => false, - 'streamMode' => StreamMode::AUTO, - 'isHls' => true, - 'isLowLatency' => false, - 'isDvr' => false, - 'hasAudio' => true, - 'hasVideo' => true - ); + $defaults = ['apiKey' => null, 'apiSecret' => null, 'apiUrl' => 'https://api.opentok.com', 'client' => null, 'isStopped' => false, 'streamMode' => StreamMode::AUTO, 'isHls' => true, 'isLowLatency' => false, 'isDvr' => false, 'hasAudio' => true, 'hasVideo' => true]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); @@ -156,47 +144,27 @@ public function __construct($broadcastData, $options = array()) /** @ignore */ public function __get($name) { - switch ($name) { - case 'createdAt': - case 'updatedAt': - case 'id': - case 'partnerId': - case 'sessionId': - case 'broadcastUrls': - case 'maxDuration': - case 'streamMode': - return $this->data[$name]; - case 'resolution': - return $this->resolution; - case 'hlsUrl': - return $this->data['broadcastUrls']['hls']; - case 'isStopped': - return $this->isStopped; - case 'isHls': - return $this->isHls; - case 'isLowLatency': - return $this->isLowLatency; - case 'isDvr': - return $this->isDvr; - case 'multiBroadcastTag': - return $this->multiBroadcastTag; - case 'hasAudio': - return $this->hasAudio; - case 'hasVideo': - return $this->hasVideo; - case 'status': - return $this->status; - case 'maxBitRate': - return $this->maxBitRate; - default: - return null; - } + return match ($name) { + 'createdAt', 'updatedAt', 'id', 'partnerId', 'sessionId', 'broadcastUrls', 'maxDuration', 'streamMode' => $this->data[$name], + 'resolution' => $this->resolution, + 'hlsUrl' => $this->data['broadcastUrls']['hls'], + 'isStopped' => $this->isStopped, + 'isHls' => $this->isHls, + 'isLowLatency' => $this->isLowLatency, + 'isDvr' => $this->isDvr, + 'multiBroadcastTag' => $this->multiBroadcastTag, + 'hasAudio' => $this->hasAudio, + 'hasVideo' => $this->hasVideo, + 'status' => $this->status, + 'maxBitRate' => $this->maxBitRate, + default => null, + }; } /** * Stops the broadcast. */ - public function stop() + public function stop(): static { if ($this->isStopped) { throw new BroadcastDomainException( @@ -231,7 +199,7 @@ public function stop() * * @param Layout $layout An object defining the layout type for the broadcast. */ - public function updateLayout($layout) + public function updateLayout($layout): void { Validators::validateLayout($layout); @@ -246,7 +214,7 @@ public function updateLayout($layout) * Adds a stream to a currently running broadcast that was started with the * the streamMode set to StreamMode.Manual. You can call the method * repeatedly with the same stream ID, to toggle the stream's audio or video in the broadcast. - * + * * @param String $streamId The stream ID. * @param Boolean $hasAudio Whether the broadcast should include the stream's audio (true, the default) * or not (false). @@ -264,23 +232,18 @@ public function addStreamToBroadcast(string $streamId, bool $hasAudio, bool $has if ($hasAudio === false && $hasVideo === false) { throw new InvalidArgumentException('Both hasAudio and hasVideo cannot be false'); } - - if ($this->client->addStreamToBroadcast( + return (bool) $this->client->addStreamToBroadcast( $this->data['id'], $streamId, $hasVideo, $hasVideo - )) { - return true; - } - - return false; + ); } /** * Removes a stream from a currently running broadcast that was started with the * the streamMode set to StreamMode.Manual. - * + * * @param String $streamId The stream ID. * * @return Boolean Returns true on success. @@ -290,15 +253,10 @@ public function removeStreamFromBroadcast(string $streamId): bool if ($this->streamMode === StreamMode::AUTO) { throw new InvalidArgumentException('Cannot remove stream from a Broadcast in auto stream mode'); } - - if ($this->client->removeStreamFromBroadcast( + return (bool) $this->client->removeStreamFromBroadcast( $this->data['id'], $streamId - )) { - return true; - } - - return false; + ); } public function jsonSerialize() diff --git a/src/OpenTok/Connection.php b/src/OpenTok/Connection.php index e3af27ed..09dffceb 100644 --- a/src/OpenTok/Connection.php +++ b/src/OpenTok/Connection.php @@ -19,30 +19,21 @@ class Connection { - - private $data; - - public function __construct($connectionData) + public function __construct(private $data) { - - $this->data = $connectionData; } /** @ignore */ public function __get($name) { - switch ($name) { - case 'connectionId': - case 'connectionState': - case 'createdAt': - return $this->data[$name]; - default: - return null; - } + return match ($name) { + 'connectionId', 'connectionState', 'createdAt' => $this->data[$name], + default => null, + }; } public function jsonSerialize() { return $this->data; } -} \ No newline at end of file +} diff --git a/src/OpenTok/ConnectionList.php b/src/OpenTok/ConnectionList.php index 7cefefa6..7b9621b2 100644 --- a/src/OpenTok/ConnectionList.php +++ b/src/OpenTok/ConnectionList.php @@ -2,26 +2,25 @@ namespace OpenTok; +use Iterator; + /** * An object, returned by the OpenTok.listConnections() * method, representing a list of connections in an OpenTok session. */ -class ConnectionList implements \Iterator +class ConnectionList implements Iterator { /** @ignore */ - private $data; - - /** @ignore */ - private $items; + private ?array $items = null; /** @ignore */ - private $position = 0; + private int $position = 0; /** @ignore */ - public function __construct($connectionListData) - { - $this->data = $connectionListData; - $this->position = 0; + public function __construct( + /** @ignore */ + private $data + ) { } /** @@ -62,7 +61,7 @@ public function getSessionId() public function getItems() { if (!is_array($this->items)) { - $items = array(); + $items = []; foreach ($this->data['items'] as $connectionData) { $items[] = new Connection($connectionData); } @@ -91,8 +90,6 @@ public function rewind(): void /** * Return the current element - * - * @return Connection */ public function current(): Connection { @@ -102,8 +99,6 @@ public function current(): Connection /** * Return the key of the current element - * - * @return int */ public function key(): int { @@ -120,12 +115,10 @@ public function next(): void /** * Checks if current position is valid - * - * @return bool */ public function valid(): bool { $items = $this->getItems(); return isset($items[$this->position]); } -} \ No newline at end of file +} diff --git a/src/OpenTok/Exception/AuthenticationException.php b/src/OpenTok/Exception/AuthenticationException.php index e42a1788..404d7c6a 100644 --- a/src/OpenTok/Exception/AuthenticationException.php +++ b/src/OpenTok/Exception/AuthenticationException.php @@ -9,7 +9,7 @@ class AuthenticationException extends DomainException implements Exception { /** @ignore */ - public function __construct($apiKey, $apiSecret, $code = 0, $previous) + public function __construct($apiKey, $apiSecret, $previous, $code = 0) { $message = 'The OpenTok API credentials were rejected. apiKey=' . $apiKey . ', apiSecret=' . $apiSecret; parent::__construct($message, $code, $previous); diff --git a/src/OpenTok/Exception/SignalNetworkConnectionException.php b/src/OpenTok/Exception/SignalNetworkConnectionException.php index e2251564..a37d809a 100644 --- a/src/OpenTok/Exception/SignalNetworkConnectionException.php +++ b/src/OpenTok/Exception/SignalNetworkConnectionException.php @@ -2,11 +2,12 @@ namespace OpenTok\Exception; +use RuntimeException; + /** * Defines an exception thrown when a call to a signal method results in no * response from the server */ -class SignalNetworkConnectionException extends \RuntimeException implements SignalException +class SignalNetworkConnectionException extends RuntimeException implements SignalException { - } diff --git a/src/OpenTok/Layout.php b/src/OpenTok/Layout.php index db7165e9..295a0983 100644 --- a/src/OpenTok/Layout.php +++ b/src/OpenTok/Layout.php @@ -2,6 +2,9 @@ namespace OpenTok; +use JsonSerializable; +use RuntimeException; +use ReturnTypeWillChange; use OpenTok\Util\Validators; /** @@ -19,7 +22,7 @@ * Configuring * video layout for OpenTok live streaming broadcasts. */ -class Layout implements \JsonSerializable +class Layout implements JsonSerializable { public const LAYOUT_BESTFIT = 'bestFit'; public const LAYOUT_CUSTOM = 'custom'; @@ -27,32 +30,26 @@ class Layout implements \JsonSerializable public const LAYOUT_PIP = 'pip'; public const LAYOUT_VERTICAL = 'verticalPresentation'; - /** - * Type of layout that we are sending - * @var string - * @ignore - * */ - private $type; - /** * Type of layout to use for screen sharing - * @var string - * @ignore - */ - private $screenshareType; - - /** - * Custom stylesheet if our type is 'custom' - * @var string * @ignore */ - private $stylesheet; + private ?string $screenshareType = null; /** @ignore */ - private function __construct(string $type, ?string $stylesheet = null) - { - $this->type = $type; - $this->stylesheet = $stylesheet; + private function __construct( + /** + * Type of layout that we are sending + * @ignore + * */ + private readonly string $type, + /** + * Custom stylesheet if our type is 'custom' + * @var string + * @ignore + */ + private readonly ?string $stylesheet = null + ) { } /** @@ -69,7 +66,7 @@ public static function createCustom(array $options): Layout // $options argument so that it can become truly optional in the future. $defaults = ['stylesheet' => null]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($stylesheet) = array_values($options); + [$stylesheet] = array_values($options); // validate arguments Validators::validateLayoutStylesheet($stylesheet); @@ -130,17 +127,17 @@ public function setScreenshareType(string $screenshareType): Layout ]; if (!in_array($screenshareType, $layouts)) { - throw new \RuntimeException('Screenshare type must be of a valid layout type'); + throw new RuntimeException('Screenshare type must be of a valid layout type'); } $this->screenshareType = $screenshareType; return $this; } - throw new \RuntimeException('Screenshare type cannot be set on a layout type other than bestFit'); + throw new RuntimeException('Screenshare type cannot be set on a layout type other than bestFit'); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function jsonSerialize() { return $this->toArray(); @@ -156,17 +153,15 @@ public function toJson(): string public function toArray(): array { - $data = array( - 'type' => $this->type - ); + $data = ['type' => $this->type]; // omit 'stylesheet' property unless it is explicitly defined - if (isset($this->stylesheet)) { + if ($this->stylesheet !== null) { $data['stylesheet'] = $this->stylesheet; } // omit 'screenshareType' property unless it is explicitly defined - if (isset($this->screenshareType)) { + if ($this->screenshareType !== null) { $data['screenshareType'] = $this->screenshareType; } diff --git a/src/OpenTok/OpenTok.php b/src/OpenTok/OpenTok.php index 7db1b78e..93e376a0 100644 --- a/src/OpenTok/OpenTok.php +++ b/src/OpenTok/OpenTok.php @@ -2,6 +2,7 @@ namespace OpenTok; +use Exception; use DateTimeImmutable; use Firebase\JWT\JWT; use Firebase\JWT\Key; @@ -40,12 +41,6 @@ class OpenTok /** @internal */ private $client; - /** - * @var bool - * Override to determine whether to hit Vonage servers with Vonage Auth in requests - */ - private $vonage = false; - /** * @var array * @internal @@ -53,31 +48,26 @@ class OpenTok public $options; /** @internal */ - public function __construct($apiKey, $apiSecret, $options = array()) + public function __construct($apiKey, $apiSecret, $options = []) { $apiUrl = 'https://api.opentok.com'; if (Validators::isVonageKeypair($apiKey, $apiSecret)) { - $this->vonage = true; $apiUrl = 'https://video.api.vonage.com'; } // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'apiUrl' => $apiUrl, - 'client' => null, - 'timeout' => null, // In the future we should set this to 2 - ); + $defaults = ['apiUrl' => $apiUrl, 'client' => null, 'timeout' => null]; $this->options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($apiUrl, $client, $timeout) = array_values($this->options); + [$apiUrl, $client, $timeout] = array_values($this->options); Validators::validateApiUrl($apiUrl); Validators::validateClient($client); Validators::validateDefaultTimeout($timeout); - $this->client = isset($client) ? $client : new Client(); + $this->client = $client ?? new Client(); if (!$this->client->isConfigured()) { $this->client->configure( $apiKey, @@ -136,13 +126,13 @@ public function __construct($apiKey, $apiSecret, $options = array()) * * @return string The token string. */ - public function generateToken(string $sessionId, array $payload = array(), bool $legacy = false): string + public function generateToken(string $sessionId, array $payload = [], bool $legacy = false): string { if ($legacy) { return $this->returnLegacyToken($sessionId, $payload); } - $issuedAt = new \DateTimeImmutable('@' . time()); + $issuedAt = new DateTimeImmutable('@' . time()); $defaults = [ 'iss' => $this->apiKey, @@ -165,7 +155,7 @@ public function generateToken(string $sessionId, array $payload = array(), bool } if (isset($payload['initialLayoutClassList'])) { - $payload['initial_layout_class_list'] = urlencode(join(' ', $payload['initialLayoutClassList'])); + $payload['initial_layout_class_list'] = urlencode(implode(' ', $payload['initialLayoutClassList'])); unset($payload['initialLayoutClassList']); } @@ -179,14 +169,9 @@ public function generateToken(string $sessionId, array $payload = array(), bool private function returnLegacyToken(string $sessionId, array $options = []): string { - $defaults = array( - 'role' => Role::PUBLISHER, - 'expireTime' => null, - 'data' => null, - 'initialLayoutClassList' => array(''), - ); + $defaults = ['role' => Role::PUBLISHER, 'expireTime' => null, 'data' => null, 'initialLayoutClassList' => ['']]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($role, $expireTime, $data, $initialLayoutClassList) = array_values($options); + [$role, $expireTime, $data, $initialLayoutClassList] = array_values($options); // additional token data $createTime = time(); @@ -201,96 +186,96 @@ private function returnLegacyToken(string $sessionId, array $options = []): stri $dataString = "session_id=$sessionId&create_time=$createTime&role=$role&nonce=$nonce" . (($expireTime) ? "&expire_time=$expireTime" : '') . - (($data) ? "&connection_data=" . urlencode($data) : '') . - ((!empty($initialLayoutClassList)) ? "&initial_layout_class_list=" . urlencode(join(" ", $initialLayoutClassList)) : ''); + (($data) ? "&connection_data=" . urlencode((string) $data) : '') . + ((empty($initialLayoutClassList)) ? '' : "&initial_layout_class_list=" . urlencode(implode(" ", $initialLayoutClassList))); $sig = $this->signString($dataString, $this->apiSecret); return "T1==" . base64_encode("partner_id=$this->apiKey&sig=$sig:$dataString"); } /** - * Creates a new OpenTok session and returns the session ID, which uniquely identifies - * the session. - *

- * For example, when using the OpenTok JavaScript library, use the session ID when calling the - * - * OT.initSession() method (to initialize an OpenTok session). - *

- * OpenTok sessions do not expire. However, authentication tokens do expire (see the - * generateToken() method). Also note that sessions cannot explicitly be destroyed. - *

- * A session ID string can be up to 255 characters long. - *

- * Calling this method results in an OpenTokException in the event of an error. - * Check the error message for details. - *

- * You can also create a session by logging in to your - * OpenTok Video API account. - * - * @param array $options (Optional) This array defines options for the session. The array includes - * the following keys (all of which are optional): - * - *

+ * + * @return Session A Session object representing the new session. Call the + * getSessionId() method of this object to get the session ID. For example, + * when using the OpenTok.js library, use this session ID when calling the + * OT.initSession() method. + */ + public function createSession(array $options = []): Session { if ( array_key_exists('archiveMode', $options) && @@ -301,9 +286,8 @@ public function createSession($options = array()) $options['mediaMode'] !== MediaMode::ROUTED ) { throw new InvalidArgumentException('A session must be routed to be archived.'); - } else { - $options['mediaMode'] = MediaMode::ROUTED; } + $options['mediaMode'] = MediaMode::ROUTED; } if (array_key_exists('e2ee', $options) && $options['e2ee']) { @@ -319,14 +303,7 @@ public function createSession($options = array()) } // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'mediaMode' => MediaMode::RELAYED, - 'archiveMode' => ArchiveMode::MANUAL, - 'location' => null, - 'e2ee' => 'false', - 'archiveName' => null, - 'archiveResolution' => null - ); + $defaults = ['mediaMode' => MediaMode::RELAYED, 'archiveMode' => ArchiveMode::MANUAL, 'location' => null, 'e2ee' => 'false', 'archiveName' => null, 'archiveResolution' => null]; // Have to hack this because the default system in these classes needs total refactor $resolvedArchiveMode = array_merge($defaults, array_intersect_key($options, $defaults)); @@ -346,7 +323,7 @@ public function createSession($options = array()) unset($options['archiveResolution']); } - list($mediaMode, $archiveMode, $location, $e2ee) = array_values($options); + [$mediaMode, $archiveMode, $location, $e2ee] = array_values($options); // validate arguments Validators::validateMediaMode($mediaMode); @@ -364,12 +341,7 @@ public function createSession($options = array()) throw new UnexpectedValueException($errorMessage); } - return new Session($this, (string)$sessionId, array( - 'location' => $location, - 'mediaMode' => $mediaMode, - 'archiveMode' => $archiveMode, - 'e2ee' => $e2ee - )); + return new Session($this, (string)$sessionId, ['location' => $location, 'mediaMode' => $mediaMode, 'archiveMode' => $archiveMode, 'e2ee' => $e2ee]); } /** @@ -399,7 +371,7 @@ public function createSession($options = array()) * * * - * @return \OpenTok\Render The render object, which includes properties defining the render, including the render ID. + * @return Render The render object, which includes properties defining the render, including the render ID. */ public function startRender( $sessionId, @@ -434,8 +406,6 @@ public function startRender( /** * Returns a list of Experience Composer renderers for an OpenTok project. * - * @param int $offset - * @param int $count * * @return mixed */ @@ -452,10 +422,8 @@ public function listRenders(int $offset = 0, int $count = 50) * Stops an existing render. * * @param $renderId - * - * @return mixed */ - public function stopRender($renderId) + public function stopRender(string $renderId): bool { return $this->client->stopRender($renderId); } @@ -470,10 +438,8 @@ public function stopRender($renderId) * * * @param $renderId - * - * @return Render */ - public function getRender($renderId): Render + public function getRender(string $renderId): Render { $renderPayload = $this->client->getRender($renderId); @@ -572,20 +538,11 @@ public function startArchive(string $sessionId, $options = []): Archive 'Archive options passed as a string is deprecated, please pass an array with a name key', E_USER_DEPRECATED ); - $options = array('name' => $options); + $options = ['name' => $options]; } // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'name' => null, - 'hasVideo' => true, - 'hasAudio' => true, - 'outputMode' => OutputMode::COMPOSED, - 'resolution' => null, - 'streamMode' => StreamMode::AUTO, - 'hasTranscription' => false, - 'transcriptionProperties' => null, - ); + $defaults = ['name' => null, 'hasVideo' => true, 'hasAudio' => true, 'outputMode' => OutputMode::COMPOSED, 'resolution' => null, 'streamMode' => StreamMode::AUTO, 'hasTranscription' => false, 'transcriptionProperties' => null]; // Horrible hack to workaround the defaults behaviour if (isset($options['maxBitrate'])) { @@ -593,11 +550,11 @@ public function startArchive(string $sessionId, $options = []): Archive } // Preserve transcription fields from user input - $hasTranscription = isset($options['hasTranscription']) ? $options['hasTranscription'] : false; - $transcriptionProperties = isset($options['transcriptionProperties']) ? $options['transcriptionProperties'] : null; + $hasTranscription = $options['hasTranscription'] ?? false; + $transcriptionProperties = $options['transcriptionProperties'] ?? null; $options = array_merge($defaults, array_intersect_key($options, $defaults)); - list($name, $hasVideo, $hasAudio, $outputMode, $resolution, $streamMode) = array_values($options); + [$name, $hasVideo, $hasAudio, $outputMode, $resolution, $streamMode] = array_values($options); // Re-add transcription options to options array for API call $options['hasTranscription'] = $hasTranscription; @@ -610,9 +567,7 @@ public function startArchive(string $sessionId, $options = []): Archive } // Remove null values before sending to API - $options = array_filter($options, function($value) { - return $value !== null; - }); + $options = array_filter($options, fn($value): bool => $value !== null); if (isset($maxBitrate)) { $options['maxBitrate'] = $maxBitrate; @@ -646,7 +601,7 @@ public function startArchive(string $sessionId, $options = []): Archive $archiveData = $this->client->startArchive($sessionId, $options); - return new Archive($archiveData, array( 'client' => $this->client )); + return new Archive($archiveData, ['client' => $this->client]); } /** @@ -658,12 +613,12 @@ public function startArchive(string $sessionId, $options = []): Archive * @param String $archiveId The archive ID of the archive you want to stop recording. * @return Archive The Archive object corresponding to the archive being stopped. */ - public function stopArchive($archiveId) + public function stopArchive($archiveId): Archive { Validators::validateArchiveId($archiveId); $archiveData = $this->client->stopArchive($archiveId); - return new Archive($archiveData, array( 'client' => $this->client )); + return new Archive($archiveData, ['client' => $this->client]); } /** @@ -676,12 +631,12 @@ public function stopArchive($archiveId) * * @return Archive The Archive object. */ - public function getArchive($archiveId) + public function getArchive($archiveId): Archive { Validators::validateArchiveId($archiveId); $archiveData = $this->client->getArchive($archiveId); - return new Archive($archiveData, array( 'client' => $this->client )); + return new Archive($archiveData, ['client' => $this->client]); } /** @@ -723,7 +678,7 @@ public function deleteArchive($archiveId) * @return ArchiveList An ArchiveList object. Call the items() method of the ArchiveList object * to return an array of Archive objects. */ - public function listArchives($offset = 0, $count = null, $sessionId = null) + public function listArchives($offset = 0, $count = null, $sessionId = null): ArchiveList { // validate params Validators::validateOffsetAndCount($offset, $count); @@ -732,7 +687,7 @@ public function listArchives($offset = 0, $count = null, $sessionId = null) } $archiveListData = $this->client->listArchives($offset, $count, $sessionId); - return new ArchiveList($archiveListData, array( 'client' => $this->client )); + return new ArchiveList($archiveListData, ['client' => $this->client]); } @@ -760,7 +715,7 @@ public function setArchiveLayout(string $archiveId, Layout $layoutType): void * @param array $classListArray The connectionId of the connection in a session. */ - public function setStreamClassLists($sessionId, $classListArray = array()) + public function setStreamClassLists($sessionId, $classListArray = []): void { Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey); @@ -809,7 +764,7 @@ public function forceMuteStream(string $sessionId, string $streamId): bool try { $this->client->forceMuteStream($sessionId, $streamId); - } catch (\Exception $e) { + } catch (Exception) { return false; } @@ -852,7 +807,7 @@ public function forceMuteAll(string $sessionId, array $options): bool try { $this->client->forceMuteAll($sessionId, $options); - } catch (\Exception $e) { + } catch (Exception) { return false; } @@ -892,7 +847,7 @@ public function disableForceMute(string $sessionId, array $options): bool try { $this->client->forceMuteAll($sessionId, $options); - } catch (\Exception $e) { + } catch (Exception) { return false; } @@ -1039,10 +994,7 @@ public function stopBroadcast($broadcastId): Broadcast // make API call $broadcastData = $this->client->stopBroadcast($broadcastId); - return new Broadcast($broadcastData, array( - 'client' => $this->client, - 'isStopped' => true - )); + return new Broadcast($broadcastData, ['client' => $this->client, 'isStopped' => true]); } /** @@ -1057,7 +1009,7 @@ public function getBroadcast($broadcastId): Broadcast Validators::validateBroadcastId($broadcastId); $broadcastData = $this->client->getBroadcast($broadcastId); - return new Broadcast($broadcastData, array( 'client' => $this->client )); + return new Broadcast($broadcastData, ['client' => $this->client]); } // TODO: not yet implemented by the platform @@ -1120,14 +1072,12 @@ public function updateBroadcastLayout(string $broadcastId, Layout $layout): void * $opentok->updateStream($sessionId, $streamId, $streamProperties); * */ - public function updateStream($sessionId, $streamId, $properties = array()) + public function updateStream($sessionId, $streamId, $properties = []): void { // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'layoutClassList' => array() - ); + $defaults = ['layoutClassList' => []]; $properties = array_merge($defaults, array_intersect_key($properties, $defaults)); - list($layoutClassList) = array_values($properties); + [$layoutClassList] = array_values($properties); // validate arguments Validators::validateSessionId($sessionId); @@ -1148,7 +1098,7 @@ public function updateStream($sessionId, $streamId, $properties = array()) * @return Stream The Stream object. */ - public function getStream($sessionId, $streamId) + public function getStream($sessionId, $streamId): Stream { Validators::validateSessionId($sessionId); Validators::validateStreamId($streamId); @@ -1167,7 +1117,7 @@ public function getStream($sessionId, $streamId) * to return an array of Stream objects. */ - public function listStreams($sessionId) + public function listStreams($sessionId): StreamList { Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey); @@ -1186,7 +1136,7 @@ public function listStreams($sessionId) * @return ConnectionList A ConnectionList object. Call the getItems() method of the ConnectionList object * to return an array of Connection objects. */ - public function listConnections($sessionId) + public function listConnections($sessionId): ConnectionList { Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey); @@ -1271,18 +1221,10 @@ public function listConnections($sessionId) * OpenTok::method_forceDisconnect() * method. */ - public function dial($sessionId, $token, $sipUri, $options = []) + public function dial($sessionId, $token, $sipUri, $options = []): SipCall { // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'auth' => null, - 'headers' => [], - 'secure' => true, - 'from' => null, - 'video' => false, - 'observeForceMute' => false, - 'streams' => null - ); + $defaults = ['auth' => null, 'headers' => [], 'secure' => true, 'from' => null, 'video' => false, 'observeForceMute' => false, 'streams' => null]; $options = array_merge($defaults, array_intersect_key($options, $defaults)); @@ -1313,8 +1255,6 @@ public function dial($sessionId, $token, $sipUri, $options = []) * needed during the input process. * * @param string $connectionId An optional parameter used to send the DTMF tones to a specific connection in a session. - * - * @return void */ public function playDTMF(string $sessionId, string $digits, string $connectionId = null): void { @@ -1343,17 +1283,14 @@ public function playDTMF(string $sessionId, string $digits, string $connectionId * * @param string $connectionId An optional parameter used to send the signal to a specific connection in a session. */ - public function signal($sessionId, $payload, $connectionId = null) + public function signal($sessionId, $payload, $connectionId = null): void { // unpack optional arguments (merging with default values) into named variables - $defaults = array( - 'type' => '', - 'data' => '', - ); + $defaults = ['type' => '', 'data' => '']; $payload = array_merge($defaults, array_intersect_key($payload, $defaults)); - list($type, $data) = array_values($payload); + [$type, $data] = array_values($payload); // validate arguments Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey); @@ -1464,8 +1401,8 @@ public function stopCaptions(string $captionsId) } /** @internal */ - private function signString($string, $secret) + private function signString(string $string, $secret): string { - return hash_hmac("sha1", $string, $secret); + return hash_hmac("sha1", $string, (string) $secret); } } diff --git a/src/OpenTok/Render.php b/src/OpenTok/Render.php index ecad7a2c..b612aae0 100644 --- a/src/OpenTok/Render.php +++ b/src/OpenTok/Render.php @@ -47,25 +47,15 @@ class Render /** @internal */ public function __construct($data) { - $this->data = json_decode($data, true); + $this->data = json_decode((string) $data, true); } /** @internal */ public function __get($name) { - switch ($name) { - case 'id': - case 'sessionId': - case 'projectId': - case 'createdAt': - case 'updatedAt': - case 'url': - case 'resolution': - case 'status': - case 'streamId': - return $this->data[$name]; - default: - return null; - } + return match ($name) { + 'id', 'sessionId', 'projectId', 'createdAt', 'updatedAt', 'url', 'resolution', 'status', 'streamId' => $this->data[$name], + default => null, + }; } } diff --git a/src/OpenTok/Session.php b/src/OpenTok/Session.php index 159f69e0..8cf9a6da 100644 --- a/src/OpenTok/Session.php +++ b/src/OpenTok/Session.php @@ -2,6 +2,7 @@ namespace OpenTok; +use Stringable; use OpenTok\Util\Validators; /** @@ -10,7 +11,7 @@ * Use the \OpenTok\OpenTok->createSession() method to create an OpenTok session. Use the * getSessionId() method of the Session object to get the session ID. */ -class Session +class Session implements Stringable { /** * @internal @@ -40,7 +41,7 @@ class Session /** * @internal */ - public function __construct($opentok, $sessionId, $properties = array()) + public function __construct($opentok, $sessionId, $properties = []) { $defaults = [ 'mediaMode' => MediaMode::ROUTED, @@ -50,7 +51,7 @@ public function __construct($opentok, $sessionId, $properties = array()) ]; $properties = array_merge($defaults, array_intersect_key($properties, $defaults)); - list($mediaMode, $archiveMode, $location, $e2ee) = array_values($properties); + [$mediaMode, $archiveMode, $location, $e2ee] = array_values($properties); Validators::validateOpenTok($opentok); Validators::validateSessionId($sessionId); @@ -120,9 +121,9 @@ public function getArchiveMode() /** * @internal */ - public function __toString() + public function __toString(): string { - return $this->sessionId; + return (string) $this->sessionId; } /** @@ -157,7 +158,7 @@ public function __toString() * * @return string The token string. */ - public function generateToken($options = array(), bool $legacy = false) + public function generateToken($options = [], bool $legacy = false) { return $this->opentok->generateToken($this->sessionId, $options, $legacy); } @@ -165,8 +166,6 @@ public function generateToken($options = array(), bool $legacy = false) /** * Whether end-to-end encryption * is set for the session. - * - * @return bool */ public function getE2EE(): bool { diff --git a/src/OpenTok/SipCall.php b/src/OpenTok/SipCall.php index 10d8f8af..8fc5c459 100644 --- a/src/OpenTok/SipCall.php +++ b/src/OpenTok/SipCall.php @@ -21,10 +21,10 @@ class SipCall { /** @internal */ - private $data; + private array $data; /** @internal */ - public function __construct($sipCallData) + public function __construct(array $sipCallData) { $this->data['id'] = $sipCallData['id']; $this->data['connectionId'] = $sipCallData['connectionId']; @@ -37,14 +37,10 @@ public function __construct($sipCallData) /** @internal */ public function __get($name) { - switch ($name) { - case 'id': - case 'connectionId': - case 'streamId': - return $this->data[$name]; - default: - return null; - } + return match ($name) { + 'id', 'connectionId', 'streamId' => $this->data[$name], + default => null, + }; } diff --git a/src/OpenTok/Stream.php b/src/OpenTok/Stream.php index 03b8fdb1..95e5fddd 100644 --- a/src/OpenTok/Stream.php +++ b/src/OpenTok/Stream.php @@ -23,27 +23,17 @@ class Stream { - - private $data; - - public function __construct($streamData) + public function __construct(private $data) { - - $this->data = $streamData; } /** @ignore */ public function __get($name) { - switch ($name) { - case 'id': - case 'videoType': - case 'name': - case 'layoutClassList': - return $this->data[$name]; - default: - return null; - } + return match ($name) { + 'id', 'videoType', 'name', 'layoutClassList' => $this->data[$name], + default => null, + }; } public function jsonSerialize() diff --git a/src/OpenTok/StreamList.php b/src/OpenTok/StreamList.php index 64cbc02e..ab960862 100644 --- a/src/OpenTok/StreamList.php +++ b/src/OpenTok/StreamList.php @@ -9,15 +9,13 @@ class StreamList { /** @ignore */ - private $data; + private ?array $items = null; /** @ignore */ - private $items; - - /** @ignore */ - public function __construct($streamListData) - { - $this->data = $streamListData; + public function __construct( + /** @ignore */ + private $data + ) { } /** @@ -38,7 +36,7 @@ public function totalCount() public function getItems() { if (!is_array($this->items)) { - $items = array(); + $items = []; foreach ($this->data['items'] as $streamData) { $items[] = new Stream($streamData); } diff --git a/src/OpenTok/Util/BasicEnum.php b/src/OpenTok/Util/BasicEnum.php index 4f450c45..5d6ec027 100644 --- a/src/OpenTok/Util/BasicEnum.php +++ b/src/OpenTok/Util/BasicEnum.php @@ -2,22 +2,24 @@ namespace OpenTok\Util; +use ReflectionClass; + /** * @internal */ abstract class BasicEnum { - private static $constCacheArray; + private static ?array $constCacheArray = null; private static function getConstants() { if (self::$constCacheArray === null) { - self::$constCacheArray = array(); + self::$constCacheArray = []; } - $calledClass = get_called_class(); + $calledClass = static::class; if (!array_key_exists($calledClass, self::$constCacheArray)) { - $reflect = new \ReflectionClass($calledClass); + $reflect = new ReflectionClass($calledClass); self::$constCacheArray[$calledClass] = $reflect->getConstants(); } @@ -33,7 +35,7 @@ public static function isValidName($name, $strict = false) } $keys = array_map('strtolower', array_keys($constants)); - return in_array(strtolower($name), $keys); + return in_array(strtolower((string) $name), $keys); } public static function isValidValue($value) diff --git a/src/OpenTok/Util/Client.php b/src/OpenTok/Util/Client.php index 7d309b9e..56ed8b3e 100755 --- a/src/OpenTok/Util/Client.php +++ b/src/OpenTok/Util/Client.php @@ -2,9 +2,12 @@ namespace OpenTok\Util; +use Psr\Http\Message\MessageInterface; +use RuntimeException; +use SimpleXMLElement; +use Throwable; use Composer\InstalledVersions; use Exception as GlobalException; -use GuzzleHttp\Utils; use OpenTok\Layout; use Firebase\JWT\JWT; use OpenTok\MediaMode; @@ -33,7 +36,6 @@ use OpenTok\Exception\SignalNetworkConnectionException; use OpenTok\Exception\BroadcastUnexpectedValueException; use OpenTok\Exception\ForceDisconnectConnectionException; - use OpenTok\Exception\ForceDisconnectAuthenticationException; use OpenTok\Exception\ForceDisconnectUnexpectedValueException; use Vonage\JWT\TokenGenerator; @@ -59,7 +61,7 @@ class Client */ public $options; - public function configure($apiKey, $apiSecret, $apiUrl, $options = array()) + public function configure($apiKey, $apiSecret, $apiUrl, array $options = []): void { $this->options = $options; $this->apiKey = $apiKey; @@ -79,14 +81,10 @@ public function configure($apiKey, $apiSecret, $apiUrl, $options = array()) $clientOptions['timeout'] = $options['timeout']; } - if (empty($options['handler'])) { - $handlerStack = HandlerStack::create(); - } else { - $handlerStack = $options['handler']; - } + $handlerStack = empty($options['handler']) ? HandlerStack::create() : $options['handler']; $clientOptions['handler'] = $handlerStack; - $handler = Middleware::mapRequest(function (RequestInterface $request) { + $handler = Middleware::mapRequest(function (RequestInterface $request): MessageInterface { $authHeader = $this->createAuthHeader(); return $request->withHeader('X-OPENTOK-AUTH', $authHeader); }); @@ -123,20 +121,21 @@ public function isConfigured() return $this->configured; } - private function createAuthHeader() + private function createAuthHeader(): string { if (Validators::isVonageKeypair($this->apiKey, $this->apiSecret)) { $tokenGenerator = new TokenGenerator($this->apiKey, file_get_contents($this->apiSecret)); return $tokenGenerator->generate(); } - $token = array( + $token = [ 'ist' => 'project', 'iss' => $this->apiKey, - 'iat' => time(), // this is in seconds + 'iat' => time(), + // this is in seconds 'exp' => time() + (5 * 60), 'jti' => uniqid('', true), - ); + ]; return JWT::encode($token, $this->apiSecret, 'HS256'); } @@ -152,12 +151,12 @@ public function createSession($options) 'form_params' => $this->postFieldsForOptions($options) ]); $sessionXml = $this->getResponseXml($response); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { // TODO: test if we have a parse exception and handle it, otherwise throw again throw $e; - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $sessionXml; } @@ -167,26 +166,20 @@ private function getResponseXml($response) { $errorMessage = null; $internalErrors = libxml_use_internal_errors(true); - if (\PHP_VERSION_ID < 80000) { - $disableEntities = libxml_disable_entity_loader(true); - } libxml_clear_errors(); try { $body = $response->getBody(); - $xml = new \SimpleXMLElement((string) $body ?: '', LIBXML_NONET); + $xml = new SimpleXMLElement((string) $body ?: '', LIBXML_NONET); if ($error = libxml_get_last_error()) { $errorMessage = $error->message; } - } catch (\Exception $e) { + } catch (GlobalException $e) { $errorMessage = $e->getMessage(); } libxml_clear_errors(); libxml_use_internal_errors($internalErrors); - if (\PHP_VERSION_ID < 80000) { - libxml_disable_entity_loader($disableEntities); - } if ($errorMessage) { - throw new \RuntimeException('Unable to parse response body into XML: ' . $errorMessage); + throw new RuntimeException('Unable to parse response body into XML: ' . $errorMessage); } return $xml; } @@ -198,47 +191,47 @@ public function startRender($payload) try { $response = $this->client->send($request, $payload); $renderJson = $response->getBody()->getContents(); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleRenderException($e); } return $renderJson; } - public function stopRender($renderId): bool + public function stopRender(string $renderId): bool { $request = new Request('DELETE', '/v2/project/' . $this->apiKey . '/render/' . $renderId); try { $response = $this->client->send($request); return $response->getStatusCode() === 200; - } catch (\Exception $e) { + } catch (GlobalException) { return false; } } - public function getRender($renderId): string + public function getRender(string $renderId): string { $request = new Request('POST', '/v2/project/' . $this->apiKey . '/render/' . $renderId); try { $response = $this->client->send($request); $renderJson = $response->getBody()->getContents(); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleRenderException($e); } return $renderJson; } - public function listRenders($query) + public function listRenders($query): mixed { $request = new Request('GET', '/v2/project/' . $this->apiKey . '/render?' . http_build_query($query)); try { $response = $this->client->send($request); $renderJson = $response->getBody()->getContents(); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleRenderException($e); } @@ -258,13 +251,13 @@ public function startArchive(string $sessionId, array $options = []): array ) ]); $archiveJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleArchiveException($e); } return $archiveJson; } - public function stopArchive($archiveId) + public function stopArchive(string $archiveId) { // set up the request $request = new Request( @@ -278,14 +271,14 @@ public function stopArchive($archiveId) 'debug' => $this->isDebug() ]); $archiveJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { // TODO: what happens with JSON parse errors? $this->handleArchiveException($e); } return $archiveJson; } - public function getArchive($archiveId) + public function getArchive(string $archiveId) { $request = new Request( 'GET', @@ -296,9 +289,9 @@ public function getArchive($archiveId) 'debug' => $this->isDebug() ]); $archiveJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $archiveJson; } @@ -329,7 +322,7 @@ public function addStreamToArchive(string $archiveId, string $streamId, bool $ha if ($response->getStatusCode() !== 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -361,7 +354,7 @@ public function removeStreamFromArchive(string $archiveId, string $streamId): bo if ($response->getStatusCode() !== 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -369,7 +362,7 @@ public function removeStreamFromArchive(string $archiveId, string $streamId): bo return true; } - public function deleteArchive($archiveId) + public function deleteArchive(string $archiveId): bool { $request = new Request( 'DELETE', @@ -383,14 +376,14 @@ public function deleteArchive($archiveId) if ($response->getStatusCode() != 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } return true; } - public function forceDisconnect($sessionId, $connectionId) + public function forceDisconnect(string $sessionId, string $connectionId): bool { $request = new Request( 'DELETE', @@ -404,7 +397,7 @@ public function forceDisconnect($sessionId, $connectionId) if ($response->getStatusCode() != 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleForceDisconnectException($e); return false; } @@ -430,9 +423,9 @@ public function listArchives($offset, $count, $sessionId) 'query' => $queryParams ]); $archiveListJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $archiveListJson; } @@ -457,13 +450,13 @@ public function startBroadcast(string $sessionId, array $options): array 'json' => $optionsJson ]); $broadcastJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleBroadcastException($e); } return $broadcastJson; } - public function stopBroadcast($broadcastId) + public function stopBroadcast(string $broadcastId) { $request = new Request( 'POST', @@ -476,13 +469,13 @@ public function stopBroadcast($broadcastId) 'debug' => $this->isDebug() ]); $broadcastJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleBroadcastException($e); } return $broadcastJson; } - public function getBroadcast($broadcastId) + public function getBroadcast(string $broadcastId) { $request = new Request( 'GET', @@ -493,7 +486,7 @@ public function getBroadcast($broadcastId) 'debug' => $this->isDebug() ]); $broadcastJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleBroadcastException($e); } return $broadcastJson; @@ -525,7 +518,7 @@ public function addStreamToBroadcast(string $broadcastId, string $streamId, bool if ($response->getStatusCode() !== 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -557,7 +550,7 @@ public function removeStreamFromBroadcast(string $broadcastId, string $streamId) if ($response->getStatusCode() !== 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -565,7 +558,7 @@ public function removeStreamFromBroadcast(string $broadcastId, string $streamId) return true; } - public function getLayout($resourceId, $resourceType = 'broadcast') + public function getLayout(string $resourceId, string $resourceType = 'broadcast') { $request = new Request( 'GET', @@ -576,7 +569,7 @@ public function getLayout($resourceId, $resourceType = 'broadcast') 'debug' => $this->isDebug() ]); $layoutJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } return $layoutJson; @@ -593,7 +586,7 @@ public function updateLayout(string $resourceId, Layout $layout, string $resourc 'debug' => $this->isDebug(), 'json' => $layout->toArray() ]); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } } @@ -609,12 +602,12 @@ public function setArchiveLayout(string $archiveId, Layout $layout): void 'debug' => $this->isDebug(), 'json' => $layout->toArray() ]); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } } - public function updateStream($sessionId, $streamId, $properties) + public function updateStream(string $sessionId, string $streamId, $properties): void { $request = new Request( 'PUT', @@ -628,12 +621,12 @@ public function updateStream($sessionId, $streamId, $properties) if ($response->getStatusCode() != 204) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } } - public function getStream($sessionId, $streamId) + public function getStream(string $sessionId, string $streamId) { $request = new Request( 'GET', @@ -645,14 +638,14 @@ public function getStream($sessionId, $streamId) 'debug' => $this->isDebug() ]); $streamJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $streamJson; } - public function listStreams($sessionId) + public function listStreams(string $sessionId) { $request = new Request( 'GET', @@ -663,14 +656,14 @@ public function listStreams($sessionId) 'debug' => $this->isDebug(), ]); $streamListJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $streamListJson; } - public function listConnections($sessionId) + public function listConnections(string $sessionId) { $request = new Request( 'GET', @@ -681,18 +674,16 @@ public function listConnections($sessionId) 'debug' => $this->isDebug(), ]); $connectionListJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); - return; + return null; } return $connectionListJson; } - public function setStreamClassLists($sessionId, $payload) + public function setStreamClassLists(string $sessionId, $payload): void { - $itemsPayload = array( - 'items' => $payload - ); + $itemsPayload = ['items' => $payload]; $request = new Request( 'PUT', 'v2/project/' . $this->apiKey . '/session/' . $sessionId . '/stream' @@ -706,7 +697,7 @@ public function setStreamClassLists($sessionId, $payload) if ($response->getStatusCode() != 200) { json_decode($response->getBody(), true); } - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } } @@ -723,19 +714,11 @@ public function setStreamClassLists($sessionId, $payload) * @throws GlobalException * @throws GuzzleException */ - public function dial($sessionId, $token, $sipUri, $options) + public function dial($sessionId, $token, $sipUri, array $options) { - $body = array( - 'sessionId' => $sessionId, - 'token' => $token, - 'sip' => array( - 'uri' => $sipUri, - 'secure' => $options['secure'], - 'observeForceMute' => $options['observeForceMute'] - ) - ); + $body = ['sessionId' => $sessionId, 'token' => $token, 'sip' => ['uri' => $sipUri, 'secure' => $options['secure'], 'observeForceMute' => $options['observeForceMute']]]; - if (array_key_exists('headers', $options) && count($options['headers']) > 0) { + if (array_key_exists('headers', $options) && $options['headers'] !== []) { $body['sip']['headers'] = $options['headers']; } @@ -748,7 +731,7 @@ public function dial($sessionId, $token, $sipUri, $options) } if (array_key_exists('video', $options)) { - $body['sip']['video'] = (bool) $options['video']; + $body['sip']['video'] = $options['video']; } if (array_key_exists('streams', $options)) { @@ -764,7 +747,7 @@ public function dial($sessionId, $token, $sipUri, $options) 'json' => $body ]); $sipJson = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } @@ -791,7 +774,7 @@ public function playDTMF(string $sessionId, string $digits, string $connectionId 'digits' => $digits ] ]); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } } @@ -808,7 +791,7 @@ public function playDTMF(string $sessionId, string $digits, string $connectionId * @throws SignalNetworkConnectionException * @throws \Exception */ - public function signal($sessionId, $payload = [], $connectionId = null) + public function signal(string $sessionId, $payload = [], $connectionId = null): void { // set up the request $requestRoot = '/v2/project/' . $this->apiKey . '/session/' . $sessionId; @@ -830,7 +813,7 @@ public function signal($sessionId, $payload = [], $connectionId = null) $this->handleSignalingException($e); } catch (RequestException $e) { throw new SignalNetworkConnectionException('Unable to communicate with host', -1, $e); - } catch (\Exception $e) { + } catch (GlobalException $e) { throw $e; } } @@ -860,7 +843,7 @@ public function forceMuteStream(string $sessionId, string $streamId) 'debug' => $this->isDebug(), ]); $jsonResponse = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -880,7 +863,7 @@ public function forceMuteAll(string $sessionId, array $options) 'json' => $options ]); $jsonResponse = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -906,7 +889,7 @@ public function connectAudio(string $sessionId, string $token, array $websocketO 'json' => $body ]); $jsonResponse = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); return false; } @@ -921,8 +904,7 @@ public function startCaptions( ?int $maxDuration, ?bool $partialCaptions, ?string $statusCallbackUrl - ) - { + ) { $request = new Request( 'POST', '/v2/project/' . $this->apiKey . '/captions' @@ -955,14 +937,14 @@ public function startCaptions( 'json' => $body ]); $jsonResponse = json_decode($response->getBody(), true); - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } return $jsonResponse; } - public function stopCaptions(string $captionsId) + public function stopCaptions(string $captionsId): ?bool { $request = new Request( 'POST', @@ -974,12 +956,13 @@ public function stopCaptions(string $captionsId) 'debug' => $this->isDebug(), ]); return true; - } catch (\Exception $e) { + } catch (GlobalException $e) { $this->handleException($e); } + return null; } - private function handleException($e) + private function handleException($e): void { // TODO: test coverage if ($e instanceof ClientException) { @@ -988,17 +971,18 @@ private function handleException($e) throw new AuthenticationException( $this->apiKey, $this->apiSecret, - null, - $e - ); - } else { - throw new DomainException( - 'The OpenTok API request failed: ' . json_decode($e->getResponse()->getBody(true))->message, - null, - $e + $e, + null ); } - } elseif ($e instanceof ServerException) { + throw new DomainException( + 'The OpenTok API request failed: ' . json_decode($e->getResponse()->getBody(true))->message, + null, + $e + ); + } + // TODO: test coverage + if ($e instanceof ServerException) { // will catch all 5xx errors throw new UnexpectedValueException( 'The OpenTok API server responded with an error: ' . json_decode($e->getResponse()->getBody(true))->message, @@ -1007,16 +991,16 @@ private function handleException($e) ); } else { // TODO: check if this works because Exception is an interface not a class - throw new \Exception('An unexpected error occurred'); + throw new GlobalException('An unexpected error occurred'); } } - private function handleArchiveException($e) + private function handleArchiveException(Throwable $e): void { try { $this->handleException($e); } catch (AuthenticationException $ae) { - throw new ArchiveAuthenticationException($this->apiKey, $this->apiSecret, null, $ae->getPrevious()); + throw new ArchiveAuthenticationException($this->apiKey, $this->apiSecret, $ae->getPrevious(), null); } catch (DomainException $de) { throw new ArchiveDomainException($e->getMessage(), null, $de->getPrevious()); } catch (UnexpectedValueException $uve) { @@ -1027,12 +1011,12 @@ private function handleArchiveException($e) } } - private function handleBroadcastException($e) + private function handleBroadcastException(Throwable $e): void { try { $this->handleException($e); } catch (AuthenticationException $ae) { - throw new BroadcastAuthenticationException($this->apiKey, $this->apiSecret, null, $ae->getPrevious()); + throw new BroadcastAuthenticationException($this->apiKey, $this->apiSecret, $ae->getPrevious(), null); } catch (DomainException $de) { throw new BroadcastDomainException($e->getMessage(), null, $de->getPrevious()); } catch (UnexpectedValueException $uve) { @@ -1043,7 +1027,7 @@ private function handleBroadcastException($e) } } - private function handleSignalingException(ClientException $e) + private function handleSignalingException(ClientException $e): void { $responseCode = $e->getResponse()->getStatusCode(); switch ($responseCode) { @@ -1051,7 +1035,7 @@ private function handleSignalingException(ClientException $e) $message = 'One of the signal properties — data, type, sessionId or connectionId — is invalid.'; throw new SignalUnexpectedValueException($message, $responseCode); case 403: - throw new SignalAuthenticationException($this->apiKey, $this->apiSecret, null, $e); + throw new SignalAuthenticationException($this->apiKey, $this->apiSecret, $e, null); case 404: $message = 'The client specified by the connectionId property is not connected to the session.'; throw new SignalConnectionException($message, $responseCode); @@ -1064,7 +1048,7 @@ private function handleSignalingException(ClientException $e) } } - private function handleForceDisconnectException($e): void + private function handleForceDisconnectException(Throwable $e): void { $responseCode = $e->getResponse()->getStatusCode(); switch ($responseCode) { @@ -1072,7 +1056,7 @@ private function handleForceDisconnectException($e): void $message = 'One of the arguments — sessionId or connectionId — is invalid.'; throw new ForceDisconnectUnexpectedValueException($message, $responseCode); case 403: - throw new ForceDisconnectAuthenticationException($this->apiKey, $this->apiSecret, null, $e); + throw new ForceDisconnectAuthenticationException($this->apiKey, $this->apiSecret, $e, null); case 404: $message = 'The client specified by the connectionId property is not connected to the session.'; throw new ForceDisconnectConnectionException($message, $responseCode); @@ -1081,22 +1065,22 @@ private function handleForceDisconnectException($e): void } } - private function handleRenderException($e): void + private function handleRenderException(Throwable $e): void { $responseCode = $e->getResponse()->getStatusCode(); switch ($responseCode) { case 400: throw new InvalidArgumentException('There was an error with the parameters supplied.'); case 403: - throw new AuthenticationException($this->apiKey, $this->apiSecret, null, $e); + throw new AuthenticationException($this->apiKey, $this->apiSecret, $e, null); case 500: - throw new \Exception('There is an error with the Video Platform'); + throw new GlobalException('There is an error with the Video Platform'); default: break; } } - private function isDebug() + private function isDebug(): bool { return defined('OPENTOK_DEBUG'); } diff --git a/src/OpenTok/Util/Validators.php b/src/OpenTok/Util/Validators.php index bb77f57d..1819ac4f 100755 --- a/src/OpenTok/Util/Validators.php +++ b/src/OpenTok/Util/Validators.php @@ -2,6 +2,7 @@ namespace OpenTok\Util; +use OutOfBoundsException; use OpenTok\Archive; use OpenTok\Util\Client; use OpenTok\Layout; @@ -66,7 +67,7 @@ private static function isValidPrivateKey(string $filePath): bool return (bool) preg_match('/^-----BEGIN PRIVATE KEY-----[\s\S]+-----END PRIVATE KEY-----$/m', trim($keyContents)); } - public static function validateForceMuteAllOptions(array $options) + public static function validateForceMuteAllOptions(array $options): void { $validOptions = [ 'excludedStreams' => 'array', @@ -74,11 +75,13 @@ public static function validateForceMuteAllOptions(array $options) ]; foreach ($validOptions as $optionName => $optionType) { - if (isset($options[$optionName])) { - if (getType($options[$optionName]) !== $optionType) { - throw new InvalidArgumentException('Invalid type given in options for: ' . $options[$optionName]); - } + if (!isset($options[$optionName])) { + continue; + } + if (getType($options[$optionName]) === $optionType) { + continue; } + throw new InvalidArgumentException('Invalid type given in options for: ' . $options[$optionName]); } if (isset($options['excludedStreams'])) { @@ -88,7 +91,7 @@ public static function validateForceMuteAllOptions(array $options) } } - public static function validateApiUrl($apiUrl) + public static function validateApiUrl($apiUrl): void { if (!(is_string($apiUrl) && filter_var($apiUrl, FILTER_VALIDATE_URL))) { throw new InvalidArgumentException( @@ -97,7 +100,7 @@ public static function validateApiUrl($apiUrl) } } - public static function validateClient($client) + public static function validateClient($client): void { if (isset($client) && !($client instanceof Client)) { throw new InvalidArgumentException( @@ -105,24 +108,24 @@ public static function validateClient($client) ); } } - public static function validateSessionId($sessionId) + public static function validateSessionId($sessionId): void { - if (!is_string($sessionId) || empty($sessionId)) { + if (!is_string($sessionId) || ($sessionId === '' || $sessionId === '0')) { throw new InvalidArgumentException( 'Null or empty session ID is not valid: ' . print_r($sessionId, true) ); } } - public static function validateConnectionId($connectionId) + public static function validateConnectionId($connectionId): void { - if (!is_string($connectionId) || empty($connectionId)) { + if (!is_string($connectionId) || ($connectionId === '' || $connectionId === '0')) { throw new InvalidArgumentException( 'Null or empty connection ID is not valid: ' . print_r($connectionId, true) ); } } - public static function validateHasStreamMode($streamMode) + public static function validateHasStreamMode($streamMode): void { if (!is_string($streamMode)) { throw new InvalidArgumentException( @@ -137,22 +140,22 @@ public static function validateHasStreamMode($streamMode) } } - public static function validateSignalPayload($payload) + public static function validateSignalPayload($payload): void { - list($type, $data) = array_values($payload); + [$type, $data] = array_values($payload); if (!is_string($data) || is_null($data || is_null($type))) { throw new InvalidArgumentException( 'Signal Payload cannot be null: ' . print_r($payload, true) ); } } - public static function validateRole($role) + public static function validateRole($role): void { if (!Role::isValidValue($role)) { throw new InvalidArgumentException('Unknown role: ' . print_r($role, true)); } } - public static function validateExpireTime($expireTime, $createTime) + public static function validateExpireTime($expireTime, $createTime): void { if (!is_null($expireTime)) { if (!is_numeric($expireTime)) { @@ -173,7 +176,7 @@ public static function validateExpireTime($expireTime, $createTime) } } } - public static function validateData($data) + public static function validateData($data): void { if ($data != null) { if (!is_string($data)) { @@ -181,7 +184,7 @@ public static function validateData($data) 'Connection data must be a string. data:' . print_r($data, true) ); } - if (!empty($data)) { + if ($data !== '0') { $dataLength = strlen($data); if ($dataLength > 1000) { throw new InvalidArgumentException( @@ -191,7 +194,7 @@ public static function validateData($data) } } } - public static function validateArchiveName($name) + public static function validateArchiveName($name): void { if ($name != null && !is_string($name) /* TODO: length? */) { throw new InvalidArgumentException( @@ -199,7 +202,7 @@ public static function validateArchiveName($name) ); } } - public static function validateArchiveHasVideo($hasVideo) + public static function validateArchiveHasVideo($hasVideo): void { if (!is_bool($hasVideo)) { throw new InvalidArgumentException( @@ -207,7 +210,7 @@ public static function validateArchiveHasVideo($hasVideo) ); } } - public static function validateArchiveHasAudio($hasAudio) + public static function validateArchiveHasAudio($hasAudio): void { if (!is_bool($hasAudio)) { throw new InvalidArgumentException( @@ -215,13 +218,13 @@ public static function validateArchiveHasAudio($hasAudio) ); } } - public static function validateArchiveOutputMode($outputMode) + public static function validateArchiveOutputMode($outputMode): void { if (!OutputMode::isValidValue($outputMode)) { throw new InvalidArgumentException('Unknown output mode: ' . print_r($outputMode, true)); } } - public static function validateArchiveId($archiveId) + public static function validateArchiveId($archiveId): void { if (!is_string($archiveId) || preg_match(self::$guidRegEx, $archiveId)) { throw new InvalidArgumentException( @@ -229,7 +232,7 @@ public static function validateArchiveId($archiveId) ); } } - public static function validateArchiveData($archiveData) + public static function validateArchiveData($archiveData): void { if (!self::$archiveSchemaUri) { self::$archiveSchemaUri = __DIR__ . '/archive-schema.json'; @@ -247,7 +250,7 @@ public static function validateArchiveData($archiveData) ); } } - public static function validateArchiveListData($archiveListData) + public static function validateArchiveListData($archiveListData): void { if (!self::$archiveSchemaUri) { self::$archiveSchemaUri = __DIR__ . '/archive-schema.json'; @@ -263,7 +266,7 @@ public static function validateArchiveListData($archiveListData) ); } } - public static function validateOffsetAndCount($offset, $count) + public static function validateOffsetAndCount($offset, $count): void { if ( (!is_numeric($offset) || $offset < 0 ) || @@ -274,7 +277,7 @@ public static function validateOffsetAndCount($offset, $count) ); } } - public static function validateSessionIdBelongsToKey($sessionId, $apiKey) + public static function validateSessionIdBelongsToKey($sessionId, $apiKey): void { self::validateSessionId($sessionId); $sessionIdParts = self::decodeSessionId($sessionId); @@ -284,7 +287,7 @@ public static function validateSessionIdBelongsToKey($sessionId, $apiKey) ); } } - public static function validateMediaMode($mediaMode) + public static function validateMediaMode($mediaMode): void { if (!MediaMode::isValidValue($mediaMode)) { throw new InvalidArgumentException( @@ -293,7 +296,7 @@ public static function validateMediaMode($mediaMode) } } - public static function validateArchiveMode($archiveMode) + public static function validateArchiveMode($archiveMode): void { if (!ArchiveMode::isValidValue($archiveMode)) { throw new InvalidArgumentException( @@ -302,7 +305,7 @@ public static function validateArchiveMode($archiveMode) } } - public static function validateAutoArchiveMode($archiveMode, $options) + public static function validateAutoArchiveMode($archiveMode, array $options): void { if ($archiveMode === ArchiveMode::MANUAL) { foreach (['archiveName', 'archiveResolution'] as $key) { @@ -317,7 +320,7 @@ public static function validateAutoArchiveMode($archiveMode, $options) } } - public static function validateLocation($location) + public static function validateLocation($location): void { if ($location != null && !filter_var($location, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { throw new InvalidArgumentException( @@ -325,7 +328,7 @@ public static function validateLocation($location) ); } } - public static function validateOpenTok($opentok) + public static function validateOpenTok($opentok): void { if (!($opentok instanceof OpenTok)) { throw new InvalidArgumentException( @@ -334,7 +337,7 @@ public static function validateOpenTok($opentok) } } - public static function validateBroadcastData($broadcastData) + public static function validateBroadcastData($broadcastData): void { if (!self::$broadcastSchemaUri) { self::$broadcastSchemaUri = __DIR__ . '/broadcast-schema.json'; @@ -351,14 +354,14 @@ public static function validateBroadcastData($broadcastData) } } - public static function validateRtmpStreams(array $rtmpData) + public static function validateRtmpStreams(array $rtmpData): void { if (count($rtmpData) > 5) { throw new InvalidArgumentException('The maximum permitted RTMP Streams is set to 5'); } } - public static function validateBroadcastId($broadcastId) + public static function validateBroadcastId($broadcastId): void { if (!is_string($broadcastId) || preg_match(self::$guidRegEx, $broadcastId)) { throw new InvalidArgumentException( @@ -367,18 +370,18 @@ public static function validateBroadcastId($broadcastId) } } - public static function validateBroadcastOutputOptions(array $outputOptions) - { - if ( - isset($outputOptions['lowLatency'], $outputOptions['dvr']) - && $outputOptions['lowLatency'] === true && $outputOptions['dvr'] === true - ) { - throw new InvalidArgumentException('When starting in HLS mode, DVR AND lowLatency + public static function validateBroadcastOutputOptions(array $outputOptions): void + { + if ( + isset($outputOptions['lowLatency'], $outputOptions['dvr']) + && $outputOptions['lowLatency'] === true && $outputOptions['dvr'] === true + ) { + throw new InvalidArgumentException('When starting in HLS mode, DVR AND lowLatency cannot both be true'); - } - } + } + } - public static function validateLayout($layout) + public static function validateLayout($layout): void { if (!($layout instanceof Layout)) { throw new InvalidArgumentException( @@ -387,14 +390,14 @@ public static function validateLayout($layout) } } - public static function validateLayoutStylesheet($stylesheet) + public static function validateLayoutStylesheet($stylesheet): void { if (!(is_string($stylesheet))) { throw new InvalidArgumentException('The stylesheet was not a string: ' . print_r($stylesheet, true)); } } - public static function validateResolution($resolution) + public static function validateResolution($resolution): void { if (!(is_string($resolution))) { throw new InvalidArgumentException('The resolution was not a string: ' . print_r($resolution, true)); @@ -414,23 +417,21 @@ public static function validateResolution($resolution) } } - public static function validateStreamId($streamId) + public static function validateStreamId($streamId): void { - if (!(is_string($streamId)) || empty($streamId)) { + if (!(is_string($streamId)) || ($streamId === '' || $streamId === '0')) { throw new InvalidArgumentException('The streamId was not a string: ' . print_r($streamId, true)); } } - public static function validateLayoutClassList($layoutClassList, $format = 'JSON') + public static function validateLayoutClassList($layoutClassList, $format = 'JSON'): void { - if ($format === 'JSON') { - if (!is_array($layoutClassList) || self::isAssoc($layoutClassList)) { - throw new InvalidArgumentException('The layoutClassList was not a valid JSON array: ' . print_r($layoutClassList, true)); - } + if ($format === 'JSON' && (!is_array($layoutClassList) || self::isAssoc($layoutClassList))) { + throw new InvalidArgumentException('The layoutClassList was not a valid JSON array: ' . print_r($layoutClassList, true)); } } - public static function validateWebsocketOptions(array $websocketOptions) + public static function validateWebsocketOptions(array $websocketOptions): void { if (!array_key_exists('uri', $websocketOptions)) { throw new InvalidArgumentException('Websocket configuration must have a uri'); @@ -440,14 +441,14 @@ public static function validateWebsocketOptions(array $websocketOptions) } } - public static function validateAutoArchiveResolution($archiveResolution) + public static function validateAutoArchiveResolution(string $archiveResolution): void { if (! in_array($archiveResolution, Archive::getPermittedResolutions(), true)) { throw new InvalidArgumentException($archiveResolution . ' is not a valid resolution'); } } - public static function validateLayoutClassListItem($layoutClassList) + public static function validateLayoutClassListItem($layoutClassList): void { if (!is_array($layoutClassList)) { throw new InvalidArgumentException('Each element in the streamClassArray must have a layoutClassList array.'); @@ -466,7 +467,7 @@ public static function validateLayoutClassListItem($layoutClassList) } } - public static function validateDefaultTimeout($timeout) + public static function validateDefaultTimeout($timeout): void { // Guzzle defaults to "null" instead of 0, so allowing that through if (is_null($timeout)) { @@ -502,11 +503,14 @@ function array_is_list(array $arr): bool return !array_is_list($arr); } - protected static function decodeSessionId($sessionId) + /** + * @return mixed[] + */ + protected static function decodeSessionId($sessionId): array { - $trimmedSessionId = substr($sessionId, 2); + $trimmedSessionId = substr((string) $sessionId, 2); $parts = explode('-', $trimmedSessionId); - $data = array(); + $data = []; foreach ($parts as $part) { $decodedPart = base64_decode($part); $dataItems = explode('~', $decodedPart); @@ -522,11 +526,11 @@ public static function validateBroadcastBitrate($maxBitRate): void } if ($maxBitRate < 400000 && $maxBitRate > 2000000) { - throw new \OutOfBoundsException('Max Bitrate must be between 400000 and 2000000'); + throw new OutOfBoundsException('Max Bitrate must be between 400000 and 2000000'); } } - public static function validateArchiveHasTranscription($hasTranscription) + public static function validateArchiveHasTranscription($hasTranscription): void { if (!is_bool($hasTranscription)) { throw new InvalidArgumentException( @@ -535,7 +539,7 @@ public static function validateArchiveHasTranscription($hasTranscription) } } - public static function validateArchiveTranscriptionProperties($transcriptionProperties) + public static function validateArchiveTranscriptionProperties($transcriptionProperties): void { if ($transcriptionProperties === null) { return; @@ -547,21 +551,19 @@ public static function validateArchiveTranscriptionProperties($transcriptionProp ); } - if (isset($transcriptionProperties['primaryLanguageCode'])) { - if (!is_string($transcriptionProperties['primaryLanguageCode']) || - empty($transcriptionProperties['primaryLanguageCode'])) { - throw new InvalidArgumentException( - 'primaryLanguageCode must be a non-empty string in BCP-47 format.' - ); - } + if ( + isset($transcriptionProperties['primaryLanguageCode']) && (!is_string($transcriptionProperties['primaryLanguageCode']) || + empty($transcriptionProperties['primaryLanguageCode'])) + ) { + throw new InvalidArgumentException( + 'primaryLanguageCode must be a non-empty string in BCP-47 format.' + ); } - if (isset($transcriptionProperties['hasSummary'])) { - if (!is_bool($transcriptionProperties['hasSummary'])) { - throw new InvalidArgumentException( - 'hasSummary must be either true or false.' - ); - } + if (isset($transcriptionProperties['hasSummary']) && !is_bool($transcriptionProperties['hasSummary'])) { + throw new InvalidArgumentException( + 'hasSummary must be either true or false.' + ); } } } diff --git a/tests/OpenTokTest/ArchiveTest.php b/tests/OpenTokTest/ArchiveTest.php index 909a39f2..c0b142da 100644 --- a/tests/OpenTokTest/ArchiveTest.php +++ b/tests/OpenTokTest/ArchiveTest.php @@ -15,6 +15,7 @@ class ArchiveTest extends TestCase { + public $historyContainer; // Fixtures protected $archiveData; protected $API_KEY; @@ -30,51 +31,25 @@ public static function setUpBeforeClass(): void self::$mockBasePath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'mock' . DIRECTORY_SEPARATOR; } - public function setupArchives($streamMode, $quantization = false) + public function setupArchives($streamMode, $quantization = false): void { // Set up fixtures - $this->archiveData = array( - 'createdAt' => 1394394801000, - 'duration' => 0, - 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', - 'name' => 'showtime', - 'partnerId' => 854511, - 'reason' => '', - 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', - 'size' => 0, - 'status' => 'started', - 'url' => null, - 'hasVideo' => false, - 'hasAudio' => true, - 'outputMode' => 'composed', - 'resolution' => '640x480', - 'streamMode' => $streamMode, - 'multiArchiveTag' => true, - 'maxBitrate' => 400000, - ); + $this->archiveData = ['createdAt' => 1394394801000, 'duration' => 0, 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', 'name' => 'showtime', 'partnerId' => 854511, 'reason' => '', 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', 'size' => 0, 'status' => 'started', 'url' => null, 'hasVideo' => false, 'hasAudio' => true, 'outputMode' => 'composed', 'resolution' => '640x480', 'streamMode' => $streamMode, 'multiArchiveTag' => true, 'maxBitrate' => 400000]; if ($quantization) { unset($this->archiveData['maxBitrate']); $this->archiveData['quantizationParameter'] = 40; } - $this->archive = new Archive($this->archiveData, array( - 'apiKey' => $this->API_KEY, - 'apiSecret' => $this->API_SECRET, - 'client' => $this->client - )); + $this->archive = new Archive($this->archiveData, ['apiKey' => $this->API_KEY, 'apiSecret' => $this->API_SECRET, 'client' => $this->client]); } - private function setupOTWithMocks($mocks) + private function setupOTWithMocks(array $mocks): void { $this->API_KEY = defined('API_KEY') ? API_KEY : '12345678'; $this->API_SECRET = defined('API_SECRET') ? API_SECRET : 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - if (is_array($mocks)) { - $responses = TestHelpers::mocksToResponses($mocks, self::$mockBasePath); - } else { - $responses = []; - } + $responses = is_array($mocks) ? TestHelpers::mocksToResponses($mocks, self::$mockBasePath) : []; $mock = new MockHandler($responses); $handlerStack = HandlerStack::create($mock); @@ -102,7 +77,7 @@ private function setupOT() return $this->setupOTWithMocks([]); } - public function testInitializes() + public function testInitializes(): void { // Arrange $this->setupOT(); @@ -112,7 +87,7 @@ public function testInitializes() $this->assertInstanceOf(Archive::class, $this->archive); } - public function testReadsProperties() + public function testReadsProperties(): void { $this->setupOT(); $this->setupArchives(StreamMode::AUTO); @@ -139,7 +114,7 @@ public function testReadsProperties() $this->assertEquals($this->archiveData['quantizationParameter'], $this->archive->quantizationParameter); } - public function testStopsArchive() + public function testStopsArchive(): void { // Arrange $this->setupOTWithMocks([[ @@ -158,7 +133,7 @@ public function testStopsArchive() $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/'.$this->API_KEY.'/archive/'.$this->archiveData['id'].'/stop', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -253,7 +228,7 @@ public function testCanRemoveStreamFromArchive(): void $this->assertTrue($return); } - public function testDeletesArchive() + public function testDeletesArchive(): void { // Arrange $this->setupOTWithMocks([[ @@ -270,7 +245,7 @@ public function testDeletesArchive() $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('DELETE', strtoupper($request->getMethod())); + $this->assertEquals('DELETE', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/'.$this->API_KEY.'/archive/'.$this->archiveData['id'], $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -286,89 +261,43 @@ public function testDeletesArchive() // TODO: assert that all properties of the archive object were cleared } - public function testAllowsUnknownProperties() + public function testAllowsUnknownProperties(): void { $this->setupOT(); // Set up fixtures - $archiveData = array( - 'createdAt' => 1394394801000, - 'duration' => 0, - 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', - 'name' => 'showtime', - 'partnerId' => 854511, - 'reason' => '', - 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', - 'size' => 0, - 'status' => 'started', - 'url' => null, - 'notarealproperty' => 'not a real value' - ); + $archiveData = ['createdAt' => 1394394801000, 'duration' => 0, 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', 'name' => 'showtime', 'partnerId' => 854511, 'reason' => '', 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', 'size' => 0, 'status' => 'started', 'url' => null, 'notarealproperty' => 'not a real value']; - $archive = new Archive($archiveData, array( - 'apiKey' => $this->API_KEY, - 'apiSecret' => $this->API_SECRET, - 'client' => $this->client - )); + $archive = new Archive($archiveData, ['apiKey' => $this->API_KEY, 'apiSecret' => $this->API_SECRET, 'client' => $this->client]); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); } - public function testRejectsBadArchiveData() + public function testRejectsBadArchiveData(): void { $this->expectException('InvalidArgumentException'); $this->setupOT(); // Set up fixtures - $badArchiveData = array( - 'createdAt' => 'imnotanumber', - 'duration' => 0, - 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', - 'name' => 'showtime', - 'partnerId' => 854511, - 'reason' => '', - 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', - 'size' => 0, - 'status' => 'started', - 'url' => null - ); + $badArchiveData = ['createdAt' => 'imnotanumber', 'duration' => 0, 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', 'name' => 'showtime', 'partnerId' => 854511, 'reason' => '', 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', 'size' => 0, 'status' => 'started', 'url' => null]; - $archive = new Archive($badArchiveData, array( - 'apiKey' => $this->API_KEY, - 'apiSecret' => $this->API_SECRET, - 'client' => $this->client - )); + new Archive($badArchiveData, ['apiKey' => $this->API_KEY, 'apiSecret' => $this->API_SECRET, 'client' => $this->client]); } - public function testAllowsPausedStatus() + public function testAllowsPausedStatus(): void { $this->setupOT(); // Set up fixtures - $archiveData = array( - 'createdAt' => 1394394801000, - 'duration' => 0, - 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', - 'name' => 'showtime', - 'partnerId' => 854511, - 'reason' => '', - 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', - 'size' => 0, - 'status' => 'paused', - 'url' => null, - ); + $archiveData = ['createdAt' => 1394394801000, 'duration' => 0, 'id' => '063e72a4-64b4-43c8-9da5-eca071daab89', 'name' => 'showtime', 'partnerId' => 854511, 'reason' => '', 'sessionId' => '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-', 'size' => 0, 'status' => 'paused', 'url' => null]; - $archive = new Archive($archiveData, array( - 'apiKey' => $this->API_KEY, - 'apiSecret' => $this->API_SECRET, - 'client' => $this->client - )); + $archive = new Archive($archiveData, ['apiKey' => $this->API_KEY, 'apiSecret' => $this->API_SECRET, 'client' => $this->client]); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals($archiveData['status'], $archive->status); } - public function testSerializesToJson() + public function testSerializesToJson(): void { // Arrange $this->setupOT(); @@ -382,7 +311,7 @@ public function testSerializesToJson() $this->assertNotNull(json_encode($archiveJson)); } - public function testSerializedToArray() + public function testSerializedToArray(): void { // Arrange $this->setupOT(); diff --git a/tests/OpenTokTest/BroadcastTest.php b/tests/OpenTokTest/BroadcastTest.php index 85afc410..2831fec1 100644 --- a/tests/OpenTokTest/BroadcastTest.php +++ b/tests/OpenTokTest/BroadcastTest.php @@ -21,10 +21,7 @@ class BroadcastTest extends TestCase protected $client; protected static $mockBasePath; - /** - * @var array - */ - private $historyContainer; + private ?array $historyContainer = null; public function setUp(): void { @@ -54,28 +51,20 @@ public static function setUpBeforeClass(): void self::$mockBasePath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'mock' . DIRECTORY_SEPARATOR; } - public function setupBroadcasts($streamMode) + public function setupBroadcasts($streamMode): void { $data = $this->broadcastData; $data['streamMode'] = $streamMode; - $this->broadcast = new Broadcast($data, array( - 'apiKey' => $this->API_KEY, - 'apiSecret' => $this->API_SECRET, - 'client' => $this->client - )); + $this->broadcast = new Broadcast($data, ['apiKey' => $this->API_KEY, 'apiSecret' => $this->API_SECRET, 'client' => $this->client]); } - private function setupOTWithMocks($mocks) + private function setupOTWithMocks(array $mocks): void { $this->API_KEY = defined('API_KEY') ? API_KEY : '12345678'; $this->API_SECRET = defined('API_SECRET') ? API_SECRET : 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - if (is_array($mocks)) { - $responses = TestHelpers::mocksToResponses($mocks, self::$mockBasePath); - } else { - $responses = []; - } + $responses = is_array($mocks) ? TestHelpers::mocksToResponses($mocks, self::$mockBasePath) : []; $mock = new MockHandler($responses); $handlerStack = HandlerStack::create($mock); @@ -203,7 +192,7 @@ public function testCannotRemoveStreamFromBroadcastOnAuto(): void $this->setupBroadcasts(StreamMode::AUTO); - $return = $this->broadcast->removeStreamFromBroadcast( + $this->broadcast->removeStreamFromBroadcast( '5dfds4-asdda4asf4' ); } diff --git a/tests/OpenTokTest/LayoutTest.php b/tests/OpenTokTest/LayoutTest.php index 60a59250..06a5e7c1 100644 --- a/tests/OpenTokTest/LayoutTest.php +++ b/tests/OpenTokTest/LayoutTest.php @@ -2,13 +2,15 @@ namespace OpenTokTest; +use InvalidArgumentException; +use RuntimeException; use OpenTok\Layout; use OpenTok\Util\Validators; -use PHPStan\Testing\TestCase; +use PHPUnit\Framework\TestCase; class LayoutTest extends TestCase { - public function testStylesheetIsNotInSerializedArrayIfNotCustom() + public function testStylesheetIsNotInSerializedArrayIfNotCustom(): void { $layouts = [ Layout::LAYOUT_BESTFIT => Layout::getBestFit(), @@ -24,20 +26,20 @@ public function testStylesheetIsNotInSerializedArrayIfNotCustom() public function testWillValidateLayout(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $object = ['bestFit' => true]; Validators::validateLayout($object); } - public function testStylesheetIsInSerializedArrayIfCustom() + public function testStylesheetIsInSerializedArrayIfCustom(): void { $layout = Layout::createCustom(['stylesheet' => 'foo']); $this->assertSame(['type' => LAYOUT::LAYOUT_CUSTOM, 'stylesheet' => 'foo'], $layout->toArray()); } - public function testScreenshareTypeSerializesProperly() + public function testScreenshareTypeSerializesProperly(): void { $layout = Layout::getBestFit(); $layout->setScreenshareType(Layout::LAYOUT_PIP); @@ -50,18 +52,18 @@ public function testScreenshareTypeSerializesProperly() $this->assertSame($expected, $layout->toArray()); } - public function testScreenshareTypeCannotBeSetToInvalidValue() + public function testScreenshareTypeCannotBeSetToInvalidValue(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Screenshare type must be of a valid layout type'); $layout = Layout::getBestFit(); $layout->setScreenshareType('bar'); } - public function testScreenshareTypeCannotBeSetOnInvalidLayoutType() + public function testScreenshareTypeCannotBeSetOnInvalidLayoutType(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Screenshare type cannot be set on a layout type other than bestFit'); $layout = Layout::createCustom(['stylesheet' => 'foo']); diff --git a/tests/OpenTokTest/OpenTokTest.php b/tests/OpenTokTest/OpenTokTest.php index b74a4ef5..ad9814df 100644 --- a/tests/OpenTokTest/OpenTokTest.php +++ b/tests/OpenTokTest/OpenTokTest.php @@ -2,6 +2,20 @@ namespace OpenTokTest; +use OpenTok\Archive; +use OpenTok\ArchiveList; +use OpenTok\Exception\ForceDisconnectConnectionException; +use OpenTok\Broadcast; +use TypeError; +use OpenTok\Stream; +use OpenTok\SipCall; +use Exception; +use OpenTok\Exception\SignalConnectionException; +use OpenTok\Exception\SignalUnexpectedValueException; +use OpenTok\StreamList; +use OpenTok\ConnectionList; +use OpenTok\Connection; +use ReflectionClass; use Firebase\JWT\JWT; use Firebase\JWT\Key; use Lcobucci\JWT\Configuration; @@ -48,16 +62,12 @@ public static function setUpBeforeClass(): void self::$mockBasePath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'mock' . DIRECTORY_SEPARATOR; } - private function setupOTWithMocks($mocks, $customAgent = false, $vonageVideo = false): void + private function setupOTWithMocks(array $mocks, $customAgent = false, bool $vonageVideo = false): void { $this->API_KEY = defined('API_KEY') ? API_KEY : '12345678'; $this->API_SECRET = defined('API_SECRET') ? API_SECRET : 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - if (is_array($mocks)) { - $responses = TestHelpers::mocksToResponses($mocks, self::$mockBasePath); - } else { - $responses = []; - } + $responses = is_array($mocks) ? TestHelpers::mocksToResponses($mocks, self::$mockBasePath) : []; $mock = new MockHandler($responses); $handlerStack = HandlerStack::create($mock); @@ -71,7 +81,7 @@ private function setupOTWithMocks($mocks, $customAgent = false, $vonageVideo = f $apiUrl = 'https://api.opentok.com'; - if ($vonageVideo === true) { + if ($vonageVideo) { $apiUrl = 'https://video.vonage.com'; $this->API_KEY = '1ab38a10-ed9d-4e2b-8b14-95e52d76a13c'; $this->API_SECRET = __DIR__ . '/test.key'; @@ -91,7 +101,7 @@ private function setupOTWithMocks($mocks, $customAgent = false, $vonageVideo = f $history = Middleware::history($this->historyContainer); $handlerStack->push($history); - $this->opentok = new OpenTok($this->API_KEY, $this->API_SECRET, array('client' => $this->client)); + $this->opentok = new OpenTok($this->API_KEY, $this->API_SECRET, ['client' => $this->client]); } private function setupOT(): void @@ -102,7 +112,7 @@ private function setupOT(): void public function testCanBeInitialized(): void { $this->setupOT(); - $this->assertInstanceOf('OpenTok\OpenTok', $this->opentok); + $this->assertInstanceOf(OpenTok::class, $this->opentok); } public function testFailsOnInvalidInitialization(): void @@ -114,7 +124,7 @@ public function testFailsOnInvalidInitialization(): void } else { $this->expectException(PHPUnit_Framework_Error_Warning::class); } - $opentok = new OpenTok(); + new OpenTok(); } public function testCanStartRender(): void @@ -133,10 +143,7 @@ public function testCanStartRender(): void 'https://webapp.customer.com', 2900, '1280x720', - 'https://sendcallbacks.to.me', - [ - 'name' => 'Composed stream for live event' - ] + 'https://sendcallbacks.to.me' ); $this->assertInstanceOf(Render::class, $render); $this->assertEquals('2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4', $render->sessionId); @@ -159,10 +166,7 @@ public function testCanUseVonageAuth(): void 'https://webapp.customer.com', 2900, '1280x720', - 'https://sendcallbacks.to.me', - [ - 'name' => 'Composed stream for live event' - ] + 'https://sendcallbacks.to.me' ); $this->assertInstanceOf(Render::class, $render); @@ -265,7 +269,7 @@ public function testCreatesDefaultSession(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -279,7 +283,7 @@ public function testCreatesDefaultSession(): void $e2ee = $this->getPostField($request, 'e2ee'); $this->assertEquals('false', $e2ee); - $this->assertInstanceOf('OpenTok\Session', $session); + $this->assertInstanceOf(Session::class, $session); // NOTE: this is an actual sessionId from the recorded response, this doesn't correspond to // the API Key and API Secret used to create the session. $this->assertEquals( @@ -312,7 +316,7 @@ public function testCanStartAutoSessionWithArchiveNameAndResolution(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -325,7 +329,7 @@ public function testCanStartAutoSessionWithArchiveNameAndResolution(): void $this->assertEquals('640x480', $this->getPostField($request, 'archiveResolution')); - $this->assertInstanceOf('OpenTok\Session', $session); + $this->assertInstanceOf(Session::class, $session); } public function testCannotStartSessionWithArchiveNameInManualMode(): void @@ -346,7 +350,7 @@ public function testCannotStartSessionWithArchiveNameInManualMode(): void ]; // Act - $session = $this->opentok->createSession($options); + $this->opentok->createSession($options); } public function testCannotStartSessionWithArchiveResolutionInManualMode(): void @@ -367,7 +371,7 @@ public function testCannotStartSessionWithArchiveResolutionInManualMode(): void ]; // Act - $session = $this->opentok->createSession($options); + $this->opentok->createSession($options); } public function testCannotStartSessionWithInvalidResolutionInAutoArchive(): void @@ -389,7 +393,7 @@ public function testCannotStartSessionWithInvalidResolutionInAutoArchive(): void ]; // Act - $session = $this->opentok->createSession($options); + $this->opentok->createSession($options); } public function testCreatesE2EESession(): void @@ -408,7 +412,7 @@ public function testCreatesE2EESession(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -442,7 +446,7 @@ public function testCannotStartE2EESessionWithWrongMediaMode(): void 'path' => 'session/create/relayed' ]]); - $session = $this->opentok->createSession( + $this->opentok->createSession( [ 'mediaMode' => MediaMode::RELAYED, 'e2ee' => true @@ -463,7 +467,7 @@ public function testCannotStartE2EESessionWithWrongArchiveMode(): void 'path' => 'session/create/relayed' ]]); - $session = $this->opentok->createSession( + $this->opentok->createSession( [ 'archiveMode' => ArchiveMode::ALWAYS, 'e2ee' => true @@ -471,18 +475,14 @@ public function testCannotStartE2EESessionWithWrongArchiveMode(): void ); } - private function getPostField($request, $targetKey) + private function getPostField($request, string $targetKey) { - $params = array_map(function ($item) { - return explode('=', $item); - }, explode('&', (string) $request->getBody())); + $params = array_map(fn($item): array => explode('=', (string) $item), explode('&', (string) $request->getBody())); $found = array_values(array_filter( $params, - function ($item) use ($targetKey) { - return is_array($item) ? $item[0] === $targetKey : false; - } + fn($item): bool => is_array($item) && $item[0] === $targetKey )); - return count($found) > 0 ? $found[0][1] : ''; + return $found !== [] ? $found[0][1] : ''; } public function testCreatesMediaRoutedAndLocationSession(): void @@ -497,16 +497,13 @@ public function testCreatesMediaRoutedAndLocationSession(): void ]]); // Act - $session = $this->opentok->createSession(array( - 'location' => '12.34.56.78', - 'mediaMode' => MediaMode::ROUTED - )); + $session = $this->opentok->createSession(['location' => '12.34.56.78', 'mediaMode' => MediaMode::ROUTED]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -520,7 +517,7 @@ public function testCreatesMediaRoutedAndLocationSession(): void $p2p_preference = $this->getPostField($request, 'p2p.preference'); $this->assertEquals('disabled', $p2p_preference); - $this->assertInstanceOf('OpenTok\Session', $session); + $this->assertInstanceOf(Session::class, $session); // NOTE: this is an actual sessionId from the recorded response, this doesn't correspond to // the API Key and API Secret used to create the session. $this->assertEquals( @@ -541,15 +538,13 @@ public function testCreatesMediaRelayedSession(): void ]]); // Act - $session = $this->opentok->createSession(array( - 'mediaMode' => MediaMode::RELAYED - )); + $session = $this->opentok->createSession(['mediaMode' => MediaMode::RELAYED]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -560,7 +555,7 @@ public function testCreatesMediaRelayedSession(): void $p2p_preference = $this->getPostField($request, 'p2p.preference'); $this->assertEquals('enabled', $p2p_preference); - $this->assertInstanceOf('OpenTok\Session', $session); + $this->assertInstanceOf(Session::class, $session); // NOTE: this is an actual sessionId from the recorded response, this doesn't correspond to // the API Key and API Secret used to create the session. $this->assertEquals( @@ -581,15 +576,13 @@ public function testCreatesAutoArchivedSession(): void ]]); // Act - $session = $this->opentok->createSession(array( - 'archiveMode' => ArchiveMode::ALWAYS - )); + $session = $this->opentok->createSession(['archiveMode' => ArchiveMode::ALWAYS]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/session/create', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -603,7 +596,7 @@ public function testCreatesAutoArchivedSession(): void $mediaMode = $this->getPostField($request, 'p2p.preference'); $this->assertNotEquals('enabled', $mediaMode); - $this->assertInstanceOf('OpenTok\Session', $session); + $this->assertInstanceOf(Session::class, $session); // NOTE: this is an actual sessionId from the recorded response, this doesn't correspond to // the API Key and API Secret used to create the session. $this->assertEquals( @@ -619,10 +612,7 @@ public function testFailsWhenCreatingRelayedAutoArchivedSession(): void $this->setupOT(); // Act - $session = $this->opentok->createSession(array( - 'mediaMode' => MediaMode::RELAYED, - 'archiveMode' => ArchiveMode::ALWAYS - )); + $this->opentok->createSession(['mediaMode' => MediaMode::RELAYED, 'archiveMode' => ArchiveMode::ALWAYS]); // Assert } @@ -655,7 +645,7 @@ public function testGeneratesToken(): void //$this->assertNotEmpty($decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } public function testGeneratesTokenWithRole(): void @@ -669,7 +659,7 @@ public function testGeneratesTokenWithRole(): void $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); // Act - $token = $opentok->generateToken($sessionId, array('role' => Role::MODERATOR), true); + $token = $opentok->generateToken($sessionId, ['role' => Role::MODERATOR], true); // Assert $this->assertIsString($token); @@ -685,7 +675,7 @@ public function testGeneratesTokenWithRole(): void //$this->assertNotEmpty($decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } public function testGeneratesTokenWithExpireTime(): void @@ -701,7 +691,7 @@ public function testGeneratesTokenWithExpireTime(): void // Act // expires in one hour (60 seconds * 60 minutes) $inOneHour = time() + (60 * 60); - $token = $opentok->generateToken($sessionId, array('expireTime' => $inOneHour ), true); + $token = $opentok->generateToken($sessionId, ['expireTime' => $inOneHour], true); // Assert $this->assertIsString($token); @@ -716,7 +706,7 @@ public function testGeneratesTokenWithExpireTime(): void $this->assertEquals($inOneHour, $decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } public function testGeneratesTokenWithData(): void @@ -731,7 +721,7 @@ public function testGeneratesTokenWithData(): void // Act $userStatus = '{nick:"johnny",status:"hey there fellas!"}'; - $token = $opentok->generateToken($sessionId, array('data' => $userStatus), true); + $token = $opentok->generateToken($sessionId, ['data' => $userStatus], true); // Assert $this->assertIsString($token); @@ -747,7 +737,7 @@ public function testGeneratesTokenWithData(): void //$this->assertNotEmpty($decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } // TODO: write tests for passing invalid $expireTime and $data to generateToken @@ -763,12 +753,10 @@ public function testGeneratesTokenWithInitialLayoutClassList(): void $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); - $initialLayouClassList = array('focus', 'main'); + $initialLayouClassList = ['focus', 'main']; // Act - $token = $opentok->generateToken($sessionId, array( - 'initialLayoutClassList' => $initialLayouClassList - ), true); + $token = $opentok->generateToken($sessionId, ['initialLayoutClassList' => $initialLayouClassList], true); // Assert $this->assertIsString($token); @@ -780,20 +768,20 @@ public function testGeneratesTokenWithInitialLayoutClassList(): void $this->assertNotEmpty($decodedToken['create_time']); $this->assertArrayNotHasKey('connection_data', $decodedToken); $this->assertEquals('publisher', $decodedToken['role']); - $this->assertEquals(join(" ", $initialLayouClassList), $decodedToken['initial_layout_class_list']); + $this->assertEquals(implode(" ", $initialLayouClassList), $decodedToken['initial_layout_class_list']); // TODO: should all tokens have a default expire time even if it wasn't specified? //$this->assertNotEmpty($decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } public function testFailsWhenGeneratingTokenUsingInvalidRole(): void { $this->expectException('InvalidArgumentException'); $this->setupOT(); - $token = $this->opentok->generateToken('SESSIONID', array('role' => 'notarole'), true); + $this->opentok->generateToken('SESSIONID', ['role' => 'notarole'], true); } public function testWillCreateLegacyT1WhenRequested(): void @@ -926,7 +914,7 @@ public function testStartsArchive(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -938,7 +926,7 @@ public function testStartsArchive(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(0, $archive->duration); $this->assertEquals('', $archive->reason); $this->assertEquals('started', $archive->status); @@ -972,7 +960,7 @@ public function testCustomUserAgent(): void // decoding to check, so it's fine. $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; - $archive = $this->opentok->startArchive($sessionId); + $this->opentok->startArchive($sessionId); $this->assertCount(1, $this->historyContainer); @@ -999,12 +987,12 @@ public function testStartsArchiveInMultiTagMode(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(0, $archive->duration); $this->assertEquals('', $archive->reason); $this->assertEquals('started', $archive->status); @@ -1038,7 +1026,7 @@ public function testStartsArchiveInManualMode(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1050,7 +1038,7 @@ public function testStartsArchiveInManualMode(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(0, $archive->duration); $this->assertEquals('', $archive->reason); $this->assertEquals('started', $archive->status); @@ -1080,7 +1068,7 @@ public function testCannotStartArchiveWithInvalidStreamMode(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, ['streamMode' => 'broadcast']); + $this->opentok->startArchive($sessionId, ['streamMode' => 'broadcast']); } public function testStartsArchiveNamed(): void @@ -1099,13 +1087,13 @@ public function testStartsArchiveNamed(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, array( 'name' => 'showtime' )); + $archive = $this->opentok->startArchive($sessionId, ['name' => 'showtime']); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1117,11 +1105,11 @@ public function testStartsArchiveNamed(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals('showtime', $body->name); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); // TODO: test the properties of the actual archive object } @@ -1151,7 +1139,7 @@ public function testStartsArchiveNamedDeprecated(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1163,11 +1151,11 @@ public function testStartsArchiveNamedDeprecated(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals('showtime', $body->name); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); // TODO: test the properties of the actual archive object } @@ -1187,13 +1175,13 @@ public function testStartsArchiveAudioOnly(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, array( 'hasVideo' => false )); + $archive = $this->opentok->startArchive($sessionId, ['hasVideo' => false]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1205,12 +1193,12 @@ public function testStartsArchiveAudioOnly(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals(false, $body->hasVideo); $this->assertEquals(true, $body->hasAudio); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); // TODO: test the properties of the actual archive object } @@ -1230,15 +1218,13 @@ public function testStartsArchiveIndividualOutput(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, array( - 'outputMode' => OutputMode::INDIVIDUAL - )); + $archive = $this->opentok->startArchive($sessionId, ['outputMode' => OutputMode::INDIVIDUAL]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1250,11 +1236,11 @@ public function testStartsArchiveIndividualOutput(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals('individual', $body->outputMode); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(OutputMode::INDIVIDUAL, $archive->outputMode); } @@ -1274,15 +1260,13 @@ public function testStartsArchiveResolutionSD(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, array( - 'resolution' => '640x480' - )); + $archive = $this->opentok->startArchive($sessionId, ['resolution' => '640x480']); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1294,11 +1278,11 @@ public function testStartsArchiveResolutionSD(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals('640x480', $body->resolution); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); } public function testStartsArchiveResolutionHD(): void @@ -1317,15 +1301,13 @@ public function testStartsArchiveResolutionHD(): void $sessionId = '2_MX44NTQ1MTF-flR1ZSBOb3YgMTIgMDk6NDA6NTkgUFNUIDIwMTN-MC43NjU0Nzh-'; // Act - $archive = $this->opentok->startArchive($sessionId, array( - 'resolution' => '1280x720' - )); + $archive = $this->opentok->startArchive($sessionId, ['resolution' => '1280x720']); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1337,11 +1319,11 @@ public function testStartsArchiveResolutionHD(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($sessionId, $body->sessionId); $this->assertEquals('1280x720', $body->resolution); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); } public function testStopsArchive(): void @@ -1364,7 +1346,7 @@ public function testStopsArchive(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId . '/stop', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1376,7 +1358,7 @@ public function testStopsArchive(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); // TODO: test the properties of the actual archive object } @@ -1400,7 +1382,7 @@ public function testGetsArchive(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1410,7 +1392,7 @@ public function testGetsArchive(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); } public function testGetsArchiveWithMaxBitrate(): void @@ -1433,7 +1415,7 @@ public function testGetsArchiveWithMaxBitrate(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1441,7 +1423,7 @@ public function testGetsArchiveWithMaxBitrate(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(2000000, $archive->maxBitrate); } @@ -1461,7 +1443,7 @@ public function testDeletesArchive(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('DELETE', strtoupper($request->getMethod())); + $this->assertEquals('DELETE', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1495,7 +1477,7 @@ public function testListsArchives(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1503,7 +1485,7 @@ public function testListsArchives(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\ArchiveList', $archiveList); + $this->assertInstanceOf(ArchiveList::class, $archiveList); // TODO: test the properties of the actual archiveList object and its contained archive // objects } @@ -1526,14 +1508,14 @@ public function testListsArchivesWithOffsetAndCount(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\ArchiveList', $archiveList); + $this->assertInstanceOf(ArchiveList::class, $archiveList); $this->assertEquals(1, $archiveList->totalCount()); $this->assertEquals('832641bf-5dbf-41a1-ad94-fea213e59a92', $archiveList->getItems()[0]->id); } @@ -1552,7 +1534,7 @@ public function testListsArchivesWithSessionId(): void $sessionId = '1_MX4xMjM0NTY3OH4-VGh1IEZlYiAyNyAwNDozODozMSBQU1QgMjAxNH4wLjI0NDgyMjI'; $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); // Act $archiveList = $this->opentok->listArchives(0, null, $sessionId); @@ -1561,14 +1543,14 @@ public function testListsArchivesWithSessionId(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\ArchiveList', $archiveList); + $this->assertInstanceOf(ArchiveList::class, $archiveList); $this->assertEquals(2, $archiveList->totalCount()); $this->assertEquals($sessionId, $archiveList->getItems()[0]->sessionId); $this->assertEquals($sessionId, $archiveList->getItems()[1]->sessionId); @@ -1589,7 +1571,7 @@ public function testFailsWhenListingArchivesWithTooLargeCount(): void ]]); // Act - $archiveList = $this->opentok->listArchives(0, 1001); + $this->opentok->listArchives(0, 1001); // Assert $this->assertCount(0, $this->historyContainer); @@ -1613,7 +1595,7 @@ public function testGetsExpiredArchive(): void $archive = $this->opentok->getArchive($archiveId); // Assert - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals("expired", $archive->status); } @@ -1645,7 +1627,7 @@ public function testStartsArchiveWithTranscription(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1658,13 +1640,13 @@ public function testStartsArchiveWithTranscription(): void $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); // Test request body contains transcription fields - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(true, $body->hasTranscription); $this->assertEquals('en-US', $body->transcriptionProperties->primaryLanguageCode); $this->assertEquals(false, $body->transcriptionProperties->hasSummary); // Test response properties - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(true, $archive->hasTranscription); $this->assertIsArray($archive->transcription); $this->assertEquals('requested', $archive->transcription['status']); @@ -1700,13 +1682,13 @@ public function testStartsArchiveWithTranscriptionAndSummary(): void $request = $this->historyContainer[0]['request']; // Test request body contains transcription fields - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(true, $body->hasTranscription); $this->assertEquals('es-ES', $body->transcriptionProperties->primaryLanguageCode); $this->assertEquals(true, $body->transcriptionProperties->hasSummary); // Test response properties - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); $this->assertEquals(true, $archive->hasTranscription); $this->assertIsArray($archive->transcription); $this->assertEquals('requested', $archive->transcription['status']); @@ -1736,14 +1718,14 @@ public function testStartsArchiveWithoutTranscription(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - + // Test request body - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(false, $body->hasTranscription); $this->assertObjectNotHasAttribute('transcriptionProperties', $body); // Test response properties (archive without transcription) - $this->assertInstanceOf('OpenTok\Archive', $archive); + $this->assertInstanceOf(Archive::class, $archive); // The hasTranscription property should not be set in response if transcription is disabled } @@ -1836,7 +1818,7 @@ public function testForceDisconnect(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('DELETE', strtoupper($request->getMethod())); + $this->assertEquals('DELETE', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/connection/' . $connectionId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -1862,13 +1844,13 @@ public function testForceDisconnectConnectionException(): void $connectionId = '063e72a4-64b4-43c8-9da5-eca071daab89'; - $this->expectException('OpenTok\Exception\ForceDisconnectConnectionException'); + $this->expectException(ForceDisconnectConnectionException::class); // Act $this->opentok->forceDisconnect($sessionId, $connectionId); } - public function testCannotConnectAudioStreamWithInvalidSessionId() + public function testCannotConnectAudioStreamWithInvalidSessionId(): void { $this->setupOTWithMocks([[ 'code' => 200 @@ -1879,7 +1861,7 @@ public function testCannotConnectAudioStreamWithInvalidSessionId() $this->opentok->connectAudio('', '2398523', []); } - public function testCannotConnectAudioStreamWithoutWebsocketUri() + public function testCannotConnectAudioStreamWithoutWebsocketUri(): void { $this->expectException(InvalidArgumentException::class); $this->expectErrorMessage('Websocket configuration must have a uri'); @@ -1895,7 +1877,7 @@ public function testCannotConnectAudioStreamWithoutWebsocketUri() $this->opentok->connectAudio('9999', 'wrwetg', $badPayload); } - public function testCanConnectAudioStreamWithWebsocket() + public function testCanConnectAudioStreamWithWebsocket(): void { $this->setupOTWithMocks([[ 'code' => 200, @@ -1923,7 +1905,7 @@ public function testCanConnectAudioStreamWithWebsocket() $this->assertEquals('7aebb3a4-3d86-4962-b317-afb73e05439d', $response['connectionId']); } - public function testCanStartBroadcastWithRmtp() + public function testCanStartBroadcastWithRmtp(): void { $this->setupOTWithMocks([[ 'code' => 200, @@ -2018,7 +2000,7 @@ public function testCannotStartBroadcastWithOver5RtmpChannels(): void ] ]; - $broadcast = $this->opentok->startBroadcast($sessionId, $options); + $this->opentok->startBroadcast($sessionId, $options); } public function testCanStartBroadcastWithDefaultHlsOptions(): void @@ -2117,7 +2099,7 @@ public function testCannotStartBroadcastWithBothHlsAndDvrEnabled(): void ] ]; - $broadcast = $this->opentok->startBroadcast($sessionId, $options); + $this->opentok->startBroadcast($sessionId, $options); } public function testStartsBroadcast(): void @@ -2137,7 +2119,7 @@ public function testStartsBroadcast(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2148,7 +2130,7 @@ public function testStartsBroadcast(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); $this->assertIsString($broadcast->id); $this->assertEquals($sessionId, $broadcast->sessionId); $this->assertIsArray($broadcast->broadcastUrls); @@ -2202,7 +2184,7 @@ public function testStartsBroadcastWithMultiBroadcastTag(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2214,7 +2196,7 @@ public function testStartsBroadcastWithMultiBroadcastTag(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); $this->assertIsString($broadcast->id); $this->assertEquals($sessionId, $broadcast->sessionId); $this->assertIsArray($broadcast->broadcastUrls); @@ -2242,7 +2224,7 @@ public function testCannotStartBroadcastWithInvalidStreamMode(): void $sessionId = '2_MX44NTQ1MTF-fjE0NzI0MzU2MDUyMjN-eVgwNFJhZmR6MjdockFHanpxNzBXaEFXfn4'; // Act - $broadcast = $this->opentok->startBroadcast($sessionId, ['streamMode' => 'stop']); + $this->opentok->startBroadcast($sessionId, ['streamMode' => 'stop']); } public function testStartsBroadcastInManualStreamMode(): void @@ -2267,7 +2249,7 @@ public function testStartsBroadcastInManualStreamMode(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2279,7 +2261,7 @@ public function testStartsBroadcastInManualStreamMode(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); $this->assertIsString($broadcast->id); $this->assertEquals($sessionId, $broadcast->sessionId); $this->assertIsArray($broadcast->broadcastUrls); @@ -2319,7 +2301,7 @@ public function testStartBroadcastWithOptions(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2330,7 +2312,7 @@ public function testStartBroadcastWithOptions(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); $this->assertIsString($broadcast->id); $this->assertEquals($sessionId, $broadcast->sessionId); $this->assertEquals($maxDuration, $broadcast->maxDuration); @@ -2364,7 +2346,7 @@ public function testStopsBroadcast(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast/' . $broadcastId . '/stop', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2372,7 +2354,7 @@ public function testStopsBroadcast(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); $this->assertTrue($broadcast->isStopped); } @@ -2396,14 +2378,14 @@ public function testGetsBroadcast(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast/' . $broadcastId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Broadcast', $broadcast); + $this->assertInstanceOf(Broadcast::class, $broadcast); } public function testCanMuteStream(): void @@ -2476,7 +2458,7 @@ public function testThrowsExceptionWhenInvalidStreamIds(): void public function testCannotMuteStreamsWithWrongTypePayload(): void { - $this->expectException(\TypeError::class); + $this->expectException(TypeError::class); $this->setupOTWithMocks([[ 'code' => 200, @@ -2514,7 +2496,7 @@ public function testUpdatesBroadcastLayoutWithPredefined(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('PUT', strtoupper($request->getMethod())); + $this->assertEquals('PUT', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast/' . $broadcastId . '/layout', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2526,7 +2508,7 @@ public function testUpdatesBroadcastLayoutWithPredefined(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('pip', $body->type); } @@ -2543,9 +2525,7 @@ public function testUpdatesBroadcastLayoutWithCustom(): void $broadcastId = 'BROADCASTID'; $stylesheet = '.classname { height: 1px; width: 1px }'; - $layout = Layout::createCustom(array( - 'stylesheet' => $stylesheet - )); + $layout = Layout::createCustom(['stylesheet' => $stylesheet]); // Act $this->opentok->updateBroadcastLayout($broadcastId, $layout); @@ -2554,7 +2534,7 @@ public function testUpdatesBroadcastLayoutWithCustom(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('PUT', strtoupper($request->getMethod())); + $this->assertEquals('PUT', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/broadcast/' . $broadcastId . '/layout', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2566,7 +2546,7 @@ public function testUpdatesBroadcastLayoutWithCustom(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('custom', $body->type); $this->assertEquals($stylesheet, $body->stylesheet); } @@ -2584,18 +2564,16 @@ public function testUpdatesStreamLayoutClassList(): void $sessionId = 'SESSIONID'; $streamId = 'STREAMID'; - $layoutClassList = array('foo', 'bar'); + $layoutClassList = ['foo', 'bar']; // Act - $this->opentok->updateStream($sessionId, $streamId, array( - 'layoutClassList' => $layoutClassList - )); + $this->opentok->updateStream($sessionId, $streamId, ['layoutClassList' => $layoutClassList]); // Assert $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('PUT', strtoupper($request->getMethod())); + $this->assertEquals('PUT', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/stream/' . $streamId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2607,7 +2585,7 @@ public function testUpdatesStreamLayoutClassList(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($layoutClassList, $body->layoutClassList); } @@ -2631,7 +2609,7 @@ public function testGetStream(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/stream/' . $streamId, $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -2639,7 +2617,7 @@ public function testGetStream(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\Stream', $streamData); + $this->assertInstanceOf(Stream::class, $streamData); $this->assertNotNull($streamData->id); $this->assertNotNull($streamData->name); $this->assertNotNull($streamData->videoType); @@ -2662,13 +2640,13 @@ public function testSipCall(): void $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $bogusToken = 'T1==TEST'; $bogusSipUri = 'sip:john@doe.com'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); // Act $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri); // Assert - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2687,20 +2665,15 @@ public function testSipCallWithAuth(): void $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $bogusToken = 'T1==TEST'; $bogusSipUri = 'sip:john@doe.com'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); - $auth = array( - 'username' => 'john', - 'password' => 'doe' - ); + $auth = ['username' => 'john', 'password' => 'doe']; // Act - $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri, array( - 'auth' => $auth - )); + $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri, ['auth' => $auth]); // Assert - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2708,7 +2681,7 @@ public function testSipCallWithAuth(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($auth['username'], $body->sip->auth->username); $this->assertEquals($auth['password'], $body->sip->auth->password); } @@ -2725,14 +2698,14 @@ public function testFailedSipCall(): void $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $bogusToken = 'T1==TEST'; $bogusSipUri = 'sip:john@doe.com'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); $sipCall = null; // Act try { $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri); $this->assertNull($sipCall); - } catch (\Exception $e) { + } catch (Exception) { $this->assertNull($sipCall); } } @@ -2760,7 +2733,7 @@ public function testSipCallFrom(): void ]); // Assert - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2768,7 +2741,7 @@ public function testSipCallFrom(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($from, $body->sip->from); } @@ -2787,7 +2760,7 @@ public function testSipCallVideo(): void $bogusSipUri = 'sip:john@doe.com'; $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri, ['video' => true]); - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2795,7 +2768,7 @@ public function testSipCallVideo(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(true, $body->sip->video); } @@ -2820,7 +2793,7 @@ public function testSipCallStreams(): void $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri, $options); - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2828,7 +2801,7 @@ public function testSipCallStreams(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(true, $body->sip->video); $this->assertEquals('stream1', $body->sip->streams[0]); } @@ -2854,7 +2827,7 @@ public function testSipCallVideoWithObserveForceMute(): void $sipCall = $this->opentok->dial($sessionId, $bogusToken, $bogusSipUri, $optionsPayload); - $this->assertInstanceOf('OpenTok\SipCall', $sipCall); + $this->assertInstanceOf(SipCall::class, $sipCall); $this->assertNotNull($sipCall->id); $this->assertNotNull($sipCall->connectionId); $this->assertNotNull($sipCall->streamId); @@ -2862,7 +2835,7 @@ public function testSipCallVideoWithObserveForceMute(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals(true, $body->sip->video); } @@ -2884,7 +2857,7 @@ public function testPlayDTMF(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($digits, $body->digits); } @@ -2907,7 +2880,7 @@ public function testPlayDTMFIntoConnection(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals($digits, $body->digits); } @@ -2958,12 +2931,9 @@ public function testSignalData(): void $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); - $payload = array( - 'data' => 'apple', - 'type' => 'signal type sample' - ); + $payload = ['data' => 'apple', 'type' => 'signal type sample']; // Act $this->opentok->signal($sessionId, $payload); @@ -2972,14 +2942,14 @@ public function testSignalData(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/signal', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('apple', $body->data); $this->assertEquals('signal type sample', $body->type); } @@ -2995,12 +2965,9 @@ public function testSignalWithConnectionId(): void $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $connectionId = 'da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf'; - $payload = array( - 'type' => 'rest', - 'data' => 'random message' - ); + $payload = ['type' => 'rest', 'data' => 'random message']; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); // Act $this->opentok->signal($sessionId, $payload, $connectionId); @@ -3008,14 +2975,14 @@ public function testSignalWithConnectionId(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('POST', strtoupper($request->getMethod())); + $this->assertEquals('POST', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/connection/' . $connectionId . '/signal', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('random message', $body->data); $this->assertEquals('rest', $body->type); } @@ -3033,15 +3000,15 @@ public function testSignalWithEmptyPayload(): void $sessionId = '1_MX4xMjM0NTY3OH4-VGh1IEZlYiAyNyAwNDozODozMSBQU1QgMjAxNH4wLjI0NDgyMjI'; $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - $payload = array(); + $payload = []; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); // Act try { $this->opentok->signal($sessionId, $payload); $this->assertTrue(true); - } catch (\Exception $e) { + } catch (Exception) { } } @@ -3056,14 +3023,11 @@ public function testSignalConnectionException(): void $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $connectionId = 'da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf'; - $payload = array( - 'type' => 'rest', - 'data' => 'random message' - ); + $payload = ['type' => 'rest', 'data' => 'random message']; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); - $this->expectException('OpenTok\Exception\SignalConnectionException'); + $this->expectException(SignalConnectionException::class); // Act $this->opentok->signal($sessionId, $payload, $connectionId); } @@ -3079,14 +3043,11 @@ public function testSignalUnexpectedValueException(): void $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; $connectionId = 'da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf'; - $payload = array( - 'type' => 'rest', - 'data' => 'more than 128 bytes' - ); + $payload = ['type' => 'rest', 'data' => 'more than 128 bytes']; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); - $this->expectException('OpenTok\Exception\SignalUnexpectedValueException'); + $this->expectException(SignalUnexpectedValueException::class); // Act $this->opentok->signal($sessionId, $payload, $connectionId); @@ -3107,7 +3068,7 @@ public function testListStreams(): void $bogusApiKey = '12345678'; $bogusApiSecret = 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f'; - $opentok = new OpenTok($bogusApiKey, $bogusApiSecret); + new OpenTok($bogusApiKey, $bogusApiSecret); // Act $streamList = $this->opentok->listStreams($sessionId); @@ -3116,7 +3077,7 @@ public function testListStreams(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/stream/', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -3124,7 +3085,7 @@ public function testListStreams(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\StreamList', $streamList); + $this->assertInstanceOf(StreamList::class, $streamList); } public function testListConnections(): void @@ -3147,7 +3108,7 @@ public function testListConnections(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('GET', strtoupper($request->getMethod())); + $this->assertEquals('GET', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/session/' . $sessionId . '/connection/', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -3155,14 +3116,14 @@ public function testListConnections(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $this->assertInstanceOf('OpenTok\ConnectionList', $connectionList); + $this->assertInstanceOf(ConnectionList::class, $connectionList); $this->assertEquals(3, $connectionList->totalCount()); $this->assertEquals('e9f8c166-6c67-440d-994a-04fb6dfed007', $connectionList->getProjectId()); $this->assertEquals('b40ef09b-3811-4726-b508-e41a0f96c68f', $connectionList->getSessionId()); $connections = $connectionList->getItems(); $this->assertCount(3, $connections); - $this->assertInstanceOf('OpenTok\Connection', $connections[0]); + $this->assertInstanceOf(Connection::class, $connections[0]); $this->assertEquals('8b732909-0a06-46a2-8ea8-074e64d43422', $connections[0]->connectionId); $this->assertEquals('Connected', $connections[0]->connectionState); $this->assertEquals('1384221730000', $connections[0]->createdAt); @@ -3174,7 +3135,7 @@ public function testListConnectionsWithInvalidSessionId(): void $this->setupOT(); // Assert - $this->expectException('OpenTok\Exception\InvalidArgumentException'); + $this->expectException(InvalidArgumentException::class); // Act $this->opentok->listConnections('invalid-session-id'); @@ -3200,7 +3161,7 @@ public function testListConnectionsIteration(): void $iteratedConnections = []; foreach ($connectionList as $index => $connection) { $iteratedConnections[$index] = $connection; - $this->assertInstanceOf('OpenTok\Connection', $connection); + $this->assertInstanceOf(Connection::class, $connection); } $this->assertCount(3, $iteratedConnections); @@ -3239,7 +3200,7 @@ public function testsSetArchiveLayoutWithPredefined(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('PUT', strtoupper($request->getMethod())); + $this->assertEquals('PUT', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId . '/layout', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -3251,7 +3212,7 @@ public function testsSetArchiveLayoutWithPredefined(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('pip', $body->type); } @@ -3267,9 +3228,7 @@ public function testsSetArchiveLayoutWithCustom(): void $archiveId = 'ARCHIVEID'; $stylesheet = '.classname { height: 1px; width: 1px }'; - $options = array( - 'stylesheet' => $stylesheet - ); + $options = ['stylesheet' => $stylesheet]; $layout = Layout::createCustom($options); // Act @@ -3279,7 +3238,7 @@ public function testsSetArchiveLayoutWithCustom(): void $this->assertCount(1, $this->historyContainer); $request = $this->historyContainer[0]['request']; - $this->assertEquals('PUT', strtoupper($request->getMethod())); + $this->assertEquals('PUT', strtoupper((string) $request->getMethod())); $this->assertEquals('/v2/project/' . $this->API_KEY . '/archive/' . $archiveId . '/layout', $request->getUri()->getPath()); $this->assertEquals('api.opentok.com', $request->getUri()->getHost()); $this->assertEquals('https', $request->getUri()->getScheme()); @@ -3291,7 +3250,7 @@ public function testsSetArchiveLayoutWithCustom(): void $authString = $request->getHeaderLine('X-OPENTOK-AUTH'); $this->assertEquals(true, TestHelpers::validateOpenTokAuthHeader($this->API_KEY, $this->API_SECRET, $authString)); - $body = json_decode($request->getBody()); + $body = json_decode((string) $request->getBody()); $this->assertEquals('custom', $body->type); $this->assertEquals($stylesheet, $body->stylesheet); } @@ -3304,11 +3263,11 @@ public function testDefaultTimeoutDefaultsToNull(): void { $this->setupOT(); - $opentokReflection = new \ReflectionClass($this->opentok); + $opentokReflection = new ReflectionClass($this->opentok); $opentokClient = $opentokReflection->getProperty('client'); $opentokClient->setAccessible(true); $opentokClient = $opentokClient->getValue($this->opentok); - $opentokClientReflection = new \ReflectionClass($opentokClient); + $opentokClientReflection = new ReflectionClass($opentokClient); /** @var \GuzzleHttp\Client $guzzleClient */ $guzzleClient = $opentokClientReflection->getProperty('client'); @@ -3325,11 +3284,11 @@ public function testDefaultTimeoutCanBeOverriden(): void { $opentok = new OpenTok('4349501', 'b60d0b2568f3ea9731bd9d3f71be263ce19f802f', ['timeout' => 400]); - $opentokReflection = new \ReflectionClass($opentok); + $opentokReflection = new ReflectionClass($opentok); $opentokClient = $opentokReflection->getProperty('client'); $opentokClient->setAccessible(true); $opentokClient = $opentokClient->getValue($opentok); - $opentokClientReflection = new \ReflectionClass($opentokClient); + $opentokClientReflection = new ReflectionClass($opentokClient); /** @var \GuzzleHttp\Client $guzzleClient */ $guzzleClient = $opentokClientReflection->getProperty('client'); @@ -3387,7 +3346,7 @@ public function testCanStopCaptions(): void $this->assertTrue($result); } - public function testCanConnectAudioStreamWithBidirectionalWebsocketTrue() + public function testCanConnectAudioStreamWithBidirectionalWebsocketTrue(): void { $this->setupOTWithMocks([[ 'code' => 200, @@ -3416,7 +3375,7 @@ public function testCanConnectAudioStreamWithBidirectionalWebsocketTrue() $this->assertEquals('7aebb3a4-3d86-4962-b317-afb73e05439d', $response['connectionId']); } - public function testCanConnectAudioStreamWithBidirectionalWebsocketFalse() + public function testCanConnectAudioStreamWithBidirectionalWebsocketFalse(): void { $this->setupOTWithMocks([[ 'code' => 200, @@ -3445,7 +3404,7 @@ public function testCanConnectAudioStreamWithBidirectionalWebsocketFalse() $this->assertEquals('7aebb3a4-3d86-4962-b317-afb73e05439d', $response['connectionId']); } - public function testConnectAudioStreamWithInvalidBidirectionalThrows() + public function testConnectAudioStreamWithInvalidBidirectionalThrows(): void { $this->expectException(InvalidArgumentException::class); $this->expectErrorMessage('Websocket configuration bidirectional option must be a boolean'); diff --git a/tests/OpenTokTest/RenderTest.php b/tests/OpenTokTest/RenderTest.php index 8ba36c8d..f828dbe9 100644 --- a/tests/OpenTokTest/RenderTest.php +++ b/tests/OpenTokTest/RenderTest.php @@ -9,7 +9,7 @@ class RenderTest extends TestCase { public function testCannotHydrateWithWrongPayload(): void { - $this->expectError(\TypeError::class); + $this->expectError(); $payload = [ 'id' => '1248e7070b81464c9789f46ad10e7764', 'sessionId' => '2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4', @@ -22,7 +22,7 @@ public function testCannotHydrateWithWrongPayload(): void 'streamId' => 'e32445b743678c98230f238' ]; - $render = new Render($payload); + new Render($payload); } public function testCanHydrateFromPayload(): void diff --git a/tests/OpenTokTest/SessionTest.php b/tests/OpenTokTest/SessionTest.php index c98fa8d6..1742ecd2 100644 --- a/tests/OpenTokTest/SessionTest.php +++ b/tests/OpenTokTest/SessionTest.php @@ -28,7 +28,7 @@ public function setUp(): void $this->opentok = new OpenTok($this->API_KEY, $this->API_SECRET); } - public function testSessionWithId() + public function testSessionWithId(): void { $sessionId = 'SESSIONID'; $session = new Session($this->opentok, $sessionId); @@ -37,59 +37,59 @@ public function testSessionWithId() $this->assertEmpty($session->getLocation()); } - public function testSessionWithIdAndLocation() + public function testSessionWithIdAndLocation(): void { $sessionId = 'SESSIONID'; $location = '12.34.56.78'; - $session = new Session($this->opentok, $sessionId, array( 'location' => $location )); + $session = new Session($this->opentok, $sessionId, ['location' => $location]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals(MediaMode::ROUTED, $session->getMediaMode()); $this->assertEquals($location, $session->getLocation()); } - public function testSessionWithIdAndMediaMode() + public function testSessionWithIdAndMediaMode(): void { $sessionId = 'SESSIONID'; $mediaMode = MediaMode::RELAYED; - $session = new Session($this->opentok, $sessionId, array( 'mediaMode' => $mediaMode )); + $session = new Session($this->opentok, $sessionId, ['mediaMode' => $mediaMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($mediaMode, $session->getMediaMode()); $this->assertEmpty($session->getLocation()); $mediaMode = MediaMode::ROUTED; - $session = new Session($this->opentok, $sessionId, array( 'mediaMode' => $mediaMode )); + $session = new Session($this->opentok, $sessionId, ['mediaMode' => $mediaMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($mediaMode, $session->getMediaMode()); $this->assertEmpty($session->getLocation()); } - public function testSessionWithIdAndLocationAndMediaMode() + public function testSessionWithIdAndLocationAndMediaMode(): void { $sessionId = 'SESSIONID'; $location = '12.34.56.78'; $mediaMode = MediaMode::RELAYED; - $session = new Session($this->opentok, $sessionId, array( 'location' => $location, 'mediaMode' => $mediaMode )); + $session = new Session($this->opentok, $sessionId, ['location' => $location, 'mediaMode' => $mediaMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($mediaMode, $session->getMediaMode()); $this->assertEquals($location, $session->getLocation()); $mediaMode = MediaMode::ROUTED; - $session = new Session($this->opentok, $sessionId, array( 'location' => $location, 'mediaMode' => $mediaMode )); + $session = new Session($this->opentok, $sessionId, ['location' => $location, 'mediaMode' => $mediaMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($mediaMode, $session->getMediaMode()); $this->assertEquals($location, $session->getLocation()); } - public function testSessionWithArchiveMode() + public function testSessionWithArchiveMode(): void { $sessionId = 'SESSIONID'; $archiveMode = ArchiveMode::ALWAYS; - $session = new Session($this->opentok, $sessionId, array( 'archiveMode' => $archiveMode )); + $session = new Session($this->opentok, $sessionId, ['archiveMode' => $archiveMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($archiveMode, $session->getArchiveMode()); $archiveMode = ArchiveMode::MANUAL; - $session = new Session($this->opentok, $sessionId, array( 'archiveMode' => $archiveMode )); + $session = new Session($this->opentok, $sessionId, ['archiveMode' => $archiveMode]); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEquals($archiveMode, $session->getArchiveMode()); } @@ -97,58 +97,52 @@ public function testSessionWithArchiveMode() /** * @dataProvider badParameterProvider */ - public function testInitializationWithBadParams($sessionId, $props) + public function testInitializationWithBadParams(string|array $sessionId, array $props): void { $this->expectException('InvalidArgumentException'); - if (!$props || empty($props)) { + if (!$props || $props === []) { $session = new Session($this->opentok, $sessionId); } else { $session = new Session($this->opentok, $sessionId, $props); } } - public function badParameterProvider() + public function badParameterProvider(): array { - return array( - array(array(), array()), - array('SESSIONID', array( 'location' => 'NOTALOCATION') ), - array('SESSIONID', array( 'mediaMode' => 'NOTAMODE' ) ), - array('SESSIONID', array( 'location' => '127.0.0.1', 'mediaMode' => 'NOTAMODE' ) ), - array('SESSIONID', array( 'location' => 'NOTALOCATION', 'mediaMode' => MediaMode::RELAYED ) ) - ); + return [[[], []], ['SESSIONID', ['location' => 'NOTALOCATION']], ['SESSIONID', ['mediaMode' => 'NOTAMODE']], ['SESSIONID', ['location' => '127.0.0.1', 'mediaMode' => 'NOTAMODE']], ['SESSIONID', ['location' => 'NOTALOCATION', 'mediaMode' => MediaMode::RELAYED]]]; } - public function testInitialzationWithoutE2ee() + public function testInitialzationWithoutE2ee(): void { $sessionId = 'SESSIONID'; $session = new Session($this->opentok, $sessionId); $this->assertEquals(false, $session->getE2EE()); } - public function testInitialzationWithE2ee() + public function testInitialzationWithE2ee(): void { $sessionId = 'SESSIONID'; $session = new Session($this->opentok, $sessionId, ['e2ee' => true]); $this->assertEquals(true, $session->getE2EE()); } - public function testInitializationWithExtraneousParams() + public function testInitializationWithExtraneousParams(): void { $sessionId = 'SESSIONID'; - $session = new Session($this->opentok, $sessionId, array( 'notrealproperty' => 'notrealvalue' )); + $session = new Session($this->opentok, $sessionId, ['notrealproperty' => 'notrealvalue']); $this->assertEquals($sessionId, $session->getSessionId()); $this->assertEmpty($session->getLocation()); $this->assertEquals(MediaMode::ROUTED, $session->getMediaMode()); } - public function testCastingToString() + public function testCastingToString(): void { $sessionId = 'SESSIONID'; $session = new Session($this->opentok, $sessionId); $this->assertEquals($sessionId, (string)$session); } - public function testGeneratesToken() + public function testGeneratesToken(): void { $sessionId = '1_MX4xMjM0NTY3OH4-VGh1IEZlYiAyNyAwNDozODozMSBQU1QgMjAxNH4wLjI0NDgyMjI'; $bogusApiKey = '12345678'; @@ -171,6 +165,6 @@ public function testGeneratesToken() //$this->assertNotEmpty($decodedToken['expire_time']); $this->assertNotEmpty($decodedToken['sig']); - $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); + $this->assertEquals(hash_hmac('sha1', (string) $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']); } } \ No newline at end of file diff --git a/tests/OpenTokTest/TestHelpers.php b/tests/OpenTokTest/TestHelpers.php index d599dbcc..3fbbde99 100644 --- a/tests/OpenTokTest/TestHelpers.php +++ b/tests/OpenTokTest/TestHelpers.php @@ -2,6 +2,7 @@ namespace OpenTokTest; +use Exception; use Firebase\JWT\Key; use GuzzleHttp\Psr7\Response; use \Firebase\JWT\JWT; @@ -9,11 +10,14 @@ class TestHelpers { // TODO: untested, unused - public static function decodeSessionId($sessionId) + /** + * @return mixed[] + */ + public static function decodeSessionId($sessionId): array { - $trimmedSessionId = substr($sessionId, 2); + $trimmedSessionId = substr((string) $sessionId, 2); $parts = explode('-', $trimmedSessionId); - $data = array(); + $data = []; foreach ($parts as $part) { $decodedPart = base64_decode($part); $dataItems = explode('~', $decodedPart); @@ -22,16 +26,14 @@ public static function decodeSessionId($sessionId) return $data; } - public static function decodeToken($token) + public static function decodeToken($token): array { - $trimmedToken = substr($token, 4); // removes T1== + $trimmedToken = substr((string) $token, 4); // removes T1== $decodedToken = base64_decode($trimmedToken); $parts = explode(':', $decodedToken); // splits into partner info and data string parse_str($parts[0], $parsedPartnerInfo); parse_str($parts[1], $parsedDataString); - return array_merge($parsedPartnerInfo, $parsedDataString, array( - 'dataString' => $parts[1] - )); + return array_merge($parsedPartnerInfo, $parsedDataString, ['dataString' => $parts[1]]); } public static function validateOpenTokAuthHeader($apiKey, $apiSecret, $token) @@ -42,7 +44,7 @@ public static function validateOpenTokAuthHeader($apiKey, $apiSecret, $token) try { $decodedToken = JWT::decode($token, new Key($apiSecret, 'HS256')); - } catch (\Exception $e) { + } catch (Exception) { return false; } @@ -57,19 +59,14 @@ public static function validateOpenTokAuthHeader($apiKey, $apiSecret, $token) if (!property_exists($decodedToken, 'exp') || time() >= $decodedToken->exp) { return false; } - - if (!property_exists($decodedToken, 'jti')) { - return false; - } - - return true; + return property_exists($decodedToken, 'jti'); } - public static function mocksToResponses($mocks, $basePath) + public static function mocksToResponses($mocks, $basePath): array { - return array_map(function ($mock) use ($basePath) { - $code = !empty($mock['code']) ? $mock['code'] : 200; - $headers = !empty($mock['headers']) ? $mock['headers'] : []; + return array_map(function ($mock) use ($basePath): Response { + $code = empty($mock['code']) ? 200 : $mock['code']; + $headers = empty($mock['headers']) ? [] : $mock['headers']; $body = null; if (!empty($mock['body'])) { $body = $mock['body']; diff --git a/tests/OpenTokTest/Util/ClientTest.php b/tests/OpenTokTest/Util/ClientTest.php index fb1e4120..08037565 100644 --- a/tests/OpenTokTest/Util/ClientTest.php +++ b/tests/OpenTokTest/Util/ClientTest.php @@ -14,7 +14,7 @@ class ClientTest extends TestCase { - public function testCanAddAudioStreamToWebsocket() + public function testCanAddAudioStreamToWebsocket(): void { $mock = new MockHandler([ $this->getResponse('connect') @@ -34,7 +34,7 @@ public function testCanAddAudioStreamToWebsocket() $this->assertEquals('7aebb3a4-3d86-4962-b317-afb73e05439d', $response['connectionId']); } - public function testHandlesSignalErrorHandles400Response() + public function testHandlesSignalErrorHandles400Response(): void { $this->expectException(SignalUnexpectedValueException::class); @@ -49,7 +49,7 @@ public function testHandlesSignalErrorHandles400Response() $client->signal('sessionabcd', ['type' => 'foo', 'data' => 'bar'], 'connection1234'); } - public function testHandlesSignalErrorHandles403Response() + public function testHandlesSignalErrorHandles403Response(): void { $this->expectException(SignalAuthenticationException::class); @@ -64,7 +64,7 @@ public function testHandlesSignalErrorHandles403Response() $client->signal('sessionabcd', ['type' => 'foo', 'data' => 'bar'], 'connection1234'); } - public function testHandlesSignalErrorHandles404Response() + public function testHandlesSignalErrorHandles404Response(): void { $this->expectException(SignalConnectionException::class); $this->expectExceptionMessage('The client specified by the connectionId property is not connected to the session.'); @@ -80,7 +80,7 @@ public function testHandlesSignalErrorHandles404Response() $client->signal('sessionabcd', ['type' => 'foo', 'data' => 'bar'], 'connection1234'); } - public function testHandlesSignalErrorHandles413Response() + public function testHandlesSignalErrorHandles413Response(): void { $this->expectException(SignalUnexpectedValueException::class); $this->expectExceptionMessage('The type string exceeds the maximum length (128 bytes), or the data string exceeds the maximum size (8 kB).'); diff --git a/tests/OpenTokTest/Validators/ValidatorsTest.php b/tests/OpenTokTest/Validators/ValidatorsTest.php index 488bc572..7cd93f14 100644 --- a/tests/OpenTokTest/Validators/ValidatorsTest.php +++ b/tests/OpenTokTest/Validators/ValidatorsTest.php @@ -2,6 +2,7 @@ namespace OpenTokTest\Validators; +use stdClass; use OpenTok\Exception\InvalidArgumentException; use OpenTok\Util\Client; use OpenTok\Util\Validators; @@ -163,7 +164,7 @@ public function testWillThrowExceptionOnInvalidWebsocketConfiguration(): void /** * @dataProvider resolutionProvider */ - public function testValidResolutions($resolution, $isValid): void + public function testValidResolutions(string $resolution, bool $isValid): void { if ( ! $isValid) { $this->expectException(InvalidArgumentException::class); @@ -234,7 +235,7 @@ public function testValidateClient(): void public function testExceptionOnInvalidClient(): void { $this->expectException(\InvalidArgumentException::class); - $client = new \stdClass(); + $client = new stdClass(); Validators::validateClient($client); } @@ -270,7 +271,7 @@ public function testValidateSignalPayload(): void /** * @dataProvider connectionIdProvider */ - public function testConnectionId($input, $expectException): void + public function testConnectionId(string|array $input, bool $expectException): void { if ($expectException) { $this->expectException(\InvalidArgumentException::class); From 7eb0b3f5911b56bdc9220c818ac1c6dbd8390560 Mon Sep 17 00:00:00 2001 From: Chris Tankersley Date: Fri, 10 Oct 2025 15:33:07 -0400 Subject: [PATCH 2/2] Update src/OpenTok/Util/Validators.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/OpenTok/Util/Validators.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/OpenTok/Util/Validators.php b/src/OpenTok/Util/Validators.php index 1819ac4f..a863cf49 100755 --- a/src/OpenTok/Util/Validators.php +++ b/src/OpenTok/Util/Validators.php @@ -78,7 +78,7 @@ public static function validateForceMuteAllOptions(array $options): void if (!isset($options[$optionName])) { continue; } - if (getType($options[$optionName]) === $optionType) { + if (gettype($options[$optionName]) === $optionType) { continue; } throw new InvalidArgumentException('Invalid type given in options for: ' . $options[$optionName]);