Require use of PHP 7 features in coding standard

parent 7c723324
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.4 || ^8.3", "phpunit/phpunit": "^6.4 || ^8.3",
"sebastian/comparator": "^2.0 || ^3.0", "sebastian/comparator": "^2.0 || ^3.0",
"squizlabs/php_codesniffer": "^3.4", "squizlabs/php_codesniffer": "^3.5",
"symfony/phpunit-bridge": "^4.4@dev" "symfony/phpunit-bridge": "^4.4@dev"
}, },
"autoload": { "autoload": {
......
...@@ -17,16 +17,14 @@ ...@@ -17,16 +17,14 @@
<rule ref="Doctrine"> <rule ref="Doctrine">
<!-- Exclude sniffs that require newer PHP versions --> <!-- Exclude sniffs that require newer PHP versions -->
<!-- Available with PHP 7.0 -->
<exclude name="SlevomatCodingStandard.TypeHints.DeclareStrictTypes" />
<exclude name="SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly" />
<exclude name="SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" />
<!-- Available with PHP 7.1 --> <!-- Available with PHP 7.1 -->
<exclude name="SlevomatCodingStandard.Classes.ClassConstantVisibility" /> <exclude name="SlevomatCodingStandard.Classes.ClassConstantVisibility" />
<exclude name="SlevomatCodingStandard.PHP.ShortList.LongListUsed" /> <exclude name="SlevomatCodingStandard.PHP.ShortList.LongListUsed" />
<exclude name="SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue" /> <exclude name="SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue" />
<!-- Can cause subtle BC breaks, disabled for now -->
<exclude name="SlevomatCodingStandard.TypeHints.DeclareStrictTypes" />
<!-- No statement alignment so far --> <!-- No statement alignment so far -->
<exclude name="Generic.Formatting.MultipleStatementAlignment" /> <exclude name="Generic.Formatting.MultipleStatementAlignment" />
......
...@@ -109,7 +109,7 @@ class Client ...@@ -109,7 +109,7 @@ class Client
} }
$this->uri = (string) $uri; $this->uri = (string) $uri;
$this->typeMap = isset($driverOptions['typeMap']) ? $driverOptions['typeMap'] : null; $this->typeMap = $driverOptions['typeMap'] ?? null;
unset($driverOptions['typeMap']); unset($driverOptions['typeMap']);
......
...@@ -162,10 +162,10 @@ class Collection ...@@ -162,10 +162,10 @@ class Collection
$this->manager = $manager; $this->manager = $manager;
$this->databaseName = (string) $databaseName; $this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName; $this->collectionName = (string) $collectionName;
$this->readConcern = isset($options['readConcern']) ? $options['readConcern'] : $this->manager->getReadConcern(); $this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = isset($options['readPreference']) ? $options['readPreference'] : $this->manager->getReadPreference(); $this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = isset($options['typeMap']) ? $options['typeMap'] : self::$defaultTypeMap; $this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = isset($options['writeConcern']) ? $options['writeConcern'] : $this->manager->getWriteConcern(); $this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
} }
/** /**
......
...@@ -129,10 +129,10 @@ class Database ...@@ -129,10 +129,10 @@ class Database
$this->manager = $manager; $this->manager = $manager;
$this->databaseName = (string) $databaseName; $this->databaseName = (string) $databaseName;
$this->readConcern = isset($options['readConcern']) ? $options['readConcern'] : $this->manager->getReadConcern(); $this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = isset($options['readPreference']) ? $options['readPreference'] : $this->manager->getReadPreference(); $this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = isset($options['typeMap']) ? $options['typeMap'] : self::$defaultTypeMap; $this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = isset($options['writeConcern']) ? $options['writeConcern'] : $this->manager->getWriteConcern(); $this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
} }
/** /**
......
...@@ -180,10 +180,10 @@ class Bucket ...@@ -180,10 +180,10 @@ class Bucket
$this->bucketName = $options['bucketName']; $this->bucketName = $options['bucketName'];
$this->chunkSizeBytes = $options['chunkSizeBytes']; $this->chunkSizeBytes = $options['chunkSizeBytes'];
$this->disableMD5 = $options['disableMD5']; $this->disableMD5 = $options['disableMD5'];
$this->readConcern = isset($options['readConcern']) ? $options['readConcern'] : $this->manager->getReadConcern(); $this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = isset($options['readPreference']) ? $options['readPreference'] : $this->manager->getReadPreference(); $this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = isset($options['typeMap']) ? $options['typeMap'] : self::$defaultTypeMap; $this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = isset($options['writeConcern']) ? $options['writeConcern'] : $this->manager->getWriteConcern(); $this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
$collectionOptions = array_intersect_key($options, ['readConcern' => 1, 'readPreference' => 1, 'typeMap' => 1, 'writeConcern' => 1]); $collectionOptions = array_intersect_key($options, ['readConcern' => 1, 'readPreference' => 1, 'typeMap' => 1, 'writeConcern' => 1]);
...@@ -688,7 +688,7 @@ class Bucket ...@@ -688,7 +688,7 @@ class Bucket
$metadata = stream_get_meta_data($stream); $metadata = stream_get_meta_data($stream);
if (! isset($metadata['wrapper_data']) || ! $metadata['wrapper_data'] instanceof StreamWrapper) { if (! isset($metadata['wrapper_data']) || ! $metadata['wrapper_data'] instanceof StreamWrapper) {
throw InvalidArgumentException::invalidType('$stream wrapper data', isset($metadata['wrapper_data']) ? $metadata['wrapper_data'] : null, StreamWrapper::class); throw InvalidArgumentException::invalidType('$stream wrapper data', $metadata['wrapper_data'] ?? null, StreamWrapper::class);
} }
return $metadata['wrapper_data']->getFile(); return $metadata['wrapper_data']->getFile();
......
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
namespace MongoDB\GridFS; namespace MongoDB\GridFS;
use Exception;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
use stdClass; use stdClass;
use Throwable;
use function explode; use function explode;
use function get_class; use function get_class;
use function in_array; use function in_array;
...@@ -150,7 +150,7 @@ class StreamWrapper ...@@ -150,7 +150,7 @@ class StreamWrapper
try { try {
return $this->stream->readBytes($length); return $this->stream->readBytes($length);
} catch (Exception $e) { } catch (Throwable $e) {
trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING); trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING);
return false; return false;
...@@ -247,7 +247,7 @@ class StreamWrapper ...@@ -247,7 +247,7 @@ class StreamWrapper
try { try {
return $this->stream->writeBytes($data); return $this->stream->writeBytes($data);
} catch (Exception $e) { } catch (Throwable $e) {
trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING); trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING);
return false; return false;
......
...@@ -230,8 +230,8 @@ class ChangeStreamIterator extends IteratorIterator implements CommandSubscriber ...@@ -230,8 +230,8 @@ class ChangeStreamIterator extends IteratorIterator implements CommandSubscriber
} }
$resumeToken = is_array($document) $resumeToken = is_array($document)
? (isset($document['_id']) ? $document['_id'] : null) ? ($document['_id'] ?? null)
: (isset($document->_id) ? $document->_id : null); : ($document->_id ?? null);
if (! isset($resumeToken)) { if (! isset($resumeToken)) {
$this->isValid = false; $this->isValid = false;
......
...@@ -325,7 +325,7 @@ class Aggregate implements Executable ...@@ -325,7 +325,7 @@ class Aggregate implements Executable
private function createCommand(Server $server, $hasWriteStage) private function createCommand(Server $server, $hasWriteStage)
{ {
$cmd = [ $cmd = [
'aggregate' => isset($this->collectionName) ? $this->collectionName : 1, 'aggregate' => $this->collectionName ?? 1,
'pipeline' => $this->pipeline, 'pipeline' => $this->pipeline,
]; ];
$cmdOptions = []; $cmdOptions = [];
......
...@@ -243,7 +243,7 @@ class FindAndModify implements Executable, Explainable ...@@ -243,7 +243,7 @@ class FindAndModify implements Executable, Explainable
$result = current($cursor->toArray()); $result = current($cursor->toArray());
return isset($result->value) ? $result->value : null; return $result->value ?? null;
} }
public function getCommandDocument(Server $server) public function getCommandDocument(Server $server)
......
...@@ -5,6 +5,7 @@ namespace MongoDB\Operation; ...@@ -5,6 +5,7 @@ namespace MongoDB\Operation;
use Exception; use Exception;
use MongoDB\Driver\Exception\RuntimeException; use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Session; use MongoDB\Driver\Session;
use Throwable;
use function call_user_func; use function call_user_func;
use function time; use function time;
...@@ -63,7 +64,7 @@ class WithTransaction ...@@ -63,7 +64,7 @@ class WithTransaction
try { try {
call_user_func($this->callback, $session); call_user_func($this->callback, $session);
} catch (Exception $e) { } catch (Throwable $e) {
if ($session->isInTransaction()) { if ($session->isInTransaction()) {
$session->abortTransaction(); $session->abortTransaction();
} }
......
...@@ -57,7 +57,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -57,7 +57,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
$this->checkServerVersion($minServerVersion, $maxServerVersion); $this->checkServerVersion($minServerVersion, $maxServerVersion);
} }
$expectedData = isset($test['outcome']['collection']['data']) ? $test['outcome']['collection']['data'] : null; $expectedData = $test['outcome']['collection']['data'] ?? null;
$this->initializeData($initialData, $expectedData); $this->initializeData($initialData, $expectedData);
if (isset($test['outcome']['collection']['name'])) { if (isset($test['outcome']['collection']['name'])) {
...@@ -84,8 +84,8 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -84,8 +84,8 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/spec-tests/*/*.json') as $filename) { foreach (glob(__DIR__ . '/spec-tests/*/*.json') as $filename) {
$json = json_decode(file_get_contents($filename), true); $json = json_decode(file_get_contents($filename), true);
$minServerVersion = isset($json['minServerVersion']) ? $json['minServerVersion'] : null; $minServerVersion = $json['minServerVersion'] ?? null;
$maxServerVersion = isset($json['maxServerVersion']) ? $json['maxServerVersion'] : null; $maxServerVersion = $json['maxServerVersion'] ?? null;
foreach ($json['tests'] as $test) { foreach ($json['tests'] as $test) {
$name = str_replace(' ', '_', $test['description']); $name = str_replace(' ', '_', $test['description']);
...@@ -152,13 +152,13 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -152,13 +152,13 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
case 'bulkWrite': case 'bulkWrite':
return $this->collection->bulkWrite( return $this->collection->bulkWrite(
array_map([$this, 'prepareBulkWriteRequest'], $operation['arguments']['requests']), array_map([$this, 'prepareBulkWriteRequest'], $operation['arguments']['requests']),
isset($operation['arguments']['options']) ? $operation['arguments']['options'] : [] $operation['arguments']['options'] ?? []
); );
case 'count': case 'count':
case 'countDocuments': case 'countDocuments':
case 'find': case 'find':
return $this->collection->{$operation['name']}( return $this->collection->{$operation['name']}(
isset($operation['arguments']['filter']) ? $operation['arguments']['filter'] : [], $operation['arguments']['filter'] ?? [],
array_diff_key($operation['arguments'], ['filter' => 1]) array_diff_key($operation['arguments'], ['filter' => 1])
); );
case 'estimatedDocumentCount': case 'estimatedDocumentCount':
...@@ -173,7 +173,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -173,7 +173,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
case 'distinct': case 'distinct':
return $this->collection->distinct( return $this->collection->distinct(
$operation['arguments']['fieldName'], $operation['arguments']['fieldName'],
isset($operation['arguments']['filter']) ? $operation['arguments']['filter'] : [], $operation['arguments']['filter'] ?? [],
array_diff_key($operation['arguments'], ['fieldName' => 1, 'filter' => 1]) array_diff_key($operation['arguments'], ['fieldName' => 1, 'filter' => 1])
); );
case 'findOneAndReplace': case 'findOneAndReplace':
...@@ -200,7 +200,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -200,7 +200,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
case 'insertMany': case 'insertMany':
return $this->collection->insertMany( return $this->collection->insertMany(
$operation['arguments']['documents'], $operation['arguments']['documents'],
isset($operation['arguments']['options']) ? $operation['arguments']['options'] : [] $operation['arguments']['options'] ?? []
); );
case 'insertOne': case 'insertOne':
return $this->collection->insertOne( return $this->collection->insertOne(
...@@ -263,7 +263,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -263,7 +263,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
{ {
switch ($operation['name']) { switch ($operation['name']) {
case 'bulkWrite': case 'bulkWrite':
$insertedIds = isset($outcome['result']['insertedIds']) ? $outcome['result']['insertedIds'] : []; $insertedIds = $outcome['result']['insertedIds'] ?? [];
if ($exception instanceof BulkWriteException) { if ($exception instanceof BulkWriteException) {
return new BulkWriteResult($exception->getWriteResult(), $insertedIds); return new BulkWriteResult($exception->getWriteResult(), $insertedIds);
...@@ -271,7 +271,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase ...@@ -271,7 +271,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase
break; break;
case 'insertMany': case 'insertMany':
$insertedIds = isset($outcome['result']['insertedIds']) ? $outcome['result']['insertedIds'] : []; $insertedIds = $outcome['result']['insertedIds'] ?? [];
if ($exception instanceof BulkWriteException) { if ($exception instanceof BulkWriteException) {
return new InsertManyResult($exception->getWriteResult(), $insertedIds); return new InsertManyResult($exception->getWriteResult(), $insertedIds);
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
namespace MongoDB\Tests; namespace MongoDB\Tests;
use Exception;
use MongoDB\Driver\Monitoring\CommandFailedEvent; use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent; use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSubscriber; use MongoDB\Driver\Monitoring\CommandSubscriber;
use MongoDB\Driver\Monitoring\CommandSucceededEvent; use MongoDB\Driver\Monitoring\CommandSucceededEvent;
use Throwable;
use function call_user_func; use function call_user_func;
use function MongoDB\Driver\Monitoring\addSubscriber; use function MongoDB\Driver\Monitoring\addSubscriber;
use function MongoDB\Driver\Monitoring\removeSubscriber; use function MongoDB\Driver\Monitoring\removeSubscriber;
...@@ -27,7 +27,7 @@ class CommandObserver implements CommandSubscriber ...@@ -27,7 +27,7 @@ class CommandObserver implements CommandSubscriber
try { try {
call_user_func($execution); call_user_func($execution);
} catch (Exception $executionException) { } catch (Throwable $executionException) {
} }
removeSubscriber($this); removeSubscriber($this);
......
...@@ -136,7 +136,7 @@ class ReadableStreamFunctionalTest extends FunctionalTestCase ...@@ -136,7 +136,7 @@ class ReadableStreamFunctionalTest extends FunctionalTestCase
$fileDocument = $this->collectionWrapper->findFileById($fileId); $fileDocument = $this->collectionWrapper->findFileById($fileId);
$stream = new ReadableStream($this->collectionWrapper, $fileDocument); $stream = new ReadableStream($this->collectionWrapper, $fileDocument);
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$expectedByte = isset($expectedBytes[$i]) ? $expectedBytes[$i] : ''; $expectedByte = $expectedBytes[$i] ?? '';
$this->assertSame($expectedByte, $stream->readBytes(1)); $this->assertSame($expectedByte, $stream->readBytes(1));
} }
} }
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
namespace MongoDB\Tests\GridFS; namespace MongoDB\Tests\GridFS;
use DateTime; use DateTime;
use Exception;
use IteratorIterator; use IteratorIterator;
use LogicException; use LogicException;
use MongoDB\BSON\Binary; use MongoDB\BSON\Binary;
...@@ -15,6 +14,7 @@ use MongoDB\Operation\BulkWrite; ...@@ -15,6 +14,7 @@ use MongoDB\Operation\BulkWrite;
use MultipleIterator; use MultipleIterator;
use PHPUnit\Framework\Error\Warning; use PHPUnit\Framework\Error\Warning;
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait; use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
use Throwable;
use function array_walk; use function array_walk;
use function array_walk_recursive; use function array_walk_recursive;
use function file_get_contents; use function file_get_contents;
...@@ -70,7 +70,7 @@ class SpecFunctionalTest extends FunctionalTestCase ...@@ -70,7 +70,7 @@ class SpecFunctionalTest extends FunctionalTestCase
try { try {
$result = $this->executeAct($test['act']); $result = $this->executeAct($test['act']);
} catch (Exception $e) { } catch (Throwable $e) {
$result = $e; $result = $e;
} }
...@@ -211,13 +211,13 @@ class SpecFunctionalTest extends FunctionalTestCase ...@@ -211,13 +211,13 @@ class SpecFunctionalTest extends FunctionalTestCase
case 'download_by_name': case 'download_by_name':
return stream_get_contents($this->bucket->openDownloadStreamByName( return stream_get_contents($this->bucket->openDownloadStreamByName(
$act['arguments']['filename'], $act['arguments']['filename'],
isset($act['arguments']['options']) ? $act['arguments']['options'] : [] $act['arguments']['options'] ?? []
)); ));
case 'upload': case 'upload':
return $this->bucket->uploadFromStream( return $this->bucket->uploadFromStream(
$act['arguments']['filename'], $act['arguments']['filename'],
$this->createStream($act['arguments']['source']), $this->createStream($act['arguments']['source']),
isset($act['arguments']['options']) ? $act['arguments']['options'] : [] $act['arguments']['options'] ?? []
); );
default: default:
throw new LogicException('Unsupported act: ' . $act['operation']); throw new LogicException('Unsupported act: ' . $act['operation']);
......
...@@ -5,6 +5,7 @@ namespace MongoDB\Tests\Model; ...@@ -5,6 +5,7 @@ namespace MongoDB\Tests\Model;
use Exception; use Exception;
use MongoDB\Model\CachingIterator; use MongoDB\Model\CachingIterator;
use MongoDB\Tests\TestCase; use MongoDB\Tests\TestCase;
use Throwable;
use function iterator_to_array; use function iterator_to_array;
class CachingIteratorTest extends TestCase class CachingIteratorTest extends TestCase
...@@ -14,7 +15,7 @@ class CachingIteratorTest extends TestCase ...@@ -14,7 +15,7 @@ class CachingIteratorTest extends TestCase
$iterator = $this->getTraversable([1, 2, 3]); $iterator = $this->getTraversable([1, 2, 3]);
$this->assertSame([1, 2, 3], iterator_to_array($iterator)); $this->assertSame([1, 2, 3], iterator_to_array($iterator));
$this->expectException(Exception::class); $this->expectException(Throwable::class);
$this->expectExceptionMessage('Cannot traverse an already closed generator'); $this->expectExceptionMessage('Cannot traverse an already closed generator');
iterator_to_array($iterator); iterator_to_array($iterator);
} }
......
...@@ -149,10 +149,10 @@ class ChangeStreamsSpecTest extends FunctionalTestCase ...@@ -149,10 +149,10 @@ class ChangeStreamsSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/change-streams/*.json') as $filename) { foreach (glob(__DIR__ . '/change-streams/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename($filename, '.json'); $group = basename($filename, '.json');
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$database2Name = isset($json->database2_name) ? $json->database2_name : null; $database2Name = $json->database2_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
$collection2Name = isset($json->collection2_name) ? $json->collection2_name : null; $collection2Name = $json->collection2_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
...@@ -173,7 +173,7 @@ class ChangeStreamsSpecTest extends FunctionalTestCase ...@@ -173,7 +173,7 @@ class ChangeStreamsSpecTest extends FunctionalTestCase
private function createChangeStream(stdClass $test) private function createChangeStream(stdClass $test)
{ {
$context = $this->getContext(); $context = $this->getContext();
$pipeline = isset($test->changeStreamPipeline) ? $test->changeStreamPipeline : []; $pipeline = $test->changeStreamPipeline ?? [];
$options = isset($test->changeStreamOptions) ? (array) $test->changeStreamOptions : []; $options = isset($test->changeStreamOptions) ? (array) $test->changeStreamOptions : [];
switch ($test->target) { switch ($test->target) {
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
namespace MongoDB\Tests\SpecTests; namespace MongoDB\Tests\SpecTests;
use Closure; use Closure;
use Exception;
use MongoDB\BSON\Binary; use MongoDB\BSON\Binary;
use MongoDB\BSON\Int64; use MongoDB\BSON\Int64;
use MongoDB\Client; use MongoDB\Client;
...@@ -20,6 +19,7 @@ use MongoDB\Tests\CommandObserver; ...@@ -20,6 +19,7 @@ use MongoDB\Tests\CommandObserver;
use PHPUnit\Framework\SkippedTestError; use PHPUnit\Framework\SkippedTestError;
use stdClass; use stdClass;
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait; use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
use Throwable;
use UnexpectedValueException; use UnexpectedValueException;
use function base64_decode; use function base64_decode;
use function basename; use function basename;
...@@ -83,8 +83,8 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase ...@@ -83,8 +83,8 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase
$this->markTestSkipped($test->skipReason); $this->markTestSkipped($test->skipReason);
} }
$databaseName = isset($databaseName) ? $databaseName : $this->getDatabaseName(); $databaseName = $databaseName ?? $this->getDatabaseName();
$collectionName = isset($collectionName) ? $collectionName : $this->getCollectionName(); $collectionName = $collectionName ?? $this->getCollectionName();
try { try {
$context = Context::fromClientSideEncryption($test, $databaseName, $collectionName); $context = Context::fromClientSideEncryption($test, $databaseName, $collectionName);
...@@ -135,7 +135,7 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase ...@@ -135,7 +135,7 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase
try { try {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
} catch (Exception $e) { } catch (Throwable $e) {
$testArgs[$group] = [ $testArgs[$group] = [
(object) ['skipReason' => sprintf('Exception loading file "%s": %s', $filename, $e->getMessage())], (object) ['skipReason' => sprintf('Exception loading file "%s": %s', $filename, $e->getMessage())],
null, null,
...@@ -145,12 +145,12 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase ...@@ -145,12 +145,12 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase
continue; continue;
} }
$runOn = isset($json->runOn) ? $json->runOn : null; $runOn = $json->runOn ?? null;
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
$keyVaultData = isset($json->key_vault_data) ? $json->key_vault_data : null; $keyVaultData = $json->key_vault_data ?? null;
$jsonSchema = isset($json->json_schema) ? $json->json_schema : null; $jsonSchema = $json->json_schema ?? null;
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
...@@ -211,6 +211,7 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase ...@@ -211,6 +211,7 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase
'local' => [ 'local' => [
static function (ClientEncryption $clientEncryption, Client $client, Client $clientEncrypted, self $test) { static function (ClientEncryption $clientEncryption, Client $client, Client $clientEncrypted, self $test) {
$commands = []; $commands = [];
$localDatakeyId = null; $localDatakeyId = null;
(new CommandObserver())->observe( (new CommandObserver())->observe(
......
...@@ -145,8 +145,8 @@ class CommandMonitoringSpecTest extends FunctionalTestCase ...@@ -145,8 +145,8 @@ class CommandMonitoringSpecTest extends FunctionalTestCase
{ {
$this->checkServerRequirements($this->createRunOn($test)); $this->checkServerRequirements($this->createRunOn($test));
$databaseName = isset($databaseName) ? $databaseName : $this->getDatabaseName(); $databaseName = $databaseName ?? $this->getDatabaseName();
$collectionName = isset($collectionName) ? $collectionName : $this->getCollectionName(); $collectionName = $collectionName ?? $this->getCollectionName();
$context = Context::fromCommandMonitoring($test, $databaseName, $collectionName); $context = Context::fromCommandMonitoring($test, $databaseName, $collectionName);
$this->setContext($context); $this->setContext($context);
...@@ -174,9 +174,9 @@ class CommandMonitoringSpecTest extends FunctionalTestCase ...@@ -174,9 +174,9 @@ class CommandMonitoringSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/command-monitoring/*.json') as $filename) { foreach (glob(__DIR__ . '/command-monitoring/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename($filename, '.json'); $group = basename($filename, '.json');
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
......
...@@ -316,8 +316,8 @@ final class Context ...@@ -316,8 +316,8 @@ final class Context
} }
$w = $writeConcern['w']; $w = $writeConcern['w'];
$wtimeout = isset($writeConcern['wtimeout']) ? $writeConcern['wtimeout'] : 0; $wtimeout = $writeConcern['wtimeout'] ?? 0;
$j = isset($writeConcern['j']) ? $writeConcern['j'] : null; $j = $writeConcern['j'] ?? null;
$options['writeConcern'] = isset($j) $options['writeConcern'] = isset($j)
? new WriteConcern($w, $wtimeout, $j) ? new WriteConcern($w, $wtimeout, $j)
......
...@@ -45,8 +45,8 @@ class CrudSpecTest extends FunctionalTestCase ...@@ -45,8 +45,8 @@ class CrudSpecTest extends FunctionalTestCase
$this->markTestSkipped($test->skipReason); $this->markTestSkipped($test->skipReason);
} }
$databaseName = isset($databaseName) ? $databaseName : $this->getDatabaseName(); $databaseName = $databaseName ?? $this->getDatabaseName();
$collectionName = isset($collectionName) ? $collectionName : $this->getCollectionName(); $collectionName = $collectionName ?? $this->getCollectionName();
$context = Context::fromCrud($test, $databaseName, $collectionName); $context = Context::fromCrud($test, $databaseName, $collectionName);
$this->setContext($context); $this->setContext($context);
...@@ -84,10 +84,10 @@ class CrudSpecTest extends FunctionalTestCase ...@@ -84,10 +84,10 @@ class CrudSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/crud/*.json') as $filename) { foreach (glob(__DIR__ . '/crud/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename($filename, '.json'); $group = basename($filename, '.json');
$runOn = isset($json->runOn) ? $json->runOn : null; $runOn = $json->runOn ?? null;
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
......
...@@ -10,6 +10,7 @@ use MongoDB\Driver\Exception\RuntimeException; ...@@ -10,6 +10,7 @@ use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Exception\InvalidArgumentException; use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Tests\TestCase; use MongoDB\Tests\TestCase;
use stdClass; use stdClass;
use Throwable;
use function get_class; use function get_class;
use function is_array; use function is_array;
use function is_string; use function is_string;
...@@ -132,7 +133,7 @@ final class ErrorExpectation ...@@ -132,7 +133,7 @@ final class ErrorExpectation
* @param TestCase $test Test instance for performing assertions * @param TestCase $test Test instance for performing assertions
* @param Exception|null $actual Exception (if any) from the actual outcome * @param Exception|null $actual Exception (if any) from the actual outcome
*/ */
public function assert(TestCase $test, Exception $actual = null) public function assert(TestCase $test, Throwable $actual = null)
{ {
if (! $this->isExpected) { if (! $this->isExpected) {
if ($actual !== null) { if ($actual !== null) {
...@@ -176,7 +177,7 @@ final class ErrorExpectation ...@@ -176,7 +177,7 @@ final class ErrorExpectation
* @param TestCase $test Test instance for performing assertions * @param TestCase $test Test instance for performing assertions
* @param Exception|null $actual Exception (if any) from the actual outcome * @param Exception|null $actual Exception (if any) from the actual outcome
*/ */
private function assertCodeName(TestCase $test, Exception $actual = null) private function assertCodeName(TestCase $test, Throwable $actual = null)
{ {
/* BulkWriteException does not expose codeName for server errors. Work /* BulkWriteException does not expose codeName for server errors. Work
* around this be comparing the error code against a map. * around this be comparing the error code against a map.
...@@ -214,7 +215,7 @@ final class ErrorExpectation ...@@ -214,7 +215,7 @@ final class ErrorExpectation
$o->isExpected = $operation->error; $o->isExpected = $operation->error;
} }
$result = isset($operation->result) ? $operation->result : null; $result = $operation->result ?? null;
if (isset($result->errorContains)) { if (isset($result->errorContains)) {
$o->messageContains = $result->errorContains; $o->messageContains = $result->errorContains;
......
...@@ -137,9 +137,9 @@ class FunctionalTestCase extends BaseFunctionalTestCase ...@@ -137,9 +137,9 @@ class FunctionalTestCase extends BaseFunctionalTestCase
protected function checkServerRequirements(array $runOn) protected function checkServerRequirements(array $runOn)
{ {
foreach ($runOn as $req) { foreach ($runOn as $req) {
$minServerVersion = isset($req->minServerVersion) ? $req->minServerVersion : null; $minServerVersion = $req->minServerVersion ?? null;
$maxServerVersion = isset($req->maxServerVersion) ? $req->maxServerVersion : null; $maxServerVersion = $req->maxServerVersion ?? null;
$topologies = isset($req->topology) ? $req->topology : null; $topologies = $req->topology ?? null;
if ($this->isServerRequirementSatisifed($minServerVersion, $maxServerVersion, $topologies)) { if ($this->isServerRequirementSatisifed($minServerVersion, $maxServerVersion, $topologies)) {
return; return;
......
...@@ -322,7 +322,7 @@ final class Operation ...@@ -322,7 +322,7 @@ final class Operation
return $client->listDatabases($args); return $client->listDatabases($args);
case 'watch': case 'watch':
return $client->watch( return $client->watch(
isset($args['pipeline']) ? $args['pipeline'] : [], $args['pipeline'] ?? [],
array_diff_key($args, ['pipeline' => 1]) array_diff_key($args, ['pipeline' => 1])
); );
default: default:
...@@ -363,7 +363,7 @@ final class Operation ...@@ -363,7 +363,7 @@ final class Operation
case 'countDocuments': case 'countDocuments':
case 'find': case 'find':
return $collection->{$this->name}( return $collection->{$this->name}(
isset($args['filter']) ? $args['filter'] : [], $args['filter'] ?? [],
array_diff_key($args, ['filter' => 1]) array_diff_key($args, ['filter' => 1])
); );
case 'estimatedDocumentCount': case 'estimatedDocumentCount':
...@@ -378,7 +378,7 @@ final class Operation ...@@ -378,7 +378,7 @@ final class Operation
case 'distinct': case 'distinct':
return $collection->distinct( return $collection->distinct(
$args['fieldName'], $args['fieldName'],
isset($args['filter']) ? $args['filter'] : [], $args['filter'] ?? [],
array_diff_key($args, ['fieldName' => 1, 'filter' => 1]) array_diff_key($args, ['fieldName' => 1, 'filter' => 1])
); );
case 'drop': case 'drop':
...@@ -439,7 +439,7 @@ final class Operation ...@@ -439,7 +439,7 @@ final class Operation
); );
case 'watch': case 'watch':
return $collection->watch( return $collection->watch(
isset($args['pipeline']) ? $args['pipeline'] : [], $args['pipeline'] ?? [],
array_diff_key($args, ['pipeline' => 1]) array_diff_key($args, ['pipeline' => 1])
); );
default: default:
...@@ -475,7 +475,7 @@ final class Operation ...@@ -475,7 +475,7 @@ final class Operation
)->toArray()[0]; )->toArray()[0];
case 'watch': case 'watch':
return $database->watch( return $database->watch(
isset($args['pipeline']) ? $args['pipeline'] : [], $args['pipeline'] ?? [],
array_diff_key($args, ['pipeline' => 1]) array_diff_key($args, ['pipeline' => 1])
); );
default: default:
......
...@@ -107,11 +107,11 @@ class RetryableReadsSpecTest extends FunctionalTestCase ...@@ -107,11 +107,11 @@ class RetryableReadsSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/retryable-reads/*.json') as $filename) { foreach (glob(__DIR__ . '/retryable-reads/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename($filename, '.json'); $group = basename($filename, '.json');
$runOn = isset($json->runOn) ? $json->runOn : null; $runOn = $json->runOn ?? null;
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
$bucketName = isset($json->bucket_name) ? $json->bucket_name : null; $bucketName = $json->bucket_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
......
...@@ -58,8 +58,8 @@ class RetryableWritesSpecTest extends FunctionalTestCase ...@@ -58,8 +58,8 @@ class RetryableWritesSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/retryable-writes/*.json') as $filename) { foreach (glob(__DIR__ . '/retryable-writes/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename($filename, '.json'); $group = basename($filename, '.json');
$runOn = isset($json->runOn) ? $json->runOn : null; $runOn = $json->runOn ?? null;
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
......
...@@ -144,8 +144,8 @@ class TransactionsSpecTest extends FunctionalTestCase ...@@ -144,8 +144,8 @@ class TransactionsSpecTest extends FunctionalTestCase
$this->markTestSkipped($test->skipReason); $this->markTestSkipped($test->skipReason);
} }
$databaseName = isset($databaseName) ? $databaseName : $this->getDatabaseName(); $databaseName = $databaseName ?? $this->getDatabaseName();
$collectionName = isset($collectionName) ? $collectionName : $this->getCollectionName(); $collectionName = $collectionName ?? $this->getCollectionName();
$context = Context::fromTransactions($test, $databaseName, $collectionName, $useMultipleMongoses); $context = Context::fromTransactions($test, $databaseName, $collectionName, $useMultipleMongoses);
$this->setContext($context); $this->setContext($context);
...@@ -188,10 +188,10 @@ class TransactionsSpecTest extends FunctionalTestCase ...@@ -188,10 +188,10 @@ class TransactionsSpecTest extends FunctionalTestCase
foreach (glob(__DIR__ . '/transactions*/*.json') as $filename) { foreach (glob(__DIR__ . '/transactions*/*.json') as $filename) {
$json = $this->decodeJson(file_get_contents($filename)); $json = $this->decodeJson(file_get_contents($filename));
$group = basename(dirname($filename)) . '/' . basename($filename, '.json'); $group = basename(dirname($filename)) . '/' . basename($filename, '.json');
$runOn = isset($json->runOn) ? $json->runOn : null; $runOn = $json->runOn ?? null;
$data = isset($json->data) ? $json->data : []; $data = $json->data ?? [];
$databaseName = isset($json->database_name) ? $json->database_name : null; $databaseName = $json->database_name ?? null;
$collectionName = isset($json->collection_name) ? $json->collection_name : null; $collectionName = $json->collection_name ?? null;
foreach ($json->tests as $test) { foreach ($json->tests as $test) {
$name = $group . ': ' . $test->description; $name = $group . ': ' . $test->description;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment