From 65ee7039e77184ae2748457d6287f4235318de58 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Thu, 13 Jul 2023 13:36:18 +0200 Subject: [PATCH 01/11] PHPLIB-1118: Drop support for PHP 7.2 and 7.3 --- .evergreen/config.yml | 14 +++----------- composer.json | 2 +- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/.evergreen/config.yml b/.evergreen/config.yml index d833c3fbe..2d0fe4351 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -690,14 +690,6 @@ axes: display_name: "PHP 7.4" variables: PHP_VERSION: "7.4" - - id: "7.3" - display_name: "PHP 7.3" - variables: - PHP_VERSION: "7.3" - - id: "7.2" - display_name: "PHP 7.2" - variables: - PHP_VERSION: "7.2" - id: php-edge-versions display_name: PHP Version @@ -707,9 +699,9 @@ axes: variables: PHP_VERSION: "8.2" - id: "oldest-supported" - display_name: "PHP 7.2" + display_name: "PHP 7.4" variables: - PHP_VERSION: "7.2" + PHP_VERSION: "7.4" - id: mongodb-versions display_name: MongoDB Version @@ -898,7 +890,7 @@ buildvariants: # Exclude "latest-stable" PHP version for Debian 11 (see: test-mongodb-versions matrix) - { "os": "debian11", "mongodb-edge-versions": "latest-stable", "php-versions": "8.2", "driver-versions": "latest-stable" } # Exclude PHP versions older than 8.1 on RHEL 9 and Ubuntu 22.04 (OpenSSL 3 is only supported on PHP 8.1+) - - { "os": ["rhel90", "ubuntu2204-arm64", "ubuntu2204"], "php-versions": ["7.2", "7.3", "7.4", "8.0"], "mongodb-edge-versions": "*", "driver-versions": "*" } + - { "os": ["rhel90", "ubuntu2204-arm64", "ubuntu2204"], "php-versions": ["7.4", "8.0"], "mongodb-edge-versions": "*", "driver-versions": "*" } tasks: - name: "test-standalone" - name: "test-replica_set" diff --git a/composer.json b/composer.json index 480cf7067..8c17649ff 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ { "name": "Jérôme Tamarelle", "email": "jerome.tamarelle@mongodb.com" } ], "require": { - "php": "^7.2 || ^8.0", + "php": "^7.4 || ^8.0", "ext-hash": "*", "ext-json": "*", "ext-mongodb": "^1.16.0", From c9abfb9a8f6e652725d0dff5c156be889642407e Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Thu, 13 Jul 2023 13:38:39 +0200 Subject: [PATCH 02/11] Modernise code for PHP 7.4 This uses rector and phpcbf to automatically fix issues --- examples/bulk.php | 2 +- examples/command_logger.php | 2 +- examples/persistable.php | 14 +-- examples/typemap.php | 14 +-- examples/with_transaction.php | 4 +- phpcs.xml.dist | 4 +- rector.php | 2 +- src/BulkWriteResult.php | 9 +- src/ChangeStream.php | 7 +- src/Client.php | 21 ++-- src/Collection.php | 9 +- src/Command/ListCollections.php | 6 +- src/Command/ListDatabases.php | 3 +- src/Database.php | 6 +- src/DeleteResult.php | 6 +- .../CreateEncryptedCollectionException.php | 3 +- src/GridFS/Bucket.php | 22 ++-- src/GridFS/CollectionWrapper.php | 23 ++-- src/GridFS/ReadableStream.php | 30 ++---- src/GridFS/StreamWrapper.php | 7 +- src/GridFS/WritableStream.php | 27 ++--- src/InsertManyResult.php | 9 +- src/InsertOneResult.php | 6 +- src/MapReduceResult.php | 3 +- src/Model/BSONIterator.php | 19 ++-- src/Model/CachingIterator.php | 12 +-- src/Model/ChangeStreamIterator.php | 18 ++-- src/Model/CollectionInfo.php | 3 +- src/Model/CollectionInfoCommandIterator.php | 3 +- src/Model/DatabaseInfo.php | 3 +- src/Model/DatabaseInfoLegacyIterator.php | 3 +- src/Model/IndexInfo.php | 3 +- src/Model/IndexInfoIteratorIterator.php | 3 +- src/Model/IndexInput.php | 3 +- src/Operation/Aggregate.php | 20 ++-- src/Operation/BulkWrite.php | 11 +- src/Operation/Count.php | 9 +- src/Operation/CountDocuments.php | 15 +-- src/Operation/CreateCollection.php | 9 +- src/Operation/CreateEncryptedCollection.php | 17 ++- src/Operation/CreateIndexes.php | 19 ++-- src/Operation/DatabaseCommand.php | 9 +- src/Operation/Delete.php | 12 +-- src/Operation/DeleteMany.php | 3 +- src/Operation/DeleteOne.php | 3 +- src/Operation/Distinct.php | 12 +-- src/Operation/DropCollection.php | 9 +- src/Operation/DropDatabase.php | 6 +- src/Operation/DropEncryptedCollection.php | 5 +- src/Operation/DropIndexes.php | 12 +-- src/Operation/EstimatedDocumentCount.php | 9 +- src/Operation/Explain.php | 9 +- src/Operation/Find.php | 9 +- src/Operation/FindAndModify.php | 9 +- src/Operation/FindOne.php | 5 +- src/Operation/FindOneAndDelete.php | 5 +- src/Operation/FindOneAndReplace.php | 5 +- src/Operation/FindOneAndUpdate.php | 5 +- src/Operation/InsertMany.php | 11 +- src/Operation/InsertOne.php | 9 +- src/Operation/ListCollectionNames.php | 7 +- src/Operation/ListCollections.php | 6 +- src/Operation/ListDatabaseNames.php | 3 +- src/Operation/ListDatabases.php | 3 +- src/Operation/ListIndexes.php | 9 +- src/Operation/MapReduce.php | 23 ++-- src/Operation/ModifyCollection.php | 12 +-- src/Operation/RenameCollection.php | 9 +- src/Operation/ReplaceOne.php | 5 +- src/Operation/Update.php | 9 +- src/Operation/UpdateMany.php | 5 +- src/Operation/UpdateOne.php | 5 +- src/Operation/Watch.php | 33 ++---- src/Operation/WithTransaction.php | 3 +- src/UpdateResult.php | 6 +- tests/ClientFunctionalTest.php | 3 +- tests/Codec/CodecLibraryTest.php | 2 +- tests/Collection/CollectionFunctionalTest.php | 56 +++++----- tests/Collection/CrudSpecFunctionalTest.php | 31 +++--- tests/Collection/FunctionalTestCase.php | 3 +- tests/CommandObserver.php | 3 +- tests/Comparator/Int64Comparator.php | 4 +- tests/Comparator/Int64ComparatorTest.php | 44 ++++---- .../CollectionManagementFunctionalTest.php | 4 +- tests/Database/DatabaseFunctionalTest.php | 6 +- tests/Database/FunctionalTestCase.php | 3 +- tests/DocumentationExamplesTest.php | 62 ++++++----- tests/ExamplesTest.php | 2 +- tests/FunctionalTestCase.php | 21 ++-- tests/FunctionsTest.php | 8 +- tests/GridFS/BucketFunctionalTest.php | 25 ++--- tests/GridFS/FunctionalTestCase.php | 9 +- tests/GridFS/ReadableStreamFunctionalTest.php | 15 ++- tests/GridFS/StreamWrapperFunctionalTest.php | 16 +-- tests/GridFS/WritableStreamFunctionalTest.php | 5 +- tests/Model/BSONArrayTest.php | 4 +- tests/Model/BSONDocumentTest.php | 4 +- tests/Model/BSONIteratorTest.php | 8 +- tests/Model/CachingIteratorTest.php | 3 +- tests/Model/CallbackIteratorTest.php | 2 +- tests/Model/ChangeStreamIteratorTest.php | 5 +- tests/Model/CollectionInfoTest.php | 20 ++-- tests/Model/DatabaseInfoTest.php | 10 +- tests/Model/IndexInfoFunctionalTest.php | 3 +- tests/Operation/AggregateFunctionalTest.php | 36 +++---- tests/Operation/AggregateTest.php | 2 +- tests/Operation/BulkWriteFunctionalTest.php | 35 +++--- tests/Operation/BulkWriteTest.php | 2 +- .../CountDocumentsFunctionalTest.php | 4 +- tests/Operation/CountFunctionalTest.php | 12 +-- .../CreateCollectionFunctionalTest.php | 8 +- ...reateEncryptedCollectionFunctionalTest.php | 25 +++-- .../Operation/CreateIndexesFunctionalTest.php | 22 ++-- .../DatabaseCommandFunctionalTest.php | 8 +- tests/Operation/DeleteFunctionalTest.php | 13 ++- tests/Operation/DistinctFunctionalTest.php | 18 ++-- .../DropCollectionFunctionalTest.php | 8 +- .../Operation/DropDatabaseFunctionalTest.php | 8 +- tests/Operation/DropIndexesFunctionalTest.php | 8 +- tests/Operation/ExplainFunctionalTest.php | 20 ++-- .../Operation/FindAndModifyFunctionalTest.php | 36 +++---- tests/Operation/FindFunctionalTest.php | 18 ++-- tests/Operation/InsertManyFunctionalTest.php | 19 ++-- tests/Operation/InsertOneFunctionalTest.php | 19 ++-- .../ListCollectionNamesFunctionalTest.php | 8 +- .../ListCollectionsFunctionalTest.php | 8 +- .../ListDatabaseNamesFunctionalTest.php | 10 +- .../Operation/ListDatabasesFunctionalTest.php | 10 +- tests/Operation/ListIndexesFunctionalTest.php | 4 +- tests/Operation/MapReduceFunctionalTest.php | 20 ++-- .../ModifyCollectionFunctionalTest.php | 2 +- .../RenameCollectionFunctionalTest.php | 23 ++-- tests/Operation/RenameCollectionTest.php | 2 +- tests/Operation/UpdateFunctionalTest.php | 25 +++-- tests/Operation/WatchFunctionalTest.php | 56 +++++----- tests/PHPUnit/Functions.php | 2 +- tests/PedantryTest.php | 14 +-- tests/SpecTests/AtlasDataLakeSpecTest.php | 8 +- ...rose21_AutomaticDataEncryptionKeysTest.php | 13 +-- .../Prose22_RangeExplicitEncryptionTest.php | 28 ++--- .../ClientSideEncryptionSpecTest.php | 37 +++---- tests/SpecTests/CommandExpectations.php | 25 ++--- tests/SpecTests/Context.php | 44 +++----- tests/SpecTests/DocumentsMatchConstraint.php | 28 ++--- .../DocumentsMatchConstraintTest.php | 2 +- tests/SpecTests/ErrorExpectation.php | 24 ++--- tests/SpecTests/FunctionalTestCase.php | 7 +- tests/SpecTests/Operation.php | 67 +++++------- tests/SpecTests/PrimaryStepDownSpecTest.php | 10 +- tests/SpecTests/ReadWriteConcernSpecTest.php | 7 +- tests/SpecTests/ResultExpectation.php | 17 ++- tests/SpecTests/RetryableReadsSpecTest.php | 7 +- tests/SpecTests/RetryableWritesSpecTest.php | 2 +- tests/SpecTests/TransactionsSpecTest.php | 10 +- tests/TestCase.php | 22 ++-- tests/UnifiedSpecTests/CollectionData.php | 13 +-- .../Constraint/IsBsonType.php | 10 +- .../Constraint/IsBsonTypeTest.php | 2 +- tests/UnifiedSpecTests/Constraint/Matches.php | 27 ++--- tests/UnifiedSpecTests/Context.php | 31 +++--- tests/UnifiedSpecTests/EntityMap.php | 38 +++---- tests/UnifiedSpecTests/EventCollector.php | 15 +-- tests/UnifiedSpecTests/EventObserver.php | 32 ++---- tests/UnifiedSpecTests/ExpectedError.php | 34 ++---- tests/UnifiedSpecTests/ExpectedResult.php | 10 +- tests/UnifiedSpecTests/FailPointObserver.php | 2 +- tests/UnifiedSpecTests/Loop.php | 24 ++--- tests/UnifiedSpecTests/Operation.php | 100 +++++++----------- tests/UnifiedSpecTests/RunOnRequirement.php | 27 ++--- .../ServerParameterHelper.php | 15 ++- tests/UnifiedSpecTests/UnifiedSpecTest.php | 6 +- tests/UnifiedSpecTests/UnifiedTestCase.php | 15 +-- tests/UnifiedSpecTests/UnifiedTestRunner.php | 21 ++-- tests/UnifiedSpecTests/Util.php | 2 +- tools/connect.php | 2 +- 175 files changed, 972 insertions(+), 1392 deletions(-) diff --git a/examples/bulk.php b/examples/bulk.php index 316594f00..dc1d8100f 100644 --- a/examples/bulk.php +++ b/examples/bulk.php @@ -68,7 +68,7 @@ function toJSON(object $document): string ['x' => 10], // Document ], ], - ] + ], ); $cursor = $collection->find([]); diff --git a/examples/command_logger.php b/examples/command_logger.php index 9d3f7c0fe..59669fd42 100644 --- a/examples/command_logger.php +++ b/examples/command_logger.php @@ -69,7 +69,7 @@ public function commandFailed(CommandFailedEvent $event): void $collection->updateMany( ['x' => ['$gt' => 1]], - ['$set' => ['y' => 1]] + ['$set' => ['y' => 1]], ); $cursor = $collection->find([], ['batchSize' => 2]); diff --git a/examples/persistable.php b/examples/persistable.php index 6e23a16bb..faf18bf6f 100644 --- a/examples/persistable.php +++ b/examples/persistable.php @@ -16,14 +16,12 @@ class PersistableEntry implements Persistable { - /** @var ObjectId */ - private $id; + private ObjectId $id; - /** @var string */ - public $name; + public string $name; /** @var array */ - public $emails = []; + public array $emails = []; public function __construct(string $name) { @@ -65,11 +63,9 @@ public function bsonUnserialize(array $data): void class PersistableEmail implements Persistable { - /** @var string */ - public $type; + public string $type; - /** @var string */ - public $address; + public string $address; public function __construct(string $type, string $address) { diff --git a/examples/typemap.php b/examples/typemap.php index 9dc96b016..875e1043b 100644 --- a/examples/typemap.php +++ b/examples/typemap.php @@ -16,14 +16,12 @@ class TypeMapEntry implements Unserializable { - /** @var ObjectId */ - private $id; + private ObjectId $id; - /** @var string */ - private $name; + private string $name; /** @var array */ - private $emails; + private array $emails; private function __construct() { @@ -64,11 +62,9 @@ public function bsonUnserialize(array $data): void class TypeMapEmail implements Unserializable { - /** @var string */ - private $type; + private string $type; - /** @var string */ - private $address; + private string $address; private function __construct() { diff --git a/examples/with_transaction.php b/examples/with_transaction.php index 15eba6524..aa1897112 100644 --- a/examples/with_transaction.php +++ b/examples/with_transaction.php @@ -37,13 +37,13 @@ function toJSON(object $document): string ['x' => 2], ['x' => 3], ], - ['session' => $session] + ['session' => $session], ); $collection->updateMany( ['x' => ['$gt' => 1]], ['$set' => ['y' => 1]], - ['session' => $session] + ['session' => $session], ); }; diff --git a/phpcs.xml.dist b/phpcs.xml.dist index b474f2a4e..dcbfb45e6 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -17,7 +17,7 @@ rector.php - + @@ -112,8 +112,6 @@ - - diff --git a/rector.php b/rector.php index cf5d60690..06d194141 100644 --- a/rector.php +++ b/rector.php @@ -15,7 +15,7 @@ ]); // Modernize code - $rectorConfig->sets([LevelSetList::UP_TO_PHP_72]); + $rectorConfig->sets([LevelSetList::UP_TO_PHP_74]); $rectorConfig->skip([ // Falsely detect unassigned variables in code paths stopped by PHPUnit\Framework\Assert::markTestSkipped() diff --git a/src/BulkWriteResult.php b/src/BulkWriteResult.php index b73771e03..9f86c3a81 100644 --- a/src/BulkWriteResult.php +++ b/src/BulkWriteResult.php @@ -25,14 +25,11 @@ */ class BulkWriteResult { - /** @var WriteResult */ - private $writeResult; + private WriteResult $writeResult; - /** @var array */ - private $insertedIds; + private array $insertedIds; - /** @var boolean */ - private $isAcknowledged; + private bool $isAcknowledged; public function __construct(WriteResult $writeResult, array $insertedIds) { diff --git a/src/ChangeStream.php b/src/ChangeStream.php index 91282e8fa..09ebf7a6a 100644 --- a/src/ChangeStream.php +++ b/src/ChangeStream.php @@ -74,16 +74,13 @@ class ChangeStream implements Iterator /** @var ChangeStreamIterator */ private $iterator; - /** @var integer */ - private $key = 0; + private int $key = 0; /** * Whether the change stream has advanced to its first result. This is used * to determine whether $key should be incremented after an iteration event. - * - * @var boolean */ - private $hasAdvanced = false; + private bool $hasAdvanced = false; /** * @internal diff --git a/src/Client.php b/src/Client.php index 5b9eedea4..06ac91846 100644 --- a/src/Client.php +++ b/src/Client.php @@ -54,26 +54,19 @@ class Client private const HANDSHAKE_SEPARATOR = '/'; - /** @var string|null */ - private static $version; + private static ?string $version = null; - /** @var Manager */ - private $manager; + private Manager $manager; - /** @var ReadConcern */ - private $readConcern; + private ReadConcern $readConcern; - /** @var ReadPreference */ - private $readPreference; + private ReadPreference $readPreference; - /** @var string */ - private $uri; + private string $uri; - /** @var array */ - private $typeMap; + private array $typeMap; - /** @var WriteConcern */ - private $writeConcern; + private WriteConcern $writeConcern; /** * Constructs a new Client instance. diff --git a/src/Collection.php b/src/Collection.php index d92dc66da..a6d911f20 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -77,14 +77,11 @@ class Collection private const WIRE_VERSION_FOR_READ_CONCERN_WITH_WRITE_STAGE = 8; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var Manager */ - private $manager; + private Manager $manager; /** @var ReadConcern */ private $readConcern; diff --git a/src/Command/ListCollections.php b/src/Command/ListCollections.php index 7b6e84489..66db017b8 100644 --- a/src/Command/ListCollections.php +++ b/src/Command/ListCollections.php @@ -37,11 +37,9 @@ */ class ListCollections implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var array */ - private $options; + private array $options; /** * Constructs a listCollections command. diff --git a/src/Command/ListDatabases.php b/src/Command/ListDatabases.php index 94e1f8750..3aba5f835 100644 --- a/src/Command/ListDatabases.php +++ b/src/Command/ListDatabases.php @@ -39,8 +39,7 @@ */ class ListDatabases implements Executable { - /** @var array */ - private $options; + private array $options; /** * Constructs a listDatabases command. diff --git a/src/Database.php b/src/Database.php index f2f9278b5..9804b1b67 100644 --- a/src/Database.php +++ b/src/Database.php @@ -61,11 +61,9 @@ class Database private const WIRE_VERSION_FOR_READ_CONCERN_WITH_WRITE_STAGE = 8; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var Manager */ - private $manager; + private Manager $manager; /** @var ReadConcern */ private $readConcern; diff --git a/src/DeleteResult.php b/src/DeleteResult.php index 3c5b2cdd4..7d2744ccc 100644 --- a/src/DeleteResult.php +++ b/src/DeleteResult.php @@ -25,11 +25,9 @@ */ class DeleteResult { - /** @var WriteResult */ - private $writeResult; + private WriteResult $writeResult; - /** @var boolean */ - private $isAcknowledged; + private bool $isAcknowledged; public function __construct(WriteResult $writeResult) { diff --git a/src/Exception/CreateEncryptedCollectionException.php b/src/Exception/CreateEncryptedCollectionException.php index 7330c7f6f..3aca268fe 100644 --- a/src/Exception/CreateEncryptedCollectionException.php +++ b/src/Exception/CreateEncryptedCollectionException.php @@ -28,8 +28,7 @@ */ final class CreateEncryptedCollectionException extends RuntimeException { - /** @var array */ - private $encryptedFields; + private array $encryptedFields; public function __construct(Throwable $previous, array $encryptedFields) { diff --git a/src/GridFS/Bucket.php b/src/GridFS/Bucket.php index b58c7bda8..4d2c6da44 100644 --- a/src/GridFS/Bucket.php +++ b/src/GridFS/Bucket.php @@ -74,23 +74,17 @@ class Bucket private const STREAM_WRAPPER_PROTOCOL = 'gridfs'; - /** @var CollectionWrapper */ - private $collectionWrapper; + private CollectionWrapper $collectionWrapper; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var Manager */ - private $manager; + private Manager $manager; - /** @var string */ - private $bucketName; + private string $bucketName; - /** @var boolean */ - private $disableMD5; + private bool $disableMD5; - /** @var integer */ - private $chunkSizeBytes; + private int $chunkSizeBytes; /** @var ReadConcern */ private $readConcern; @@ -654,7 +648,7 @@ private function createPathForFile(object $file): string self::STREAM_WRAPPER_PROTOCOL, urlencode($this->databaseName), urlencode($this->bucketName), - urlencode($id) + urlencode($id), ); } @@ -667,7 +661,7 @@ private function createPathForUpload(): string '%s://%s/%s.files', self::STREAM_WRAPPER_PROTOCOL, urlencode($this->databaseName), - urlencode($this->bucketName) + urlencode($this->bucketName), ); } diff --git a/src/GridFS/CollectionWrapper.php b/src/GridFS/CollectionWrapper.php index 4642028e3..11ad145a6 100644 --- a/src/GridFS/CollectionWrapper.php +++ b/src/GridFS/CollectionWrapper.php @@ -40,20 +40,15 @@ */ class CollectionWrapper { - /** @var string */ - private $bucketName; + private string $bucketName; - /** @var Collection */ - private $chunksCollection; + private Collection $chunksCollection; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var boolean */ - private $checkedIndexes = false; + private bool $checkedIndexes = false; - /** @var Collection */ - private $filesCollection; + private Collection $filesCollection; /** * Constructs a GridFS collection wrapper. @@ -120,7 +115,7 @@ public function findChunksByFileId($id, int $fromChunk = 0): Cursor [ 'sort' => ['n' => 1], 'typeMap' => ['root' => 'stdClass'], - ] + ], ); } @@ -158,7 +153,7 @@ public function findFileByFilenameAndRevision(string $filename, int $revision): 'skip' => $skip, 'sort' => ['uploadDate' => $sortOrder], 'typeMap' => ['root' => 'stdClass'], - ] + ], ); assert(is_object($file) || $file === null); @@ -174,7 +169,7 @@ public function findFileById($id): ?object { $file = $this->filesCollection->findOne( ['_id' => $id], - ['typeMap' => ['root' => 'stdClass']] + ['typeMap' => ['root' => 'stdClass']], ); assert(is_object($file) || $file === null); @@ -265,7 +260,7 @@ public function updateFilenameForId($id, string $filename): UpdateResult { return $this->filesCollection->updateOne( ['_id' => $id], - ['$set' => ['filename' => $filename]] + ['$set' => ['filename' => $filename]], ); } diff --git a/src/GridFS/ReadableStream.php b/src/GridFS/ReadableStream.php index 7c3d8be4b..577384f2b 100644 --- a/src/GridFS/ReadableStream.php +++ b/src/GridFS/ReadableStream.php @@ -39,35 +39,25 @@ */ class ReadableStream { - /** @var string|null */ - private $buffer; + private ?string $buffer = null; - /** @var integer */ - private $bufferOffset = 0; + private int $bufferOffset = 0; - /** @var integer */ - private $chunkSize; + private int $chunkSize; - /** @var integer */ - private $chunkOffset = 0; + private int $chunkOffset = 0; - /** @var Cursor|null */ - private $chunksIterator; + private ?Cursor $chunksIterator = null; - /** @var CollectionWrapper */ - private $collectionWrapper; + private CollectionWrapper $collectionWrapper; - /** @var integer */ - private $expectedLastChunkSize = 0; + private int $expectedLastChunkSize = 0; - /** @var object */ - private $file; + private object $file; - /** @var integer */ - private $length; + private int $length; - /** @var integer */ - private $numChunks = 0; + private int $numChunks = 0; /** * Constructs a readable GridFS stream. diff --git a/src/GridFS/StreamWrapper.php b/src/GridFS/StreamWrapper.php index a90104e9a..71a36d07b 100644 --- a/src/GridFS/StreamWrapper.php +++ b/src/GridFS/StreamWrapper.php @@ -46,8 +46,7 @@ class StreamWrapper /** @var resource|null Stream context (set by PHP) */ public $context; - /** @var string|null */ - private $protocol; + private ?string $protocol = null; /** @var ReadableStream|WritableStream|null */ private $stream; @@ -298,7 +297,7 @@ private function initReadableStream(): bool assert($this->protocol !== null); $this->stream = new ReadableStream( $context[$this->protocol]['collectionWrapper'], - $context[$this->protocol]['file'] + $context[$this->protocol]['file'], ); return true; @@ -318,7 +317,7 @@ private function initWritableStream(): bool $this->stream = new WritableStream( $context[$this->protocol]['collectionWrapper'], $context[$this->protocol]['filename'], - $context[$this->protocol]['options'] + $context[$this->protocol]['options'], ); return true; diff --git a/src/GridFS/WritableStream.php b/src/GridFS/WritableStream.php index ff30927de..e61b04fac 100644 --- a/src/GridFS/WritableStream.php +++ b/src/GridFS/WritableStream.php @@ -46,32 +46,23 @@ class WritableStream { private const DEFAULT_CHUNK_SIZE_BYTES = 261120; - /** @var string */ - private $buffer = ''; + private string $buffer = ''; - /** @var integer */ - private $chunkOffset = 0; + private int $chunkOffset = 0; - /** @var integer */ - private $chunkSize; + private int $chunkSize; - /** @var boolean */ - private $disableMD5; + private bool $disableMD5; - /** @var CollectionWrapper */ - private $collectionWrapper; + private CollectionWrapper $collectionWrapper; - /** @var array */ - private $file; + private array $file; - /** @var HashContext|null */ - private $hashCtx; + private ?HashContext $hashCtx = null; - /** @var boolean */ - private $isClosed = false; + private bool $isClosed = false; - /** @var integer */ - private $length = 0; + private int $length = 0; /** * Constructs a writable GridFS stream. diff --git a/src/InsertManyResult.php b/src/InsertManyResult.php index 5de89920e..f8c33ad0b 100644 --- a/src/InsertManyResult.php +++ b/src/InsertManyResult.php @@ -25,14 +25,11 @@ */ class InsertManyResult { - /** @var WriteResult */ - private $writeResult; + private WriteResult $writeResult; - /** @var array */ - private $insertedIds; + private array $insertedIds; - /** @var boolean */ - private $isAcknowledged; + private bool $isAcknowledged; public function __construct(WriteResult $writeResult, array $insertedIds) { diff --git a/src/InsertOneResult.php b/src/InsertOneResult.php index 0a387579f..da851d204 100644 --- a/src/InsertOneResult.php +++ b/src/InsertOneResult.php @@ -25,14 +25,12 @@ */ class InsertOneResult { - /** @var WriteResult */ - private $writeResult; + private WriteResult $writeResult; /** @var mixed */ private $insertedId; - /** @var boolean */ - private $isAcknowledged; + private bool $isAcknowledged; /** @param mixed $insertedId */ public function __construct(WriteResult $writeResult, $insertedId) diff --git a/src/MapReduceResult.php b/src/MapReduceResult.php index 4c70b4a07..7095f5e2d 100644 --- a/src/MapReduceResult.php +++ b/src/MapReduceResult.php @@ -39,8 +39,7 @@ class MapReduceResult implements IteratorAggregate /** @var callable */ private $getIterator; - /** @var integer */ - private $executionTimeMS; + private int $executionTimeMS; /** @var array */ private $counts; diff --git a/src/Model/BSONIterator.php b/src/Model/BSONIterator.php index daf1d413e..1f630c669 100644 --- a/src/Model/BSONIterator.php +++ b/src/Model/BSONIterator.php @@ -36,23 +36,18 @@ class BSONIterator implements Iterator { private const BSON_SIZE = 4; - /** @var string */ - private $buffer; + private string $buffer; - /** @var integer */ - private $bufferLength; + private int $bufferLength; - /** @var mixed */ - private $current; + /** @var array|object|null */ + private $current = null; - /** @var integer */ - private $key = 0; + private int $key = 0; - /** @var integer */ - private $position = 0; + private int $position = 0; - /** @var array */ - private $options; + private array $options; /** * Constructs a BSON Iterator. diff --git a/src/Model/CachingIterator.php b/src/Model/CachingIterator.php index ff0e35d55..78c9a3626 100644 --- a/src/Model/CachingIterator.php +++ b/src/Model/CachingIterator.php @@ -42,17 +42,13 @@ class CachingIterator implements Countable, Iterator private const FIELD_KEY = 0; private const FIELD_VALUE = 1; - /** @var array */ - private $items = []; + private array $items = []; - /** @var Iterator */ - private $iterator; + private Iterator $iterator; - /** @var boolean */ - private $iteratorAdvanced = false; + private bool $iteratorAdvanced = false; - /** @var boolean */ - private $iteratorExhausted = false; + private bool $iteratorExhausted = false; /** * Initialize the iterator and stores the first item in the cache. This diff --git a/src/Model/ChangeStreamIterator.php b/src/Model/ChangeStreamIterator.php index c34e07d4e..b089b09f5 100644 --- a/src/Model/ChangeStreamIterator.php +++ b/src/Model/ChangeStreamIterator.php @@ -49,26 +49,20 @@ */ class ChangeStreamIterator extends IteratorIterator implements CommandSubscriber { - /** @var integer */ - private $batchPosition = 0; + private int $batchPosition = 0; - /** @var integer */ - private $batchSize; + private int $batchSize; - /** @var boolean */ - private $isRewindNop; + private bool $isRewindNop; - /** @var boolean */ - private $isValid = false; + private bool $isValid = false; - /** @var object|null */ - private $postBatchResumeToken; + private ?object $postBatchResumeToken = null; /** @var array|object|null */ private $resumeToken; - /** @var Server */ - private $server; + private Server $server; /** * @internal diff --git a/src/Model/CollectionInfo.php b/src/Model/CollectionInfo.php index 4940a5e00..f6481a78c 100644 --- a/src/Model/CollectionInfo.php +++ b/src/Model/CollectionInfo.php @@ -35,8 +35,7 @@ */ class CollectionInfo implements ArrayAccess { - /** @var array */ - private $info; + private array $info; /** @param array $info Collection info */ public function __construct(array $info) diff --git a/src/Model/CollectionInfoCommandIterator.php b/src/Model/CollectionInfoCommandIterator.php index 96c2d73a9..b0d4e0118 100644 --- a/src/Model/CollectionInfoCommandIterator.php +++ b/src/Model/CollectionInfoCommandIterator.php @@ -33,8 +33,7 @@ */ class CollectionInfoCommandIterator extends IteratorIterator implements CollectionInfoIterator { - /** @var string|null */ - private $databaseName; + private ?string $databaseName = null; public function __construct(Traversable $iterator, ?string $databaseName = null) { diff --git a/src/Model/DatabaseInfo.php b/src/Model/DatabaseInfo.php index 062600784..4d4e57667 100644 --- a/src/Model/DatabaseInfo.php +++ b/src/Model/DatabaseInfo.php @@ -34,8 +34,7 @@ */ class DatabaseInfo implements ArrayAccess { - /** @var array */ - private $info; + private array $info; /** @param array $info Database info */ public function __construct(array $info) diff --git a/src/Model/DatabaseInfoLegacyIterator.php b/src/Model/DatabaseInfoLegacyIterator.php index 2fb8e88a5..4bbf46a42 100644 --- a/src/Model/DatabaseInfoLegacyIterator.php +++ b/src/Model/DatabaseInfoLegacyIterator.php @@ -34,8 +34,7 @@ */ class DatabaseInfoLegacyIterator implements DatabaseInfoIterator { - /** @var array */ - private $databases; + private array $databases; public function __construct(array $databases) { diff --git a/src/Model/IndexInfo.php b/src/Model/IndexInfo.php index 4d86bab16..74f230254 100644 --- a/src/Model/IndexInfo.php +++ b/src/Model/IndexInfo.php @@ -43,8 +43,7 @@ */ class IndexInfo implements ArrayAccess { - /** @var array */ - private $info; + private array $info; /** @param array $info Index info */ public function __construct(array $info) diff --git a/src/Model/IndexInfoIteratorIterator.php b/src/Model/IndexInfoIteratorIterator.php index f0a35baf0..09537c046 100644 --- a/src/Model/IndexInfoIteratorIterator.php +++ b/src/Model/IndexInfoIteratorIterator.php @@ -37,8 +37,7 @@ */ class IndexInfoIteratorIterator extends IteratorIterator implements IndexInfoIterator { - /** @var string|null $ns */ - private $ns; + private ?string $ns = null; public function __construct(Traversable $iterator, ?string $ns = null) { diff --git a/src/Model/IndexInput.php b/src/Model/IndexInput.php index b95fbfc1f..1c089db9e 100644 --- a/src/Model/IndexInput.php +++ b/src/Model/IndexInput.php @@ -39,8 +39,7 @@ */ class IndexInput implements Serializable { - /** @var array */ - private $index; + private array $index; /** * @param array $index Index specification diff --git a/src/Operation/Aggregate.php b/src/Operation/Aggregate.php index 43f964410..be6cc60a9 100644 --- a/src/Operation/Aggregate.php +++ b/src/Operation/Aggregate.php @@ -50,23 +50,17 @@ */ class Aggregate implements Executable, Explainable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string|null */ - private $collectionName; + private ?string $collectionName = null; - /** @var array */ - private $pipeline; + private array $pipeline; - /** @var array */ - private $options; + private array $options; - /** @var bool */ - private $isExplain; + private bool $isExplain; - /** @var bool */ - private $isWrite; + private bool $isWrite; /** * Constructs an aggregate command. @@ -267,7 +261,7 @@ public function execute(Server $server) $command = new Command( $this->createCommandDocument(), - $this->createCommandOptions() + $this->createCommandOptions(), ); $cursor = $this->executeCommand($server, $command); diff --git a/src/Operation/BulkWrite.php b/src/Operation/BulkWrite.php index 0f5153489..495bdb819 100644 --- a/src/Operation/BulkWrite.php +++ b/src/Operation/BulkWrite.php @@ -52,17 +52,14 @@ class BulkWrite implements Executable public const UPDATE_MANY = 'updateMany'; public const UPDATE_ONE = 'updateOne'; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array[] */ - private $operations; + private array $operations; - /** @var array */ - private $options; + private array $options; /** * Constructs a bulk write operation. diff --git a/src/Operation/Count.php b/src/Operation/Count.php index b42050ae3..3ae3340e7 100644 --- a/src/Operation/Count.php +++ b/src/Operation/Count.php @@ -43,17 +43,14 @@ */ class Count implements Executable, Explainable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $filter; - /** @var array */ - private $options; + private array $options; /** * Constructs a count command. diff --git a/src/Operation/CountDocuments.php b/src/Operation/CountDocuments.php index ecb0e135d..e1652a394 100644 --- a/src/Operation/CountDocuments.php +++ b/src/Operation/CountDocuments.php @@ -41,23 +41,18 @@ */ class CountDocuments implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $filter; - /** @var array */ - private $aggregateOptions; + private array $aggregateOptions; - /** @var array */ - private $countOptions; + private array $countOptions; - /** @var Aggregate */ - private $aggregate; + private Aggregate $aggregate; /** * Constructs an aggregate command for counting documents diff --git a/src/Operation/CreateCollection.php b/src/Operation/CreateCollection.php index 795542fea..470359542 100644 --- a/src/Operation/CreateCollection.php +++ b/src/Operation/CreateCollection.php @@ -46,14 +46,11 @@ class CreateCollection implements Executable public const USE_POWER_OF_2_SIZES = 1; public const NO_PADDING = 2; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options = []; + private array $options = []; /** * Constructs a create command. diff --git a/src/Operation/CreateEncryptedCollection.php b/src/Operation/CreateEncryptedCollection.php index aced1321f..973720199 100644 --- a/src/Operation/CreateEncryptedCollection.php +++ b/src/Operation/CreateEncryptedCollection.php @@ -52,23 +52,18 @@ class CreateEncryptedCollection implements Executable { private const WIRE_VERSION_FOR_QUERYABLE_ENCRYPTION_V2 = 21; - /** @var CreateCollection */ - private $createCollection; + private CreateCollection $createCollection; /** @var CreateCollection[] */ - private $createMetadataCollections; + private array $createMetadataCollections; - /** @var CreateIndexes */ - private $createSafeContentIndex; + private CreateIndexes $createSafeContentIndex; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options; + private array $options; /** * @see CreateCollection::__construct() for supported options diff --git a/src/Operation/CreateIndexes.php b/src/Operation/CreateIndexes.php index 1b8414fd8..a71825812 100644 --- a/src/Operation/CreateIndexes.php +++ b/src/Operation/CreateIndexes.php @@ -45,17 +45,13 @@ class CreateIndexes implements Executable { private const WIRE_VERSION_FOR_COMMIT_QUORUM = 9; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $indexes = []; + private array $indexes = []; - /** @var array */ - private $options = []; + private array $options = []; /** * Constructs a createIndexes command. @@ -143,9 +139,10 @@ public function execute(Server $server) $this->executeCommand($server); - return array_map(function (IndexInput $index) { - return (string) $index; - }, $this->indexes); + return array_map( + fn (IndexInput $index): string => (string) $index, + $this->indexes, + ); } /** diff --git a/src/Operation/DatabaseCommand.php b/src/Operation/DatabaseCommand.php index 39e5a9928..adcccca37 100644 --- a/src/Operation/DatabaseCommand.php +++ b/src/Operation/DatabaseCommand.php @@ -34,14 +34,11 @@ */ class DatabaseCommand implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var Command */ - private $command; + private Command $command; - /** @var array */ - private $options; + private array $options; /** * Constructs a command. diff --git a/src/Operation/Delete.php b/src/Operation/Delete.php index 99bad4ebf..b23e1eac9 100644 --- a/src/Operation/Delete.php +++ b/src/Operation/Delete.php @@ -46,20 +46,16 @@ class Delete implements Executable, Explainable { private const WIRE_VERSION_FOR_HINT = 9; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $filter; - /** @var integer */ - private $limit; + private int $limit; - /** @var array */ - private $options; + private array $options; /** * Constructs a delete command. diff --git a/src/Operation/DeleteMany.php b/src/Operation/DeleteMany.php index 087a60b6d..9f580133e 100644 --- a/src/Operation/DeleteMany.php +++ b/src/Operation/DeleteMany.php @@ -31,8 +31,7 @@ */ class DeleteMany implements Executable, Explainable { - /** @var Delete */ - private $delete; + private Delete $delete; /** * Constructs a delete command. diff --git a/src/Operation/DeleteOne.php b/src/Operation/DeleteOne.php index 6c3133f34..3e2c3e089 100644 --- a/src/Operation/DeleteOne.php +++ b/src/Operation/DeleteOne.php @@ -31,8 +31,7 @@ */ class DeleteOne implements Executable, Explainable { - /** @var Delete */ - private $delete; + private Delete $delete; /** * Constructs a delete command. diff --git a/src/Operation/Distinct.php b/src/Operation/Distinct.php index 5c8863fbc..d2f039d2a 100644 --- a/src/Operation/Distinct.php +++ b/src/Operation/Distinct.php @@ -42,20 +42,16 @@ */ class Distinct implements Executable, Explainable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var string */ - private $fieldName; + private string $fieldName; /** @var array|object */ private $filter; - /** @var array */ - private $options; + private array $options; /** * Constructs a distinct command. diff --git a/src/Operation/DropCollection.php b/src/Operation/DropCollection.php index 38b362306..d24f9fd88 100644 --- a/src/Operation/DropCollection.php +++ b/src/Operation/DropCollection.php @@ -40,14 +40,11 @@ class DropCollection implements Executable { private const ERROR_CODE_NAMESPACE_NOT_FOUND = 26; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options; + private array $options; /** * Constructs a drop command. diff --git a/src/Operation/DropDatabase.php b/src/Operation/DropDatabase.php index e207c96de..76a3d772f 100644 --- a/src/Operation/DropDatabase.php +++ b/src/Operation/DropDatabase.php @@ -36,11 +36,9 @@ */ class DropDatabase implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var array */ - private $options; + private array $options; /** * Constructs a dropDatabase command. diff --git a/src/Operation/DropEncryptedCollection.php b/src/Operation/DropEncryptedCollection.php index 6bcdf06d5..381ab8af5 100644 --- a/src/Operation/DropEncryptedCollection.php +++ b/src/Operation/DropEncryptedCollection.php @@ -39,11 +39,10 @@ */ class DropEncryptedCollection implements Executable { - /** @var DropCollection */ - private $dropCollection; + private DropCollection $dropCollection; /** @var DropCollection[] */ - private $dropMetadataCollections; + private array $dropMetadataCollections; /** * Constructs an operation to drop an encrypted collection and its related diff --git a/src/Operation/DropIndexes.php b/src/Operation/DropIndexes.php index 915fbe5a9..66ded5712 100644 --- a/src/Operation/DropIndexes.php +++ b/src/Operation/DropIndexes.php @@ -37,17 +37,13 @@ */ class DropIndexes implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var string */ - private $indexName; + private string $indexName; - /** @var array */ - private $options; + private array $options; /** * Constructs a dropIndexes command. diff --git a/src/Operation/EstimatedDocumentCount.php b/src/Operation/EstimatedDocumentCount.php index ca53ff029..718a0142c 100644 --- a/src/Operation/EstimatedDocumentCount.php +++ b/src/Operation/EstimatedDocumentCount.php @@ -37,14 +37,11 @@ */ class EstimatedDocumentCount implements Executable, Explainable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options; + private array $options; /** * Constructs a command to get the estimated number of documents in a diff --git a/src/Operation/Explain.php b/src/Operation/Explain.php index 7e3bebda6..c3b3fa526 100644 --- a/src/Operation/Explain.php +++ b/src/Operation/Explain.php @@ -44,14 +44,11 @@ class Explain implements Executable private const WIRE_VERSION_FOR_AGGREGATE = 7; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var Explainable */ - private $explainable; + private Explainable $explainable; - /** @var array */ - private $options; + private array $options; /** * Constructs an explain command for explainable operations. diff --git a/src/Operation/Find.php b/src/Operation/Find.php index d3ec85f1a..622b5a540 100644 --- a/src/Operation/Find.php +++ b/src/Operation/Find.php @@ -51,17 +51,14 @@ class Find implements Executable, Explainable public const TAILABLE = 2; public const TAILABLE_AWAIT = 3; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $filter; - /** @var array */ - private $options; + private array $options; /** * Constructs a find command. diff --git a/src/Operation/FindAndModify.php b/src/Operation/FindAndModify.php index 8a08e9b4d..8f23d1237 100644 --- a/src/Operation/FindAndModify.php +++ b/src/Operation/FindAndModify.php @@ -54,14 +54,11 @@ class FindAndModify implements Executable, Explainable private const WIRE_VERSION_FOR_UNSUPPORTED_OPTION_SERVER_SIDE_ERROR = 8; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options; + private array $options; /** * Constructs a findAndModify command. diff --git a/src/Operation/FindOne.php b/src/Operation/FindOne.php index 095ffaf1a..8d6430058 100644 --- a/src/Operation/FindOne.php +++ b/src/Operation/FindOne.php @@ -33,8 +33,7 @@ */ class FindOne implements Executable, Explainable { - /** @var Find */ - private $find; + private Find $find; /** * Constructs a find command for finding a single document. @@ -108,7 +107,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $databaseName, $collectionName, $filter, - ['limit' => 1] + $options + ['limit' => 1] + $options, ); } diff --git a/src/Operation/FindOneAndDelete.php b/src/Operation/FindOneAndDelete.php index d37523003..39381b1fb 100644 --- a/src/Operation/FindOneAndDelete.php +++ b/src/Operation/FindOneAndDelete.php @@ -32,8 +32,7 @@ */ class FindOneAndDelete implements Executable, Explainable { - /** @var FindAndModify */ - private $findAndModify; + private FindAndModify $findAndModify; /** * Constructs a findAndModify command for deleting a document. @@ -98,7 +97,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $this->findAndModify = new FindAndModify( $databaseName, $collectionName, - ['query' => $filter, 'remove' => true] + $options + ['query' => $filter, 'remove' => true] + $options, ); } diff --git a/src/Operation/FindOneAndReplace.php b/src/Operation/FindOneAndReplace.php index ca1c96c79..34fe6a2d8 100644 --- a/src/Operation/FindOneAndReplace.php +++ b/src/Operation/FindOneAndReplace.php @@ -39,8 +39,7 @@ class FindOneAndReplace implements Executable, Explainable public const RETURN_DOCUMENT_BEFORE = 1; public const RETURN_DOCUMENT_AFTER = 2; - /** @var FindAndModify */ - private $findAndModify; + private FindAndModify $findAndModify; /** * Constructs a findAndModify command for replacing a document. @@ -151,7 +150,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $this->findAndModify = new FindAndModify( $databaseName, $collectionName, - ['query' => $filter, 'update' => $replacement] + $options + ['query' => $filter, 'update' => $replacement] + $options, ); } diff --git a/src/Operation/FindOneAndUpdate.php b/src/Operation/FindOneAndUpdate.php index 711d7389b..ae8374ba4 100644 --- a/src/Operation/FindOneAndUpdate.php +++ b/src/Operation/FindOneAndUpdate.php @@ -41,8 +41,7 @@ class FindOneAndUpdate implements Executable, Explainable public const RETURN_DOCUMENT_BEFORE = 1; public const RETURN_DOCUMENT_AFTER = 2; - /** @var FindAndModify */ - private $findAndModify; + private FindAndModify $findAndModify; /** * Constructs a findAndModify command for updating a document. @@ -147,7 +146,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $this->findAndModify = new FindAndModify( $databaseName, $collectionName, - ['query' => $filter, 'update' => $update] + $options + ['query' => $filter, 'update' => $update] + $options, ); } diff --git a/src/Operation/InsertMany.php b/src/Operation/InsertMany.php index 8fe782c29..db9bd36f1 100644 --- a/src/Operation/InsertMany.php +++ b/src/Operation/InsertMany.php @@ -39,17 +39,14 @@ */ class InsertMany implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var object[]|array[] */ - private $documents; + private array $documents; - /** @var array */ - private $options; + private array $options; /** * Constructs an insert command. diff --git a/src/Operation/InsertOne.php b/src/Operation/InsertOne.php index 727bb503c..1b93b4fc5 100644 --- a/src/Operation/InsertOne.php +++ b/src/Operation/InsertOne.php @@ -37,17 +37,14 @@ */ class InsertOne implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $document; - /** @var array */ - private $options; + private array $options; /** * Constructs an insert command. diff --git a/src/Operation/ListCollectionNames.php b/src/Operation/ListCollectionNames.php index ebfa5977b..064e39765 100644 --- a/src/Operation/ListCollectionNames.php +++ b/src/Operation/ListCollectionNames.php @@ -32,8 +32,7 @@ */ class ListCollectionNames implements Executable { - /** @var ListCollectionsCommand */ - private $listCollections; + private ListCollectionsCommand $listCollections; /** * Constructs a listCollections command. @@ -76,9 +75,7 @@ public function execute(Server $server): Iterator { return new CallbackIterator( $this->listCollections->execute($server), - function (array $collectionInfo) { - return $collectionInfo['name']; - } + fn (array $collectionInfo): string => (string) $collectionInfo['name'] ); } } diff --git a/src/Operation/ListCollections.php b/src/Operation/ListCollections.php index a46968983..36d0bc446 100644 --- a/src/Operation/ListCollections.php +++ b/src/Operation/ListCollections.php @@ -32,11 +32,9 @@ */ class ListCollections implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var ListCollectionsCommand */ - private $listCollections; + private ListCollectionsCommand $listCollections; /** * Constructs a listCollections command. diff --git a/src/Operation/ListDatabaseNames.php b/src/Operation/ListDatabaseNames.php index db2a468cd..7b6a529b4 100644 --- a/src/Operation/ListDatabaseNames.php +++ b/src/Operation/ListDatabaseNames.php @@ -35,8 +35,7 @@ */ class ListDatabaseNames implements Executable { - /** @var ListDatabasesCommand */ - private $listDatabases; + private ListDatabasesCommand $listDatabases; /** * Constructs a listDatabases command. diff --git a/src/Operation/ListDatabases.php b/src/Operation/ListDatabases.php index 412538c16..ee90cca65 100644 --- a/src/Operation/ListDatabases.php +++ b/src/Operation/ListDatabases.php @@ -33,8 +33,7 @@ */ class ListDatabases implements Executable { - /** @var ListDatabasesCommand */ - private $listDatabases; + private ListDatabasesCommand $listDatabases; /** * Constructs a listDatabases command. diff --git a/src/Operation/ListIndexes.php b/src/Operation/ListIndexes.php index 1c2e29be0..041cc7c44 100644 --- a/src/Operation/ListIndexes.php +++ b/src/Operation/ListIndexes.php @@ -41,14 +41,11 @@ class ListIndexes implements Executable private const ERROR_CODE_DATABASE_NOT_FOUND = 60; private const ERROR_CODE_NAMESPACE_NOT_FOUND = 26; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $options; + private array $options; /** * Constructs a listIndexes command. diff --git a/src/Operation/MapReduce.php b/src/Operation/MapReduce.php index b08b2ebb9..364ea52e2 100644 --- a/src/Operation/MapReduce.php +++ b/src/Operation/MapReduce.php @@ -55,23 +55,18 @@ */ class MapReduce implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var JavascriptInterface */ - private $map; + private JavascriptInterface $map; - /** @var JavascriptInterface */ - private $reduce; + private JavascriptInterface $reduce; /** @var array|object|string */ private $out; - /** @var array */ - private $options; + private array $options; /** * Constructs a mapReduce command. @@ -366,9 +361,7 @@ private function createGetIteratorCallable(stdClass $result, Server $server): ca if (isset($result->results) && is_array($result->results)) { $results = $result->results; - return function () use ($results) { - return new ArrayIterator($results); - }; + return fn () => new ArrayIterator($results); } if (isset($result->result) && (is_string($result->result) || is_object($result->result))) { @@ -378,9 +371,7 @@ private function createGetIteratorCallable(stdClass $result, Server $server): ca ? new Find($this->databaseName, $result->result, [], $options) : new Find($result->result->db, $result->result->collection, [], $options); - return function () use ($find, $server) { - return $find->execute($server); - }; + return fn () => $find->execute($server); } throw new UnexpectedValueException('mapReduce command did not return inline results or an output collection'); diff --git a/src/Operation/ModifyCollection.php b/src/Operation/ModifyCollection.php index 61b5aafe6..a10bce5e8 100644 --- a/src/Operation/ModifyCollection.php +++ b/src/Operation/ModifyCollection.php @@ -35,17 +35,13 @@ */ class ModifyCollection implements Executable { - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var array */ - private $collectionOptions; + private array $collectionOptions; - /** @var array */ - private $options; + private array $options; /** * Constructs a collMod command. diff --git a/src/Operation/RenameCollection.php b/src/Operation/RenameCollection.php index 5ab7a6f20..5be7d4dff 100644 --- a/src/Operation/RenameCollection.php +++ b/src/Operation/RenameCollection.php @@ -38,14 +38,11 @@ */ class RenameCollection implements Executable { - /** @var string */ - private $fromNamespace; + private string $fromNamespace; - /** @var string */ - private $toNamespace; + private string $toNamespace; - /** @var array */ - private $options; + private array $options; /** * Constructs a renameCollection command. diff --git a/src/Operation/ReplaceOne.php b/src/Operation/ReplaceOne.php index 7b09f7985..c56d9c94d 100644 --- a/src/Operation/ReplaceOne.php +++ b/src/Operation/ReplaceOne.php @@ -35,8 +35,7 @@ */ class ReplaceOne implements Executable { - /** @var Update */ - private $update; + private Update $update; /** * Constructs an update command. @@ -102,7 +101,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $collectionName, $filter, $replacement, - ['multi' => false] + $options + ['multi' => false] + $options, ); } diff --git a/src/Operation/Update.php b/src/Operation/Update.php index 84e8a45c9..a026ec7e4 100644 --- a/src/Operation/Update.php +++ b/src/Operation/Update.php @@ -49,11 +49,9 @@ class Update implements Executable, Explainable { private const WIRE_VERSION_FOR_HINT = 8; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var string */ - private $collectionName; + private string $collectionName; /** @var array|object */ private $filter; @@ -61,8 +59,7 @@ class Update implements Executable, Explainable /** @var array|object */ private $update; - /** @var array */ - private $options; + private array $options; /** * Constructs a update command. diff --git a/src/Operation/UpdateMany.php b/src/Operation/UpdateMany.php index b4c0062cd..d836a7c83 100644 --- a/src/Operation/UpdateMany.php +++ b/src/Operation/UpdateMany.php @@ -36,8 +36,7 @@ */ class UpdateMany implements Executable, Explainable { - /** @var Update */ - private $update; + private Update $update; /** * Constructs an update command. @@ -97,7 +96,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $collectionName, $filter, $update, - ['multi' => true] + $options + ['multi' => true] + $options, ); } diff --git a/src/Operation/UpdateOne.php b/src/Operation/UpdateOne.php index 581acea35..ff0c53f7a 100644 --- a/src/Operation/UpdateOne.php +++ b/src/Operation/UpdateOne.php @@ -36,8 +36,7 @@ */ class UpdateOne implements Executable, Explainable { - /** @var Update */ - private $update; + private Update $update; /** * Constructs an update command. @@ -97,7 +96,7 @@ public function __construct(string $databaseName, string $collectionName, $filte $collectionName, $filter, $update, - ['multi' => false] + $options + ['multi' => false] + $options, ); } diff --git a/src/Operation/Watch.php b/src/Operation/Watch.php index 9eaa7f246..6d0418c0c 100644 --- a/src/Operation/Watch.php +++ b/src/Operation/Watch.php @@ -70,8 +70,7 @@ class Watch implements Executable, /* @internal */ CommandSubscriber private const WIRE_VERSION_FOR_START_AT_OPERATION_TIME = 7; - /** @var Aggregate */ - private $aggregate; + private Aggregate $aggregate; /** @var array */ private $aggregateOptions; @@ -79,29 +78,21 @@ class Watch implements Executable, /* @internal */ CommandSubscriber /** @var array */ private $changeStreamOptions; - /** @var string|null */ - private $collectionName; + private ?string $collectionName = null; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var integer */ - private $firstBatchSize; + private int $firstBatchSize; - /** @var boolean */ - private $hasResumed = false; + private bool $hasResumed = false; - /** @var Manager */ - private $manager; + private Manager $manager; - /** @var TimestampInterface */ - private $operationTime; + private ?TimestampInterface $operationTime = null; - /** @var array */ - private $pipeline; + private array $pipeline; - /** @var object|null */ - private $postBatchResumeToken; + private ?object $postBatchResumeToken = null; /** * Constructs an aggregate command for creating a change stream. @@ -325,9 +316,7 @@ public function execute(Server $server) { return new ChangeStream( $this->createChangeStreamIterator($server), - function ($resumeToken, $hasAdvanced): ChangeStreamIterator { - return $this->resume($resumeToken, $hasAdvanced); - } + fn ($resumeToken, $hasAdvanced): ChangeStreamIterator => $this->resume($resumeToken, $hasAdvanced) ); } @@ -353,7 +342,7 @@ private function createChangeStreamIterator(Server $server): ChangeStreamIterato $this->executeAggregate($server), $this->firstBatchSize, $this->getInitialResumeToken(), - $this->postBatchResumeToken + $this->postBatchResumeToken, ); } diff --git a/src/Operation/WithTransaction.php b/src/Operation/WithTransaction.php index f6c1057fb..de5644073 100644 --- a/src/Operation/WithTransaction.php +++ b/src/Operation/WithTransaction.php @@ -16,8 +16,7 @@ class WithTransaction /** @var callable */ private $callback; - /** @var array */ - private $transactionOptions; + private array $transactionOptions; /** * @see Session::startTransaction for supported transaction options diff --git a/src/UpdateResult.php b/src/UpdateResult.php index 8c2284ad5..76f042ae1 100644 --- a/src/UpdateResult.php +++ b/src/UpdateResult.php @@ -25,11 +25,9 @@ */ class UpdateResult { - /** @var WriteResult */ - private $writeResult; + private WriteResult $writeResult; - /** @var boolean */ - private $isAcknowledged; + private bool $isAcknowledged; public function __construct(WriteResult $writeResult) { diff --git a/tests/ClientFunctionalTest.php b/tests/ClientFunctionalTest.php index 6535c66da..e2be0f8ff 100644 --- a/tests/ClientFunctionalTest.php +++ b/tests/ClientFunctionalTest.php @@ -18,8 +18,7 @@ */ class ClientFunctionalTest extends FunctionalTestCase { - /** @var Client */ - private $client; + private Client $client; public function setUp(): void { diff --git a/tests/Codec/CodecLibraryTest.php b/tests/Codec/CodecLibraryTest.php index 489e1d1d8..f03c57a89 100644 --- a/tests/Codec/CodecLibraryTest.php +++ b/tests/Codec/CodecLibraryTest.php @@ -126,7 +126,7 @@ public function encode($value) { return 'encoded'; } - } + }, ); } diff --git a/tests/Collection/CollectionFunctionalTest.php b/tests/Collection/CollectionFunctionalTest.php index eeb4af16c..dd62133f8 100644 --- a/tests/Collection/CollectionFunctionalTest.php +++ b/tests/Collection/CollectionFunctionalTest.php @@ -25,6 +25,8 @@ use function usort; use function version_compare; +use const JSON_THROW_ON_ERROR; + /** * Functional tests for the Collection class. */ @@ -111,7 +113,7 @@ public function testAggregateWithinTransaction(): void $cursor = $this->collection->aggregate( [['$match' => ['_id' => ['$lt' => 3]]]], - ['session' => $session] + ['session' => $session], ); $expected = [ @@ -139,7 +141,7 @@ function (): void { 'sparse' => true, 'unique' => true, 'writeConcern' => new WriteConcern(1), - ] + ], ); }, function (array $event): void { @@ -149,7 +151,7 @@ function (array $event): void { $this->assertObjectHasAttribute('writeConcern', $command); $this->assertObjectHasAttribute('sparse', $command->indexes[0]); $this->assertObjectHasAttribute('unique', $command->indexes[0]); - } + }, ); } @@ -182,8 +184,8 @@ public function testDistinctWithTypeMap(array $typeMap, array $expectedDocuments return 1; } - $a = json_encode($a); - $b = json_encode($b); + $a = json_encode($a, JSON_THROW_ON_ERROR); + $b = json_encode($b, JSON_THROW_ON_ERROR); } return $a < $b ? -1 : 1; @@ -291,7 +293,7 @@ public function testFindWithinTransaction(): void $cursor = $this->collection->find( ['_id' => ['$lt' => 3]], - ['session' => $session] + ['session' => $session], ); $expected = [ @@ -438,7 +440,7 @@ public function collectionMethodClosures() function ($collection, $session, $options = []): void { $collection->aggregate( [['$match' => ['_id' => ['$lt' => 3]]]], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'r', ], @@ -461,7 +463,7 @@ function ($collection, $session, $options = []): void { function ($collection, $session, $options = []): void { $collection->bulkWrite( [['insertOne' => [['test' => 'foo']]]], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -481,7 +483,7 @@ function($collection, $session, $options = []) { function ($collection, $session, $options = []): void { $collection->countDocuments( [], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'r', ], @@ -501,7 +503,7 @@ function($collection, $session, $options = []) { function ($collection, $session, $options = []): void { $collection->deleteMany( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -510,7 +512,7 @@ function ($collection, $session, $options = []): void { function ($collection, $session, $options = []): void { $collection->deleteOne( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -520,7 +522,7 @@ function ($collection, $session, $options = []): void { $collection->distinct( '_id', [], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'r', ], @@ -569,7 +571,7 @@ function($collection, $session, $options = []) { function ($collection, $session, $options = []): void { $collection->find( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'r', ], @@ -578,7 +580,7 @@ function ($collection, $session, $options = []): void { function ($collection, $session, $options = []): void { $collection->findOne( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'r', ], @@ -587,7 +589,7 @@ function ($collection, $session, $options = []): void { function ($collection, $session, $options = []): void { $collection->findOneAndDelete( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -597,7 +599,7 @@ function ($collection, $session, $options = []): void { $collection->findOneAndReplace( ['test' => 'foo'], [], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -607,7 +609,7 @@ function ($collection, $session, $options = []): void { $collection->findOneAndUpdate( ['test' => 'foo'], ['$set' => ['updated' => 1]], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -619,7 +621,7 @@ function ($collection, $session, $options = []): void { ['test' => 'foo'], ['test' => 'bar'], ], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -628,7 +630,7 @@ function ($collection, $session, $options = []): void { function ($collection, $session, $options = []): void { $collection->insertOne( ['test' => 'foo'], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -661,7 +663,7 @@ function ($collection, $session, $options = []): void { $collection->replaceOne( ['test' => 'foo'], [], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -671,7 +673,7 @@ function ($collection, $session, $options = []): void { $collection->updateMany( ['test' => 'foo'], ['$set' => ['updated' => 1]], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -681,7 +683,7 @@ function ($collection, $session, $options = []): void { $collection->updateOne( ['test' => 'foo'], ['$set' => ['updated' => 1]], - ['session' => $session] + $options + ['session' => $session] + $options, ); }, 'w', ], @@ -703,9 +705,7 @@ public function collectionReadMethodClosures(): array { return array_filter( $this->collectionMethodClosures(), - function ($rw) { - return str_contains($rw[1], 'r'); - } + fn ($rw) => str_contains($rw[1], 'r') ); } @@ -713,9 +713,7 @@ public function collectionWriteMethodClosures(): array { return array_filter( $this->collectionMethodClosures(), - function ($rw) { - return str_contains($rw[1], 'w'); - } + fn ($rw) => str_contains($rw[1], 'w') ); } @@ -741,7 +739,7 @@ function () use ($method, $collection, $session): void { function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Collection/CrudSpecFunctionalTest.php b/tests/Collection/CrudSpecFunctionalTest.php index 994ec915b..5ab551b81 100644 --- a/tests/Collection/CrudSpecFunctionalTest.php +++ b/tests/Collection/CrudSpecFunctionalTest.php @@ -25,6 +25,8 @@ use function str_replace; use function strtolower; +use const JSON_THROW_ON_ERROR; + /** * CRUD spec functional tests. * @@ -39,8 +41,7 @@ class CrudSpecFunctionalTest extends FunctionalTestCase public const SERVERLESS_FORBID = 'forbid'; public const SERVERLESS_REQUIRE = 'require'; - /** @var Collection */ - private $expectedCollection; + private Collection $expectedCollection; public function setUp(): void { @@ -87,7 +88,7 @@ public function provideSpecificationTests() $testArgs = []; foreach (glob(__DIR__ . '/spec-tests/*/*.json') as $filename) { - $json = json_decode(file_get_contents($filename), true); + $json = json_decode(file_get_contents($filename), true, 512, JSON_THROW_ON_ERROR); foreach ($json['tests'] as $test) { $name = str_replace(' ', '_', $test['description']); @@ -157,13 +158,13 @@ private function executeOperation(array $operation) case 'aggregate': return $this->collection->aggregate( $operation['arguments']['pipeline'], - array_diff_key($operation['arguments'], ['pipeline' => 1]) + array_diff_key($operation['arguments'], ['pipeline' => 1]), ); case 'bulkWrite': return $this->collection->bulkWrite( array_map([$this, 'prepareBulkWriteRequest'], $operation['arguments']['requests']), - $operation['arguments']['options'] ?? [] + $operation['arguments']['options'] ?? [], ); case 'count': @@ -189,7 +190,7 @@ private function executeOperation(array $operation) return $this->collection->distinct( $operation['arguments']['fieldName'], $operation['arguments']['filter'] ?? [], - array_diff_key($operation['arguments'], ['fieldName' => 1, 'filter' => 1]) + array_diff_key($operation['arguments'], ['fieldName' => 1, 'filter' => 1]), ); case 'findOneAndReplace': @@ -218,13 +219,13 @@ private function executeOperation(array $operation) case 'insertMany': return $this->collection->insertMany( $operation['arguments']['documents'], - $operation['arguments']['options'] ?? [] + $operation['arguments']['options'] ?? [], ); case 'insertOne': return $this->collection->insertOne( $operation['arguments']['document'], - array_diff_key($operation['arguments'], ['document' => 1]) + array_diff_key($operation['arguments'], ['document' => 1]), ); default: @@ -337,7 +338,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR if (isset($expectedResult['insertedIds'])) { $this->assertSameDocument( ['insertedIds' => $expectedResult['insertedIds']], - ['insertedIds' => $actualResult->getInsertedIds()] + ['insertedIds' => $actualResult->getInsertedIds()], ); } @@ -356,7 +357,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR if (isset($expectedResult['upsertedIds'])) { $this->assertSameDocument( ['upsertedIds' => $expectedResult['upsertedIds']], - ['upsertedIds' => $actualResult->getUpsertedIds()] + ['upsertedIds' => $actualResult->getUpsertedIds()], ); } @@ -371,7 +372,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR case 'distinct': $this->assertSameDocument( ['values' => $expectedResult], - ['values' => $actualResult] + ['values' => $actualResult], ); break; @@ -395,7 +396,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR case 'findOneAndUpdate': $this->assertSameDocument( ['result' => $expectedResult], - ['result' => $actualResult] + ['result' => $actualResult], ); break; @@ -410,7 +411,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR if (isset($expectedResult['insertedIds'])) { $this->assertSameDocument( ['insertedIds' => $expectedResult['insertedIds']], - ['insertedIds' => $actualResult->getInsertedIds()] + ['insertedIds' => $actualResult->getInsertedIds()], ); } @@ -427,7 +428,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR if (isset($expectedResult['insertedId'])) { $this->assertSameDocument( ['insertedId' => $expectedResult['insertedId']], - ['insertedId' => $actualResult->getInsertedId()] + ['insertedId' => $actualResult->getInsertedId()], ); } @@ -454,7 +455,7 @@ private function executeAssertResult(array $operation, $expectedResult, $actualR if (array_key_exists('upsertedId', $expectedResult)) { $this->assertSameDocument( ['upsertedId' => $expectedResult['upsertedId']], - ['upsertedId' => $actualResult->getUpsertedId()] + ['upsertedId' => $actualResult->getUpsertedId()], ); } diff --git a/tests/Collection/FunctionalTestCase.php b/tests/Collection/FunctionalTestCase.php index d299d18fa..9e5341501 100644 --- a/tests/Collection/FunctionalTestCase.php +++ b/tests/Collection/FunctionalTestCase.php @@ -10,8 +10,7 @@ */ abstract class FunctionalTestCase extends BaseFunctionalTestCase { - /** @var Collection */ - protected $collection; + protected Collection $collection; public function setUp(): void { diff --git a/tests/CommandObserver.php b/tests/CommandObserver.php index 2f5165138..89fc79de7 100644 --- a/tests/CommandObserver.php +++ b/tests/CommandObserver.php @@ -17,8 +17,7 @@ */ class CommandObserver implements CommandSubscriber { - /** @var array */ - private $commands = []; + private array $commands = []; public function observe(callable $execution, callable $commandCallback): void { diff --git a/tests/Comparator/Int64Comparator.php b/tests/Comparator/Int64Comparator.php index c985e0c03..c786aa919 100644 --- a/tests/Comparator/Int64Comparator.php +++ b/tests/Comparator/Int64Comparator.php @@ -33,8 +33,8 @@ public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = f sprintf( 'Failed asserting that %s matches expected %s.', $this->exporter->export($actual), - $this->exporter->export($expected) - ) + $this->exporter->export($expected), + ), ); } diff --git a/tests/Comparator/Int64ComparatorTest.php b/tests/Comparator/Int64ComparatorTest.php index 9a887acd3..9e85964c2 100644 --- a/tests/Comparator/Int64ComparatorTest.php +++ b/tests/Comparator/Int64ComparatorTest.php @@ -108,48 +108,48 @@ public function testMatchingAssertions($expected, $actual): void public static function provideMatchingAssertions(): Generator { yield 'Expected Int64, Actual Int64' => [ - 'expected' => new Int64(8589934592), - 'actual' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), + 'actual' => new Int64(8_589_934_592), ]; yield 'Expected Int64, Actual int' => [ - 'expected' => new Int64(8589934592), - 'actual' => 8589934592, + 'expected' => new Int64(8_589_934_592), + 'actual' => 8_589_934_592, ]; yield 'Expected Int64, Actual int string' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => '8589934592', ]; yield 'Expected Int64, Actual float' => [ - 'expected' => new Int64(8589934592), - 'actual' => 8589934592.0, + 'expected' => new Int64(8_589_934_592), + 'actual' => 8_589_934_592.0, ]; yield 'Expected Int64, Actual float string' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => '8589934592.0', ]; yield 'Expected int, Actual Int64' => [ - 'expected' => 8589934592, - 'actual' => new Int64(8589934592), + 'expected' => 8_589_934_592, + 'actual' => new Int64(8_589_934_592), ]; yield 'Expected int string, Actual Int64' => [ 'expected' => '8589934592', - 'actual' => new Int64(8589934592), + 'actual' => new Int64(8_589_934_592), ]; yield 'Expected float, Actual Int64' => [ - 'expected' => 8589934592.0, - 'actual' => new Int64(8589934592), + 'expected' => 8_589_934_592.0, + 'actual' => new Int64(8_589_934_592), ]; yield 'Expected float string, Actual Int64' => [ 'expected' => '8589934592.0', - 'actual' => new Int64(8589934592), + 'actual' => new Int64(8_589_934_592), ]; } @@ -164,32 +164,32 @@ public function testFailingAssertions($expected, $actual): void public static function provideFailingValues(): Generator { yield 'Expected Int64, Actual Int64' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => new Int64(456), ]; yield 'Expected Int64, Actual int' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => 456, ]; yield 'Expected Int64, Actual int string' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => '456', ]; yield 'Expected Int64, Actual float' => [ - 'expected' => new Int64(8589934592), - 'actual' => 8589934592.1, + 'expected' => new Int64(8_589_934_592), + 'actual' => 8_589_934_592.1, ]; yield 'Expected Int64, Actual float string' => [ - 'expected' => new Int64(8589934592), + 'expected' => new Int64(8_589_934_592), 'actual' => '8589934592.1', ]; yield 'Expected int, Actual Int64' => [ - 'expected' => 8589934592, + 'expected' => 8_589_934_592, 'actual' => new Int64(456), ]; @@ -199,7 +199,7 @@ public static function provideFailingValues(): Generator ]; yield 'Expected float, Actual Int64' => [ - 'expected' => 8589934592.1, + 'expected' => 8_589_934_592.1, 'actual' => new Int64(456), ]; diff --git a/tests/Database/CollectionManagementFunctionalTest.php b/tests/Database/CollectionManagementFunctionalTest.php index 4cb5c6107..485bcd8e5 100644 --- a/tests/Database/CollectionManagementFunctionalTest.php +++ b/tests/Database/CollectionManagementFunctionalTest.php @@ -26,7 +26,7 @@ public function testCreateCollection(): void $cappedCollectionOptions = [ 'capped' => true, 'max' => 100, - 'size' => 1048576, + 'size' => 1_048_576, ]; $commandResult = $this->database->createCollection($cappedCollectionName, $cappedCollectionOptions); @@ -34,7 +34,7 @@ public function testCreateCollection(): void $this->assertCollectionExists($cappedCollectionName, null, function (CollectionInfo $info) use ($that): void { $that->assertTrue($info->isCapped()); $that->assertEquals(100, $info->getCappedMax()); - $that->assertEquals(1048576, $info->getCappedSize()); + $that->assertEquals(1_048_576, $info->getCappedSize()); }); } diff --git a/tests/Database/DatabaseFunctionalTest.php b/tests/Database/DatabaseFunctionalTest.php index 0022df7a1..c5854e882 100644 --- a/tests/Database/DatabaseFunctionalTest.php +++ b/tests/Database/DatabaseFunctionalTest.php @@ -185,7 +185,7 @@ public function testModifyCollection(): void $commandResult = $this->database->modifyCollection( $this->getCollectionName(), ['index' => ['keyPattern' => ['lastAccess' => 1], 'expireAfterSeconds' => 1000]], - ['typeMap' => ['root' => 'array', 'document' => 'array']] + ['typeMap' => ['root' => 'array', 'document' => 'array']], ); $this->assertCommandSucceeded($commandResult); @@ -222,7 +222,7 @@ public function testRenameCollectionToSameDatabase(): void $this->getCollectionName(), $toCollectionName, null, - ['dropTarget' => true] + ['dropTarget' => true], ); $this->assertCommandSucceeded($commandResult); $this->assertCollectionDoesNotExist($this->getCollectionName()); @@ -258,7 +258,7 @@ public function testRenameCollectionToDifferentDatabase(): void $commandResult = $this->database->renameCollection( $this->getCollectionName(), $toCollectionName, - $toDatabaseName + $toDatabaseName, ); $this->assertCommandSucceeded($commandResult); $this->assertCollectionDoesNotExist($this->getCollectionName()); diff --git a/tests/Database/FunctionalTestCase.php b/tests/Database/FunctionalTestCase.php index 5e0906731..4b6f62d8e 100644 --- a/tests/Database/FunctionalTestCase.php +++ b/tests/Database/FunctionalTestCase.php @@ -10,8 +10,7 @@ */ abstract class FunctionalTestCase extends BaseFunctionalTestCase { - /** @var Database */ - protected $database; + protected Database $database; public function setUp(): void { diff --git a/tests/DocumentationExamplesTest.php b/tests/DocumentationExamplesTest.php index a49204c8b..c44038bf4 100644 --- a/tests/DocumentationExamplesTest.php +++ b/tests/DocumentationExamplesTest.php @@ -597,7 +597,7 @@ public function testExample_42_50(): void // Start Example 44 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['item' => 1, 'status' => 1]] + ['projection' => ['item' => 1, 'status' => 1]], ); // End Example 44 @@ -616,7 +616,7 @@ public function testExample_42_50(): void // Start Example 45 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['item' => 1, 'status' => 1, '_id' => 0]] + ['projection' => ['item' => 1, 'status' => 1, '_id' => 0]], ); // End Example 45 @@ -635,7 +635,7 @@ public function testExample_42_50(): void // Start Example 46 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['status' => 0, 'instock' => 0]] + ['projection' => ['status' => 0, 'instock' => 0]], ); // End Example 46 @@ -654,7 +654,7 @@ public function testExample_42_50(): void // Start Example 47 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['item' => 1, 'status' => 1, 'size.uom' => 1]] + ['projection' => ['item' => 1, 'status' => 1, 'size.uom' => 1]], ); // End Example 47 @@ -674,7 +674,7 @@ public function testExample_42_50(): void // Start Example 48 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['size.uom' => 0]] + ['projection' => ['size.uom' => 0]], ); // End Example 48 @@ -693,7 +693,7 @@ public function testExample_42_50(): void // Start Example 49 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['item' => 1, 'status' => 1, 'instock.qty' => 1]] + ['projection' => ['item' => 1, 'status' => 1, 'instock.qty' => 1]], ); // End Example 49 @@ -714,7 +714,7 @@ public function testExample_42_50(): void // Start Example 50 $cursor = $db->inventory->find( ['status' => 'A'], - ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]] + ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]], ); // End Example 50 @@ -813,7 +813,7 @@ public function testExample_51_54(): void [ '$set' => ['size.uom' => 'cm', 'status' => 'P'], '$currentDate' => ['lastModified' => true], - ] + ], ); // End Example 52 @@ -833,7 +833,7 @@ public function testExample_51_54(): void [ '$set' => ['size.uom' => 'cm', 'status' => 'P'], '$currentDate' => ['lastModified' => true], - ] + ], ); // End Example 53 @@ -856,7 +856,7 @@ public function testExample_51_54(): void ['warehouse' => 'A', 'qty' => 60], ['warehouse' => 'B', 'qty' => 40], ], - ] + ], ); // End Example 54 @@ -1205,7 +1205,7 @@ public function testIndex_example_2(): void // Start Index Example 2 $indexName = $db->restaurants->createIndex( ['cuisine' => 1, 'name' => 1], - ['partialFilterExpression' => ['rating' => ['$gt' => 5]]] + ['partialFilterExpression' => ['rating' => ['$gt' => 5]]], ); // End Index Example 2 @@ -1227,11 +1227,11 @@ private function updateEmployeeInfo1(\MongoDB\Client $client, \MongoDB\Driver\Se $client->hr->employees->updateOne( ['employee' => 3], ['$set' => ['status' => 'Inactive']], - ['session' => $session] + ['session' => $session], ); $client->reporting->events->insertOne( ['employee' => 3, 'status' => ['new' => 'Inactive', 'old' => 'Active']], - ['session' => $session] + ['session' => $session], ); } catch (\MongoDB\Driver\Exception\Exception $error) { echo "Caught exception during transaction, aborting.\n"; @@ -1412,11 +1412,11 @@ private function updateEmployeeInfo3(\MongoDB\Client $client, \MongoDB\Driver\Se $client->hr->employees->updateOne( ['employee' => 3], ['$set' => ['status' => 'Inactive']], - ['session' => $session] + ['session' => $session], ); $client->reporting->events->insertOne( ['employee' => 3, 'status' => ['new' => 'Inactive', 'old' => 'Active']], - ['session' => $session] + ['session' => $session], ); } catch (\MongoDB\Driver\Exception\Exception $error) { echo "Caught exception during transaction, aborting.\n"; @@ -1472,7 +1472,7 @@ public function testCausalConsistency(): void $client = static::createTestClient(); $items = $this->createCollection('test', 'items'); $items->insertOne( - ['sku' => '111', 'name' => 'Peanuts', 'start' => new UTCDateTime()] + ['sku' => '111', 'name' => 'Peanuts', 'start' => new UTCDateTime()], ); try { @@ -1492,11 +1492,11 @@ public function testCausalConsistency(): void [ 'readConcern' => new \MongoDB\Driver\ReadConcern(\MongoDB\Driver\ReadConcern::MAJORITY), 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000), - ] + ], )->items; $s1 = $client->startSession( - ['causalConsistency' => true] + ['causalConsistency' => true], ); $currentDate = new \MongoDB\BSON\UTCDateTime(); @@ -1504,11 +1504,11 @@ public function testCausalConsistency(): void $items->updateOne( ['sku' => '111', 'end' => ['$exists' => false]], ['$set' => ['end' => $currentDate]], - ['session' => $s1] + ['session' => $s1], ); $items->insertOne( ['sku' => '111-nuts', 'name' => 'Pecans', 'start' => $currentDate], - ['session' => $s1] + ['session' => $s1], ); // End Causal Consistency Example 1 // phpcs:enable @@ -1518,7 +1518,7 @@ public function testCausalConsistency(): void // phpcs:disable SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly // Start Causal Consistency Example 2 $s2 = $client->startSession( - ['causalConsistency' => true] + ['causalConsistency' => true], ); $s2->advanceClusterTime($s1->getClusterTime()); $s2->advanceOperationTime($s1->getOperationTime()); @@ -1529,12 +1529,12 @@ public function testCausalConsistency(): void 'readPreference' => new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::SECONDARY), 'readConcern' => new \MongoDB\Driver\ReadConcern(\MongoDB\Driver\ReadConcern::MAJORITY), 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000), - ] + ], )->items; $result = $items->find( ['end' => ['$exists' => false]], - ['session' => $s2] + ['session' => $s2], ); foreach ($result as $item) { var_dump($item); @@ -1590,7 +1590,7 @@ public function testSnapshotQueries(): void ['$match' => ['adoptable' => true]], ['$count' => 'adoptableCatsCount'], ], - ['session' => $session] + ['session' => $session], )->toArray()[0]->adoptableCatsCount; $adoptablePetsCount += $dogsCollection->aggregate( @@ -1598,7 +1598,7 @@ public function testSnapshotQueries(): void ['$match' => ['adoptable' => true]], ['$count' => 'adoptableDogsCount'], ], - ['session' => $session] + ['session' => $session], )->toArray()[0]->adoptableDogsCount; var_dump($adoptablePetsCount); @@ -1642,7 +1642,7 @@ public function testSnapshotQueries(): void ], ['$count' => 'totalDailySales'], ], - ['session' => $session] + ['session' => $session], )->toArray()[0]->totalDailySales; // End Snapshot Query Example 2 @@ -1691,9 +1691,7 @@ public function testVersionedApiMigration(): void $db = $client->selectDatabase($this->getDatabaseName()); // Start Versioned API Example 5 - $strtoutc = function (string $datetime) { - return new \MongoDB\BSON\UTCDateTime(new \DateTime($datetime)); - }; + $strtoutc = fn (string $datetime) => new \MongoDB\BSON\UTCDateTime(new \DateTime($datetime)); $db->sales->insertMany([ ['_id' => 1, 'item' => 'abc', 'price' => 10, 'quantity' => 2, 'date' => $strtoutc('2021-01-01T08:00:00Z')], @@ -1713,7 +1711,7 @@ public function testVersionedApiMigration(): void try { $count = $db->sales->count(); } catch (\MongoDB\Driver\Exception\CommandException $e) { - echo json_encode($e->getResultDocument()); + echo json_encode($e->getResultDocument(), JSON_THROW_ON_ERROR); // { "ok": 0, "errmsg": "Provided apiStrict:true, but the command count is not in API Version 1", "code": 323, "codeName": "APIStrictError" } } @@ -1762,7 +1760,7 @@ public function testWithTransactionExample(): void 'foo', [ 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000), - ] + ], )->insertOne(['abc' => 0]); $client->selectCollection( @@ -1770,7 +1768,7 @@ public function testWithTransactionExample(): void 'bar', [ 'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000), - ] + ], )->insertOne(['xyz' => 0]); // Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions. diff --git a/tests/ExamplesTest.php b/tests/ExamplesTest.php index 65c2741f1..b3eda5fe6 100644 --- a/tests/ExamplesTest.php +++ b/tests/ExamplesTest.php @@ -486,7 +486,7 @@ private function setUpKeyVaultIndex(): void [ 'unique' => true, 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], - ] + ], ); } } diff --git a/tests/FunctionalTestCase.php b/tests/FunctionalTestCase.php index cc4df8ef9..0b603ed23 100644 --- a/tests/FunctionalTestCase.php +++ b/tests/FunctionalTestCase.php @@ -52,11 +52,10 @@ abstract class FunctionalTestCase extends TestCase { - /** @var Manager */ - protected $manager; + protected Manager $manager; /** @var array */ - private $configuredFailPoints = []; + private array $configuredFailPoints = []; /** @var array{int,{Collection,array}} */ private $collectionsToCleanup = []; @@ -85,7 +84,7 @@ public static function createTestClient(?string $uri = null, array $options = [] return new Client( $uri ?? static::getUri(), static::appendAuthenticationOptions($options), - static::appendServerApiOption($driverOptions) + static::appendServerApiOption($driverOptions), ); } @@ -94,7 +93,7 @@ public static function createTestManager(?string $uri = null, array $options = [ return new Manager( $uri ?? static::getUri(), static::appendAuthenticationOptions($options), - static::appendServerApiOption($driverOptions) + static::appendServerApiOption($driverOptions), ); } @@ -330,7 +329,7 @@ protected function getFeatureCompatibilityVersion(?ReadPreference $readPreferenc $cursor = $this->manager->executeCommand( 'admin', new Command(['getParameter' => 1, 'featureCompatibilityVersion' => 1]), - $readPreference ?: new ReadPreference(ReadPreference::PRIMARY) + $readPreference ?: new ReadPreference(ReadPreference::PRIMARY), ); $cursor->setTypeMap(['root' => 'array', 'document' => 'array']); @@ -353,7 +352,7 @@ protected function getServerVersion(?ReadPreference $readPreference = null) $buildInfo = $this->manager->executeCommand( $this->getDatabaseName(), new Command(['buildInfo' => 1]), - $readPreference ?: new ReadPreference(ReadPreference::PRIMARY) + $readPreference ?: new ReadPreference(ReadPreference::PRIMARY), )->toArray()[0]; if (isset($buildInfo->version) && is_string($buildInfo->version)) { @@ -368,7 +367,7 @@ protected function getServerStorageEngine(?ReadPreference $readPreference = null $cursor = $this->manager->executeCommand( $this->getDatabaseName(), new Command(['serverStatus' => 1]), - $readPreference ?: new ReadPreference(ReadPreference::PRIMARY) + $readPreference ?: new ReadPreference(ReadPreference::PRIMARY), ); $result = current($cursor->toArray()); @@ -389,7 +388,7 @@ protected function isApiVersionRequired(): bool try { $cursor = $this->manager->executeCommand( 'admin', - new Command(['getParameter' => 1, 'requireApiVersion' => 1]) + new Command(['getParameter' => 1, 'requireApiVersion' => 1]), ); $document = current($cursor->toArray()); @@ -455,7 +454,7 @@ protected function isShardedClusterUsingReplicasets() $cursor = $this->getPrimaryServer()->executeQuery( 'config.shards', - new Query([], ['limit' => 1]) + new Query([], ['limit' => 1]), ); $cursor->setTypeMap(['root' => 'array', 'document' => 'array']); @@ -726,7 +725,7 @@ private function isFailCommandEnabled(): bool try { $cursor = $this->manager->executeCommand( 'admin', - new Command(['getParameter' => 1, 'enableTestCommands' => 1]) + new Command(['getParameter' => 1, 'enableTestCommands' => 1]), ); $document = current($cursor->toArray()); diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index c07f81535..428028d0c 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -132,10 +132,10 @@ public function provideDocumentCasts(): array // phpcs:disable Squiz.Functions.MultiLineFunctionDeclaration // phpcs:disable Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore return [ - 'array' => [function ($value) { return $value; }], - 'object' => [function ($value) { return (object) $value; }], - 'Serializable' => [function ($value) { return new BSONDocument($value); }], - 'Document' => [function ($value) { return Document::fromPHP($value); }], + 'array' => [fn ($value) => $value], + 'object' => [fn ($value) => (object) $value], + 'Serializable' => [fn ($value) => new BSONDocument($value)], + 'Document' => [fn ($value) => Document::fromPHP($value)], ]; // phpcs:enable } diff --git a/tests/GridFS/BucketFunctionalTest.php b/tests/GridFS/BucketFunctionalTest.php index 13f466475..9de4479ac 100644 --- a/tests/GridFS/BucketFunctionalTest.php +++ b/tests/GridFS/BucketFunctionalTest.php @@ -37,7 +37,6 @@ use const PHP_EOL; use const PHP_OS; -use const PHP_VERSION_ID; /** * Functional tests for the Bucket class. @@ -156,7 +155,7 @@ public function testDownloadingFileWithUnexpectedChunkIndex(): void $this->chunksCollection->updateOne( ['files_id' => $id, 'n' => 0], - ['$set' => ['n' => 1]] + ['$set' => ['n' => 1]], ); $this->expectException(CorruptFileException::class); @@ -170,7 +169,7 @@ public function testDownloadingFileWithUnexpectedChunkSize(): void $this->chunksCollection->updateOne( ['files_id' => $id, 'n' => 0], - ['$set' => ['data' => new Binary('fooba')]] + ['$set' => ['data' => new Binary('fooba')]], ); $this->expectException(CorruptFileException::class); @@ -297,7 +296,7 @@ public function testFind(): void '_id' => 0, ], 'sort' => ['length' => -1], - ] + ], ); $expected = [ @@ -333,7 +332,7 @@ public function testFindOne(): void '_id' => 0, ], 'sort' => ['length' => -1], - ] + ], ); $this->assertInstanceOf(BSONDocument::class, $fileDocument); @@ -566,7 +565,7 @@ public function testRename(): void $fileDocument = $this->filesCollection->findOne( ['_id' => $id], - ['projection' => ['filename' => 1, '_id' => 0]] + ['projection' => ['filename' => 1, '_id' => 0]], ); $this->assertSameDocument(['filename' => 'b'], $fileDocument); @@ -580,7 +579,7 @@ public function testRenameShouldNotRequireFileToBeModified(): void $fileDocument = $this->filesCollection->findOne( ['_id' => $id], - ['projection' => ['filename' => 1, '_id' => 0]] + ['projection' => ['filename' => 1, '_id' => 0]], ); $this->assertSameDocument(['filename' => 'a'], $fileDocument); @@ -637,7 +636,7 @@ public function testUploadingAnEmptyFile(): void 'md5' => 1, '_id' => 0, ], - ] + ], ); $expected = [ @@ -654,7 +653,7 @@ public function testDisableMD5(): void $id = $this->bucket->uploadFromStream('filename', $this->createStream('data'), $options); $fileDocument = $this->filesCollection->findOne( - ['_id' => $id] + ['_id' => $id], ); $this->assertArrayNotHasKey('md5', $fileDocument); @@ -668,7 +667,7 @@ public function testDisableMD5OptionInConstructor(): void $id = $this->bucket->uploadFromStream('filename', $this->createStream('data')); $fileDocument = $this->filesCollection->findOne( - ['_id' => $id] + ['_id' => $id], ); $this->assertArrayNotHasKey('md5', $fileDocument); @@ -715,10 +714,6 @@ public function testDownloadToStreamByNameFails(): void public function testUploadFromStreamFails(): void { - if (PHP_VERSION_ID < 70400) { - $this->markTestSkipped('Test only works on PHP 7.4 and newer'); - } - UnusableStream::register(); $source = fopen('unusable://temp', 'w'); @@ -741,7 +736,7 @@ public function testDanglingOpenWritableStream(): void @exec( $command, $output, - $return + $return, ); $this->assertSame(0, $return); diff --git a/tests/GridFS/FunctionalTestCase.php b/tests/GridFS/FunctionalTestCase.php index c22143f20..1508fef68 100644 --- a/tests/GridFS/FunctionalTestCase.php +++ b/tests/GridFS/FunctionalTestCase.php @@ -17,14 +17,11 @@ */ abstract class FunctionalTestCase extends BaseFunctionalTestCase { - /** @var Bucket */ - protected $bucket; + protected Bucket $bucket; - /** @var Collection */ - protected $chunksCollection; + protected Collection $chunksCollection; - /** @var Collection */ - protected $filesCollection; + protected Collection $filesCollection; public function setUp(): void { diff --git a/tests/GridFS/ReadableStreamFunctionalTest.php b/tests/GridFS/ReadableStreamFunctionalTest.php index 95f21c840..7e30b8c93 100644 --- a/tests/GridFS/ReadableStreamFunctionalTest.php +++ b/tests/GridFS/ReadableStreamFunctionalTest.php @@ -16,8 +16,7 @@ */ class ReadableStreamFunctionalTest extends FunctionalTestCase { - /** @var CollectionWrapper */ - private $collectionWrapper; + private CollectionWrapper $collectionWrapper; public function setUp(): void { @@ -116,9 +115,7 @@ public function provideFilteredFileIdAndExpectedBytes() { return array_filter( $this->provideFileIdAndExpectedBytes(), - function (array $args) { - return $args[1] > 0; - } + fn (array $args) => $args[1] > 0 ); } @@ -161,7 +158,7 @@ public function testReadBytesWithUnexpectedChunkSize(): void { $this->chunksCollection->updateOne( ['files_id' => 'length-10', 'n' => 2], - ['$set' => ['data' => new Binary('i')]] + ['$set' => ['data' => new Binary('i')]], ); $fileDocument = $this->collectionWrapper->findFileById('length-10'); @@ -218,7 +215,7 @@ function () use ($stream, $offset, $length, $expectedBytes): void { }, function (array $event) use (&$commands): void { $commands[] = $event['started']->getCommandName(); - } + }, ); $this->assertSame(['find'], $commands); @@ -252,7 +249,7 @@ function () use ($stream, $offset, $length, $expectedBytes): void { }, function (array $event) use (&$commands): void { $commands[] = $event['started']->getCommandName(); - } + }, ); $this->assertSame([], $commands); @@ -284,7 +281,7 @@ function () use ($stream, $offset, $length, $expectedBytes): void { }, function (array $event) use (&$commands): void { $commands[] = $event['started']->getCommandName(); - } + }, ); $this->assertSame([], $commands); diff --git a/tests/GridFS/StreamWrapperFunctionalTest.php b/tests/GridFS/StreamWrapperFunctionalTest.php index 3c5e140bf..ebe6eb9ba 100644 --- a/tests/GridFS/StreamWrapperFunctionalTest.php +++ b/tests/GridFS/StreamWrapperFunctionalTest.php @@ -96,10 +96,10 @@ public function testReadableStreamStat(): void $this->assertSame(0100444, $stat['mode']); $this->assertSame(10, $stat[7]); $this->assertSame(10, $stat['size']); - $this->assertSame(1484202200, $stat[9]); - $this->assertSame(1484202200, $stat['mtime']); - $this->assertSame(1484202200, $stat[10]); - $this->assertSame(1484202200, $stat['ctime']); + $this->assertSame(1_484_202_200, $stat[9]); + $this->assertSame(1_484_202_200, $stat['mtime']); + $this->assertSame(1_484_202_200, $stat[10]); + $this->assertSame(1_484_202_200, $stat['ctime']); $this->assertSame(4, $stat[11]); $this->assertSame(4, $stat['blksize']); } @@ -190,10 +190,10 @@ public function testWritableStreamStatAfterSaving(): void $this->assertSame(0100444, $stat['mode']); $this->assertSame(10, $stat[7]); $this->assertSame(10, $stat['size']); - $this->assertSame(1484202200, $stat[9]); - $this->assertSame(1484202200, $stat['mtime']); - $this->assertSame(1484202200, $stat[10]); - $this->assertSame(1484202200, $stat['ctime']); + $this->assertSame(1_484_202_200, $stat[9]); + $this->assertSame(1_484_202_200, $stat['mtime']); + $this->assertSame(1_484_202_200, $stat[10]); + $this->assertSame(1_484_202_200, $stat['ctime']); $this->assertSame(4, $stat[11]); $this->assertSame(4, $stat['blksize']); } diff --git a/tests/GridFS/WritableStreamFunctionalTest.php b/tests/GridFS/WritableStreamFunctionalTest.php index ea6902d26..f87eaf1aa 100644 --- a/tests/GridFS/WritableStreamFunctionalTest.php +++ b/tests/GridFS/WritableStreamFunctionalTest.php @@ -13,8 +13,7 @@ */ class WritableStreamFunctionalTest extends FunctionalTestCase { - /** @var CollectionWrapper */ - private $collectionWrapper; + private CollectionWrapper $collectionWrapper; public function setUp(): void { @@ -81,7 +80,7 @@ public function testWriteBytesCalculatesMD5($input, $expectedMD5): void $fileDocument = $this->filesCollection->findOne( ['_id' => $stream->getFile()->_id], - ['projection' => ['md5' => 1, '_id' => 0]] + ['projection' => ['md5' => 1, '_id' => 0]], ); $this->assertSameDocument(['md5' => $expectedMD5], $fileDocument); diff --git a/tests/Model/BSONArrayTest.php b/tests/Model/BSONArrayTest.php index 9f420bed9..d6f6c162e 100644 --- a/tests/Model/BSONArrayTest.php +++ b/tests/Model/BSONArrayTest.php @@ -11,6 +11,8 @@ use function json_encode; +use const JSON_THROW_ON_ERROR; + class BSONArrayTest extends TestCase { public function testBsonSerializeReindexesKeys(): void @@ -88,7 +90,7 @@ public function testJsonSerialize(): void $expectedJson = '["foo",[1,2,3],{"foo":1,"bar":2,"baz":3},[[[]]]]'; - $this->assertSame($expectedJson, json_encode($document)); + $this->assertSame($expectedJson, json_encode($document, JSON_THROW_ON_ERROR)); } public function testJsonSerializeReindexesKeys(): void diff --git a/tests/Model/BSONDocumentTest.php b/tests/Model/BSONDocumentTest.php index bd0009dcf..4d832d591 100644 --- a/tests/Model/BSONDocumentTest.php +++ b/tests/Model/BSONDocumentTest.php @@ -12,6 +12,8 @@ use function json_encode; +use const JSON_THROW_ON_ERROR; + class BSONDocumentTest extends TestCase { public function testConstructorDefaultsToPropertyAccess(): void @@ -96,7 +98,7 @@ public function testJsonSerialize(): void $expectedJson = '{"foo":"bar","array":[1,2,3],"object":{"0":1,"1":2,"2":3},"nested":{"0":{"0":{}}}}'; - $this->assertSame($expectedJson, json_encode($document)); + $this->assertSame($expectedJson, json_encode($document, JSON_THROW_ON_ERROR)); } public function testJsonSerializeCastsToObject(): void diff --git a/tests/Model/BSONIteratorTest.php b/tests/Model/BSONIteratorTest.php index 9e208151b..efda8481d 100644 --- a/tests/Model/BSONIteratorTest.php +++ b/tests/Model/BSONIteratorTest.php @@ -34,7 +34,7 @@ public function provideTypeMapOptionsAndExpectedDocuments() [ ['_id' => 1, 'x' => ['foo' => 'bar']], ['_id' => 3, 'x' => ['foo' => 'bar']], - ] + ], )), [ (object) ['_id' => 1, 'x' => (object) ['foo' => 'bar']], @@ -48,7 +48,7 @@ public function provideTypeMapOptionsAndExpectedDocuments() [ ['_id' => 1, 'x' => ['foo' => 'bar']], ['_id' => 3, 'x' => ['foo' => 'bar']], - ] + ], )), [ ['_id' => 1, 'x' => ['foo' => 'bar']], @@ -62,7 +62,7 @@ public function provideTypeMapOptionsAndExpectedDocuments() [ ['_id' => 1, 'x' => ['foo' => 'bar']], ['_id' => 3, 'x' => ['foo' => 'bar']], - ] + ], )), [ (object) ['_id' => 1, 'x' => ['foo' => 'bar']], @@ -76,7 +76,7 @@ public function provideTypeMapOptionsAndExpectedDocuments() [ ['_id' => 1, 'x' => ['foo' => 'bar']], ['_id' => 3, 'x' => ['foo' => 'bar']], - ] + ], )), [ ['_id' => 1, 'x' => (object) ['foo' => 'bar']], diff --git a/tests/Model/CachingIteratorTest.php b/tests/Model/CachingIteratorTest.php index 1539db3e3..b8e43aece 100644 --- a/tests/Model/CachingIteratorTest.php +++ b/tests/Model/CachingIteratorTest.php @@ -119,8 +119,7 @@ public function testCountWithEmptySet(): void public function testWithWrongIterator(): void { $nestedIterator = new class implements Iterator { - /** @var int */ - private $i = 0; + private int $i = 0; public function current(): int { diff --git a/tests/Model/CallbackIteratorTest.php b/tests/Model/CallbackIteratorTest.php index efa3bd7d7..6705e79f5 100644 --- a/tests/Model/CallbackIteratorTest.php +++ b/tests/Model/CallbackIteratorTest.php @@ -28,7 +28,7 @@ public static function provideTests(): Generator $iteratorAggregate = new class ($listIterator) implements IteratorAggregate { - private $iterator; + private Iterator $iterator; public function __construct(Iterator $iterator) { diff --git a/tests/Model/ChangeStreamIteratorTest.php b/tests/Model/ChangeStreamIteratorTest.php index 053b1609d..bdc062be6 100644 --- a/tests/Model/ChangeStreamIteratorTest.php +++ b/tests/Model/ChangeStreamIteratorTest.php @@ -20,8 +20,7 @@ class ChangeStreamIteratorTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -144,7 +143,7 @@ private function assertNoCommandExecuted(callable $callable): void $callable, function (array $event) use (&$commands): void { $this->fail(sprintf('"%s" command was executed', $event['started']->getCommandName())); - } + }, ); $this->assertEmpty($commands); diff --git a/tests/Model/CollectionInfoTest.php b/tests/Model/CollectionInfoTest.php index ff5a112db..043023baa 100644 --- a/tests/Model/CollectionInfoTest.php +++ b/tests/Model/CollectionInfoTest.php @@ -13,7 +13,7 @@ public function testGetBasicInformation(): void $info = new CollectionInfo([ 'name' => 'foo', 'type' => 'view', - 'options' => ['capped' => true, 'size' => 1048576], + 'options' => ['capped' => true, 'size' => 1_048_576], 'info' => ['readOnly' => true], 'idIndex' => ['idIndex' => true], // Dummy option ]); @@ -24,8 +24,8 @@ public function testGetBasicInformation(): void $this->assertSame('view', $info->getType()); $this->assertSame('view', $info['type']); - $this->assertSame(['capped' => true, 'size' => 1048576], $info->getOptions()); - $this->assertSame(['capped' => true, 'size' => 1048576], $info['options']); + $this->assertSame(['capped' => true, 'size' => 1_048_576], $info->getOptions()); + $this->assertSame(['capped' => true, 'size' => 1_048_576], $info['options']); $this->assertSame(['readOnly' => true], $info->getInfo()); $this->assertSame(['readOnly' => true], $info['info']); @@ -58,22 +58,22 @@ public function testCappedCollectionMethods(): void $this->assertNull($info->getCappedMax()); $this->assertNull($info->getCappedSize()); - $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1048576]]); + $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1_048_576]]); $this->assertTrue($info->isCapped()); $this->assertNull($info->getCappedMax()); - $this->assertSame(1048576, $info->getCappedSize()); + $this->assertSame(1_048_576, $info->getCappedSize()); - $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1048576, 'max' => 100]]); + $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1_048_576, 'max' => 100]]); $this->assertTrue($info->isCapped()); $this->assertSame(100, $info->getCappedMax()); - $this->assertSame(1048576, $info->getCappedSize()); + $this->assertSame(1_048_576, $info->getCappedSize()); } public function testDebugInfo(): void { $expectedInfo = [ 'name' => 'foo', - 'options' => ['capped' => true, 'size' => 1048576], + 'options' => ['capped' => true, 'size' => 1_048_576], ]; $info = new CollectionInfo($expectedInfo); @@ -90,7 +90,7 @@ public function testImplementsArrayAccess(): void public function testOffsetSetCannotBeCalled(): void { - $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1048576]]); + $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1_048_576]]); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage(CollectionInfo::class . ' is immutable'); $info['options'] = ['capped' => false]; @@ -98,7 +98,7 @@ public function testOffsetSetCannotBeCalled(): void public function testOffsetUnsetCannotBeCalled(): void { - $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1048576]]); + $info = new CollectionInfo(['name' => 'foo', 'options' => ['capped' => true, 'size' => 1_048_576]]); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage(CollectionInfo::class . ' is immutable'); unset($info['options']); diff --git a/tests/Model/DatabaseInfoTest.php b/tests/Model/DatabaseInfoTest.php index 14e083a08..dd3e6093e 100644 --- a/tests/Model/DatabaseInfoTest.php +++ b/tests/Model/DatabaseInfoTest.php @@ -16,8 +16,8 @@ public function testGetName(): void public function testGetSizeOnDisk(): void { - $info = new DatabaseInfo(['sizeOnDisk' => 1048576]); - $this->assertSame(1048576, $info->getSizeOnDisk()); + $info = new DatabaseInfo(['sizeOnDisk' => 1_048_576]); + $this->assertSame(1_048_576, $info->getSizeOnDisk()); } public function testIsEmpty(): void @@ -33,7 +33,7 @@ public function testDebugInfo(): void { $expectedInfo = [ 'name' => 'foo', - 'sizeOnDisk' => 1048576, + 'sizeOnDisk' => 1_048_576, 'empty' => false, ]; @@ -51,7 +51,7 @@ public function testImplementsArrayAccess(): void public function testOffsetSetCannotBeCalled(): void { - $info = new DatabaseInfo(['name' => 'foo', 'sizeOnDisk' => 1048576, 'empty' => false]); + $info = new DatabaseInfo(['name' => 'foo', 'sizeOnDisk' => 1_048_576, 'empty' => false]); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage(DatabaseInfo::class . ' is immutable'); $info['empty'] = true; @@ -59,7 +59,7 @@ public function testOffsetSetCannotBeCalled(): void public function testOffsetUnsetCannotBeCalled(): void { - $info = new DatabaseInfo(['name' => 'foo', 'sizeOnDisk' => 1048576, 'empty' => false]); + $info = new DatabaseInfo(['name' => 'foo', 'sizeOnDisk' => 1_048_576, 'empty' => false]); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage(DatabaseInfo::class . ' is immutable'); unset($info['empty']); diff --git a/tests/Model/IndexInfoFunctionalTest.php b/tests/Model/IndexInfoFunctionalTest.php index a45a97724..65d22259a 100644 --- a/tests/Model/IndexInfoFunctionalTest.php +++ b/tests/Model/IndexInfoFunctionalTest.php @@ -7,8 +7,7 @@ class IndexInfoFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { diff --git a/tests/Operation/AggregateFunctionalTest.php b/tests/Operation/AggregateFunctionalTest.php index 4e7582975..4aad0a667 100644 --- a/tests/Operation/AggregateFunctionalTest.php +++ b/tests/Operation/AggregateFunctionalTest.php @@ -23,14 +23,14 @@ function (): void { $operation = new Aggregate( $this->getDatabaseName(), $this->getCollectionName(), - [['$match' => ['x' => 1]]] + [['$match' => ['x' => 1]]], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('allowDiskUse', $event['started']->getCommand()); - } + }, ); } @@ -42,14 +42,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['$out' => $this->getCollectionName() . '.output']], - ['batchSize' => 0] + ['batchSize' => 0], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertEquals(new stdClass(), $event['started']->getCommand()->cursor); - } + }, ); $outCollection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName() . '.output'); @@ -63,14 +63,14 @@ function (): void { $operation = new Aggregate( 'admin', null, - [['$currentOp' => (object) []]] + [['$currentOp' => (object) []]], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertSame(1, $event['started']->getCommand()->aggregate); - } + }, ); } @@ -82,14 +82,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['$match' => ['x' => 1]]], - ['readConcern' => $this->createDefaultReadConcern()] + ['readConcern' => $this->createDefaultReadConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -101,14 +101,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['$out' => $this->getCollectionName() . '.output']], - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); $outCollection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName() . '.output'); @@ -146,14 +146,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -184,7 +184,7 @@ public function testExplainOption(): void * result in different explain output (see: SERVER-24860) */ $this->assertThat($results[0], $this->logicalOr( $this->arrayHasKey('stages'), - $this->arrayHasKey('queryPlanner') + $this->arrayHasKey('queryPlanner'), )); } @@ -214,7 +214,7 @@ function () use ($pipeline, $options): void { }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); $this->assertCollectionCount($this->getCollectionName() . '.output', 0); @@ -228,7 +228,7 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['$match' => ['x' => 1]]], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -236,7 +236,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -248,14 +248,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['$match' => ['x' => 1]]], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/AggregateTest.php b/tests/Operation/AggregateTest.php index e7d148db1..7ea4ee9fa 100644 --- a/tests/Operation/AggregateTest.php +++ b/tests/Operation/AggregateTest.php @@ -53,7 +53,7 @@ public function testConstructorBatchSizeOptionRequiresUseCursor(): void $this->getDatabaseName(), $this->getCollectionName(), [['$match' => ['x' => 1]]], - ['batchSize' => 100, 'useCursor' => false] + ['batchSize' => 100, 'useCursor' => false], ); } diff --git a/tests/Operation/BulkWriteFunctionalTest.php b/tests/Operation/BulkWriteFunctionalTest.php index 2acb747bf..c1089150d 100644 --- a/tests/Operation/BulkWriteFunctionalTest.php +++ b/tests/Operation/BulkWriteFunctionalTest.php @@ -18,8 +18,7 @@ class BulkWriteFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -70,7 +69,7 @@ function () use ($document, $expectedDocument): void { $operation = new BulkWrite( $this->getDatabaseName(), $this->getCollectionName(), - [['insertOne' => [$document]]] + [['insertOne' => [$document]]], ); $result = $operation->execute($this->getPrimaryServer()); @@ -82,7 +81,7 @@ function () use ($document, $expectedDocument): void { }, function (array $event) use ($expectedDocument): void { $this->assertEquals($expectedDocument, $event['started']->getCommand()->documents[0] ?? null); - } + }, ); } @@ -161,7 +160,7 @@ function () use ($filter): void { ['replaceOne' => [$filter, ['x' => 1]]], ['updateOne' => [$filter, ['$set' => ['x' => 1]]]], ['updateMany' => [$filter, ['$set' => ['x' => 1]]]], - ] + ], ); $operation->execute($this->getPrimaryServer()); @@ -170,7 +169,7 @@ function (array $event) use ($expectedFilter): void { $this->assertEquals($expectedFilter, $event['started']->getCommand()->updates[0]->q ?? null); $this->assertEquals($expectedFilter, $event['started']->getCommand()->updates[1]->q ?? null); $this->assertEquals($expectedFilter, $event['started']->getCommand()->updates[2]->q ?? null); - } + }, ); } @@ -182,14 +181,14 @@ function () use ($replacement): void { $operation = new BulkWrite( $this->getDatabaseName(), $this->getCollectionName(), - [['replaceOne' => [['x' => 1], $replacement]]] + [['replaceOne' => [['x' => 1], $replacement]]], ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedReplacement): void { $this->assertEquals($expectedReplacement, $event['started']->getCommand()->updates[0]->u ?? null); - } + }, ); } @@ -211,7 +210,7 @@ function () use ($update): void { [ ['updateOne' => [['x' => 1], $update]], ['updateMany' => [['x' => 1], $update]], - ] + ], ); $operation->execute($this->getPrimaryServer()); @@ -219,7 +218,7 @@ function () use ($update): void { function (array $event) use ($expectedUpdate): void { $this->assertEquals($expectedUpdate, $event['started']->getCommand()->updates[0]->u ?? null); $this->assertEquals($expectedUpdate, $event['started']->getCommand()->updates[1]->u ?? null); - } + }, ); } @@ -256,7 +255,7 @@ function () use ($filter): void { [ ['deleteOne' => [$filter]], ['deleteMany' => [$filter]], - ] + ], ); $operation->execute($this->getPrimaryServer()); @@ -264,7 +263,7 @@ function () use ($filter): void { function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->deletes[0]->q ?? null); $this->assertEquals($expectedQuery, $event['started']->getCommand()->deletes[1]->q ?? null); - } + }, ); } @@ -372,14 +371,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['insertOne' => [['_id' => 1]]]], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -391,7 +390,7 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['insertOne' => [['_id' => 1]]]], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -399,7 +398,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -411,14 +410,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['insertOne' => [['_id' => 1]]]], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/BulkWriteTest.php b/tests/Operation/BulkWriteTest.php index 18941b455..5da144343 100644 --- a/tests/Operation/BulkWriteTest.php +++ b/tests/Operation/BulkWriteTest.php @@ -417,7 +417,7 @@ public function testConstructorOptionTypeChecks(array $options): void $this->getDatabaseName(), $this->getCollectionName(), [[BulkWrite::INSERT_ONE => [['x' => 1]]]], - $options + $options, ); } diff --git a/tests/Operation/CountDocumentsFunctionalTest.php b/tests/Operation/CountDocumentsFunctionalTest.php index 3b3aa7cc1..e3dc36a53 100644 --- a/tests/Operation/CountDocumentsFunctionalTest.php +++ b/tests/Operation/CountDocumentsFunctionalTest.php @@ -17,14 +17,14 @@ function () use ($filter): void { $operation = new CountDocuments( $this->getDatabaseName(), $this->getCollectionName(), - $filter + $filter, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedMatchStage): void { $this->assertEquals($expectedMatchStage, $event['started']->getCommand()->pipeline[0]->{'$match'} ?? null); - } + }, ); } diff --git a/tests/Operation/CountFunctionalTest.php b/tests/Operation/CountFunctionalTest.php index 192dd5434..47e9bea07 100644 --- a/tests/Operation/CountFunctionalTest.php +++ b/tests/Operation/CountFunctionalTest.php @@ -18,14 +18,14 @@ function () use ($filter): void { $operation = new Count( $this->getDatabaseName(), $this->getCollectionName(), - $filter + $filter, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->query ?? null); - } + }, ); } @@ -37,14 +37,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['readConcern' => $this->createDefaultReadConcern()] + ['readConcern' => $this->createDefaultReadConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -93,14 +93,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/CreateCollectionFunctionalTest.php b/tests/Operation/CreateCollectionFunctionalTest.php index aa9d9e592..aa383f091 100644 --- a/tests/Operation/CreateCollectionFunctionalTest.php +++ b/tests/Operation/CreateCollectionFunctionalTest.php @@ -14,14 +14,14 @@ function (): void { $operation = new CreateCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -32,14 +32,14 @@ function (): void { $operation = new CreateCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/CreateEncryptedCollectionFunctionalTest.php b/tests/Operation/CreateEncryptedCollectionFunctionalTest.php index fe3d5fa22..b1359e314 100644 --- a/tests/Operation/CreateEncryptedCollectionFunctionalTest.php +++ b/tests/Operation/CreateEncryptedCollectionFunctionalTest.php @@ -5,7 +5,7 @@ use MongoDB\BSON\Binary; use MongoDB\BSON\Document; use MongoDB\Client; -use MongoDB\ClientEncryption; +use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\WriteConcern; use MongoDB\Model\BSONArray; use MongoDB\Model\BSONDocument; @@ -18,8 +18,7 @@ class CreateEncryptedCollectionFunctionalTest extends FunctionalTestCase { public const LOCAL_MASTERKEY = 'Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk'; - /** @var ClientEncryption */ - private $clientEncryption; + private ClientEncryption $clientEncryption; public function setUp(): void { @@ -61,14 +60,14 @@ public function testCreateDataKeysNopIfFieldsIsMissing($input, array $expectedOu $operation = new CreateEncryptedCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['encryptedFields' => $input] + ['encryptedFields' => $input], ); $operation->createDataKeys( $this->clientEncryption, 'local', null, - $encryptedFieldsOutput + $encryptedFieldsOutput, ); $this->assertSame($expectedOutput, $encryptedFieldsOutput); @@ -92,14 +91,14 @@ public function testCreateDataKeysNopIfFieldsHasInvalidType($input, array $expec $operation = new CreateEncryptedCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['encryptedFields' => $input] + ['encryptedFields' => $input], ); $operation->createDataKeys( $this->clientEncryption, 'local', null, - $encryptedFieldsOutput + $encryptedFieldsOutput, ); $this->assertSame($expectedOutput, $encryptedFieldsOutput); @@ -123,14 +122,14 @@ public function testCreateDataKeysSkipsNonDocumentFields($input, array $expected $operation = new CreateEncryptedCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['encryptedFields' => $input] + ['encryptedFields' => $input], ); $operation->createDataKeys( $this->clientEncryption, 'local', null, - $encryptedFieldsOutput + $encryptedFieldsOutput, ); $this->assertSame($expectedOutput, $encryptedFieldsOutput); @@ -156,14 +155,14 @@ public function testCreateDataKeysDoesNotModifyOriginalEncryptedFieldsOption(): $operation = new CreateEncryptedCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['encryptedFields' => $originalEncryptedFields] + ['encryptedFields' => $originalEncryptedFields], ); $operation->createDataKeys( $this->clientEncryption, 'local', null, - $modifiedEncryptedFields + $modifiedEncryptedFields, ); $this->assertSame($originalField, $originalEncryptedFields->fields[0]); @@ -178,14 +177,14 @@ public function testEncryptedFieldsDocuments($input): void $operation = new CreateEncryptedCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['encryptedFields' => $input] + ['encryptedFields' => $input], ); $operation->createDataKeys( $this->clientEncryption, 'local', null, - $modifiedEncryptedFields + $modifiedEncryptedFields, ); $this->assertInstanceOf(Binary::class, $modifiedEncryptedFields['fields'][0]['keyId'] ?? null); diff --git a/tests/Operation/CreateIndexesFunctionalTest.php b/tests/Operation/CreateIndexesFunctionalTest.php index 748e33bc1..4204465d7 100644 --- a/tests/Operation/CreateIndexesFunctionalTest.php +++ b/tests/Operation/CreateIndexesFunctionalTest.php @@ -127,10 +127,10 @@ public function provideKeyCasts(): array // phpcs:disable Squiz.Functions.MultiLineFunctionDeclaration // phpcs:disable Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore return [ - 'array' => [function ($key) { return $key; }], - 'object' => [function ($key) { return (object) $key; }], - 'Serializable' => [function ($key) { return new BSONDocument($key); }], - 'Document' => [function ($key) { return Document::fromPHP($key); }], + 'array' => [fn ($key) => $key], + 'object' => [fn ($key) => (object) $key], + 'Serializable' => [fn ($key) => new BSONDocument($key)], + 'Document' => [fn ($key) => Document::fromPHP($key)], ]; // phpcs:enable } @@ -156,14 +156,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['key' => ['x' => 1]]], - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -175,14 +175,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['key' => ['x' => 1]]], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -200,14 +200,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['key' => ['x' => 1]]], - ['commitQuorum' => 'majority'] + ['commitQuorum' => 'majority'], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('commitQuorum', $event['started']->getCommand()); - } + }, ); } @@ -219,7 +219,7 @@ public function testCommitQuorumUnsupported(): void $this->getDatabaseName(), $this->getCollectionName(), [['key' => ['x' => 1]]], - ['commitQuorum' => 'majority'] + ['commitQuorum' => 'majority'], ); $this->expectException(UnsupportedException::class); diff --git a/tests/Operation/DatabaseCommandFunctionalTest.php b/tests/Operation/DatabaseCommandFunctionalTest.php index f113269d0..4381718e8 100644 --- a/tests/Operation/DatabaseCommandFunctionalTest.php +++ b/tests/Operation/DatabaseCommandFunctionalTest.php @@ -17,14 +17,14 @@ public function testCommandDocuments($command): void function () use ($command): void { $operation = new DatabaseCommand( $this->getDatabaseName(), - $command + $command, ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertEquals(1, $event['started']->getCommand()->ping ?? null); - } + }, ); } @@ -49,14 +49,14 @@ function (): void { $operation = new DatabaseCommand( $this->getDatabaseName(), ['ping' => 1], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/DeleteFunctionalTest.php b/tests/Operation/DeleteFunctionalTest.php index 4ae84045e..44d96bda7 100644 --- a/tests/Operation/DeleteFunctionalTest.php +++ b/tests/Operation/DeleteFunctionalTest.php @@ -14,8 +14,7 @@ class DeleteFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -33,14 +32,14 @@ function () use ($filter): void { $this->getDatabaseName(), $this->getCollectionName(), $filter, - 1 + 1, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->deletes[0]->q ?? null); - } + }, ); } @@ -92,7 +91,7 @@ public function testHintOptionAndUnacknowledgedWriteConcernUnsupportedClientSide $this->getCollectionName(), [], 0, - ['hint' => '_id_', 'writeConcern' => new WriteConcern(0)] + ['hint' => '_id_', 'writeConcern' => new WriteConcern(0)], ); $this->expectException(UnsupportedException::class); @@ -110,14 +109,14 @@ function (): void { $this->getCollectionName(), [], 0, - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/DistinctFunctionalTest.php b/tests/Operation/DistinctFunctionalTest.php index 53e411a0f..625053bd9 100644 --- a/tests/Operation/DistinctFunctionalTest.php +++ b/tests/Operation/DistinctFunctionalTest.php @@ -11,6 +11,8 @@ use function json_encode; use function usort; +use const JSON_THROW_ON_ERROR; + class DistinctFunctionalTest extends FunctionalTestCase { /** @dataProvider provideFilterDocuments */ @@ -22,14 +24,14 @@ function () use ($filter): void { $this->getDatabaseName(), $this->getCollectionName(), 'x', - $filter + $filter, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->query ?? null); - } + }, ); } @@ -42,14 +44,14 @@ function (): void { $this->getCollectionName(), 'x', [], - ['readConcern' => $this->createDefaultReadConcern()] + ['readConcern' => $this->createDefaultReadConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -62,14 +64,14 @@ function (): void { $this->getCollectionName(), 'x', [], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -103,8 +105,8 @@ public function testTypeMapOption(array $typeMap, array $expectedDocuments): voi return 1; } - $a = json_encode($a); - $b = json_encode($b); + $a = json_encode($a, JSON_THROW_ON_ERROR); + $b = json_encode($b, JSON_THROW_ON_ERROR); } return $a < $b ? -1 : 1; diff --git a/tests/Operation/DropCollectionFunctionalTest.php b/tests/Operation/DropCollectionFunctionalTest.php index 08a5af222..39b82a69f 100644 --- a/tests/Operation/DropCollectionFunctionalTest.php +++ b/tests/Operation/DropCollectionFunctionalTest.php @@ -15,14 +15,14 @@ function (): void { $operation = new DropCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -61,14 +61,14 @@ function (): void { $operation = new DropCollection( $this->getDatabaseName(), $this->getCollectionName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/DropDatabaseFunctionalTest.php b/tests/Operation/DropDatabaseFunctionalTest.php index 8ee86b3b1..6dd101a5d 100644 --- a/tests/Operation/DropDatabaseFunctionalTest.php +++ b/tests/Operation/DropDatabaseFunctionalTest.php @@ -18,14 +18,14 @@ public function testDefaultWriteConcernIsOmitted(): void function (): void { $operation = new DropDatabase( $this->getDatabaseName(), - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -63,14 +63,14 @@ public function testSessionOption(): void function (): void { $operation = new DropDatabase( $this->getDatabaseName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/DropIndexesFunctionalTest.php b/tests/Operation/DropIndexesFunctionalTest.php index a7cecf548..1c3604159 100644 --- a/tests/Operation/DropIndexesFunctionalTest.php +++ b/tests/Operation/DropIndexesFunctionalTest.php @@ -26,14 +26,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), 'x_1', - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -131,14 +131,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), '*', - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/ExplainFunctionalTest.php b/tests/Operation/ExplainFunctionalTest.php index aa28ce8f7..f37814486 100644 --- a/tests/Operation/ExplainFunctionalTest.php +++ b/tests/Operation/ExplainFunctionalTest.php @@ -131,7 +131,7 @@ public function testFindMaxAwait(): void $cappedCollectionOptions = [ 'capped' => true, 'max' => 100, - 'size' => 1048576, + 'size' => 1_048_576, ]; $this->createCollection($databaseName, $cappedCollectionName, $cappedCollectionOptions); @@ -150,7 +150,7 @@ function (array $event): void { $this->assertObjectNotHasAttribute('maxAwaitTimeMS', $command->explain); $this->assertObjectHasAttribute('tailable', $command->explain); $this->assertObjectHasAttribute('awaitData', $command->explain); - } + }, ); } @@ -162,7 +162,7 @@ public function testFindModifiers(): void $this->getDatabaseName(), $this->getCollectionName(), [], - ['modifiers' => ['$orderby' => ['_id' => 1]]] + ['modifiers' => ['$orderby' => ['_id' => 1]]], ); (new CommandObserver())->observe( @@ -174,7 +174,7 @@ function (array $event): void { $command = $event['started']->getCommand(); $this->assertObjectHasAttribute('sort', $command->explain); $this->assertObjectNotHasAttribute('modifiers', $command->explain); - } + }, ); } @@ -251,7 +251,7 @@ function (): void { $this->getCollectionName(), ['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $explainOperation = new Explain($this->getDatabaseName(), $operation); @@ -260,10 +260,10 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute( 'bypassDocumentValidation', - $event['started']->getCommand()->explain + $event['started']->getCommand()->explain, ); $this->assertEquals(true, $event['started']->getCommand()->explain->bypassDocumentValidation); - } + }, ); } @@ -278,7 +278,7 @@ function (): void { $this->getCollectionName(), ['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $explainOperation = new Explain($this->getDatabaseName(), $operation); @@ -287,9 +287,9 @@ function (): void { function (array $event): void { $this->assertObjectNotHasAttribute( 'bypassDocumentValidation', - $event['started']->getCommand()->explain + $event['started']->getCommand()->explain, ); - } + }, ); } diff --git a/tests/Operation/FindAndModifyFunctionalTest.php b/tests/Operation/FindAndModifyFunctionalTest.php index ebdbd1092..1b82328a1 100644 --- a/tests/Operation/FindAndModifyFunctionalTest.php +++ b/tests/Operation/FindAndModifyFunctionalTest.php @@ -22,14 +22,14 @@ function () use ($query): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['query' => $query, 'remove' => true] + ['query' => $query, 'remove' => true], ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->query ?? null); - } + }, ); } @@ -61,14 +61,14 @@ function () use ($update): void { [ 'query' => ['x' => 1], 'update' => $update, - ] + ], ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedUpdate): void { $this->assertEquals($expectedUpdate, $event['started']->getCommand()->update ?? null); - } + }, ); } @@ -96,14 +96,14 @@ function () use ($server): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true] + ['remove' => true], ); $operation->execute($server); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -114,14 +114,14 @@ function (): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'writeConcern' => $this->createDefaultWriteConcern()] + ['remove' => true, 'writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -132,7 +132,7 @@ public function testHintOptionUnsupportedClientSideError(): void $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'hint' => '_id_'] + ['remove' => true, 'hint' => '_id_'], ); $this->expectException(UnsupportedException::class); @@ -148,7 +148,7 @@ public function testHintOptionAndUnacknowledgedWriteConcernUnsupportedClientSide $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'hint' => '_id_', 'writeConcern' => new WriteConcern(0)] + ['remove' => true, 'hint' => '_id_', 'writeConcern' => new WriteConcern(0)], ); $this->expectException(UnsupportedException::class); @@ -170,7 +170,7 @@ public function testFindAndModifyReportedWriteConcernError(): void $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'writeConcern' => new WriteConcern(50)] + ['remove' => true, 'writeConcern' => new WriteConcern(50)], ); $operation->execute($this->getPrimaryServer()); @@ -183,14 +183,14 @@ function (): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'session' => $this->createSession()] + ['remove' => true, 'session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -201,7 +201,7 @@ function (): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'bypassDocumentValidation' => true] + ['remove' => true, 'bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -209,7 +209,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -220,14 +220,14 @@ function (): void { $operation = new FindAndModify( $this->getDatabaseName(), $this->getCollectionName(), - ['remove' => true, 'bypassDocumentValidation' => false] + ['remove' => true, 'bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } @@ -242,7 +242,7 @@ public function testTypeMapOption(?array $typeMap, $expectedDocument): void [ 'remove' => true, 'typeMap' => $typeMap, - ] + ], ); $document = $operation->execute($this->getPrimaryServer()); diff --git a/tests/Operation/FindFunctionalTest.php b/tests/Operation/FindFunctionalTest.php index a7975f338..53b50f4da 100644 --- a/tests/Operation/FindFunctionalTest.php +++ b/tests/Operation/FindFunctionalTest.php @@ -23,14 +23,14 @@ function () use ($filter): void { $operation = new Find( $this->getDatabaseName(), $this->getCollectionName(), - $filter + $filter, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedQuery): void { $this->assertEquals($expectedQuery, $event['started']->getCommand()->filter ?? null); - } + }, ); } @@ -43,14 +43,14 @@ function () use ($modifiers): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['modifiers' => $modifiers] + ['modifiers' => $modifiers], ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedSort): void { $this->assertEquals($expectedSort, $event['started']->getCommand()->sort ?? null); - } + }, ); } @@ -74,14 +74,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['readConcern' => $this->createDefaultReadConcern()] + ['readConcern' => $this->createDefaultReadConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -144,14 +144,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -211,7 +211,7 @@ public function testMaxAwaitTimeMS(): void $cappedCollectionOptions = [ 'capped' => true, 'max' => 100, - 'size' => 1048576, + 'size' => 1_048_576, ]; $this->createCollection($databaseName, $cappedCollectionName, $cappedCollectionOptions); diff --git a/tests/Operation/InsertManyFunctionalTest.php b/tests/Operation/InsertManyFunctionalTest.php index 4d47ea104..b8ca886be 100644 --- a/tests/Operation/InsertManyFunctionalTest.php +++ b/tests/Operation/InsertManyFunctionalTest.php @@ -14,8 +14,7 @@ class InsertManyFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -54,7 +53,7 @@ function () use ($documents, $expectedDocuments): void { $operation = new InsertMany( $this->getDatabaseName(), $this->getCollectionName(), - $documents + $documents, ); $result = $operation->execute($this->getPrimaryServer()); @@ -69,7 +68,7 @@ function () use ($documents, $expectedDocuments): void { }, function (array $event) use ($expectedDocuments): void { $this->assertEquals($expectedDocuments, $event['started']->getCommand()->documents ?? null); - } + }, ); } @@ -125,14 +124,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['_id' => 1], ['_id' => 2]], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -144,7 +143,7 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['_id' => 1], ['_id' => 2]], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -152,7 +151,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -164,14 +163,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), [['_id' => 1], ['_id' => 2]], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/InsertOneFunctionalTest.php b/tests/Operation/InsertOneFunctionalTest.php index 61a517894..0a158ccb5 100644 --- a/tests/Operation/InsertOneFunctionalTest.php +++ b/tests/Operation/InsertOneFunctionalTest.php @@ -15,8 +15,7 @@ class InsertOneFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -36,7 +35,7 @@ function () use ($document, $expectedDocument): void { $operation = new InsertOne( $this->getDatabaseName(), $this->getCollectionName(), - $document + $document, ); $result = $operation->execute($this->getPrimaryServer()); @@ -48,7 +47,7 @@ function () use ($document, $expectedDocument): void { }, function (array $event) use ($expectedDocument): void { $this->assertEquals($expectedDocument, $event['started']->getCommand()->documents[0] ?? null); - } + }, ); } @@ -116,14 +115,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), ['_id' => 1], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -135,7 +134,7 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), ['_id' => 1], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -143,7 +142,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -155,14 +154,14 @@ function (): void { $this->getDatabaseName(), $this->getCollectionName(), ['_id' => 1], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/ListCollectionNamesFunctionalTest.php b/tests/Operation/ListCollectionNamesFunctionalTest.php index e72c7789c..91f8b2fb7 100644 --- a/tests/Operation/ListCollectionNamesFunctionalTest.php +++ b/tests/Operation/ListCollectionNamesFunctionalTest.php @@ -35,7 +35,7 @@ public function testAuthorizedCollectionsOption(): void function (): void { $operation = new ListCollectionNames( $this->getDatabaseName(), - ['authorizedCollections' => true] + ['authorizedCollections' => true], ); $operation->execute($this->getPrimaryServer()); @@ -43,7 +43,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('authorizedCollections', $event['started']->getCommand()); $this->assertSame(true, $event['started']->getCommand()->authorizedCollections); - } + }, ); } @@ -53,14 +53,14 @@ public function testSessionOption(): void function (): void { $operation = new ListCollectionNames( $this->getDatabaseName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/ListCollectionsFunctionalTest.php b/tests/Operation/ListCollectionsFunctionalTest.php index ec48e7e79..ffdc3748c 100644 --- a/tests/Operation/ListCollectionsFunctionalTest.php +++ b/tests/Operation/ListCollectionsFunctionalTest.php @@ -80,7 +80,7 @@ public function testAuthorizedCollectionsOption(): void function (): void { $operation = new ListCollections( $this->getDatabaseName(), - ['authorizedCollections' => true] + ['authorizedCollections' => true], ); $operation->execute($this->getPrimaryServer()); @@ -88,7 +88,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('authorizedCollections', $event['started']->getCommand()); $this->assertSame(true, $event['started']->getCommand()->authorizedCollections); - } + }, ); } @@ -98,14 +98,14 @@ public function testSessionOption(): void function (): void { $operation = new ListCollections( $this->getDatabaseName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/ListDatabaseNamesFunctionalTest.php b/tests/Operation/ListDatabaseNamesFunctionalTest.php index b0b728a89..651112afd 100644 --- a/tests/Operation/ListDatabaseNamesFunctionalTest.php +++ b/tests/Operation/ListDatabaseNamesFunctionalTest.php @@ -26,7 +26,7 @@ function () use (&$databases, $server): void { function (array $event): void { $this->assertObjectNotHasAttribute('authorizedDatabases', $event['started']->getCommand()); $this->assertSame(true, $event['started']->getCommand()->nameOnly); - } + }, ); foreach ($databases as $database) { @@ -39,7 +39,7 @@ public function testAuthorizedDatabasesOption(): void (new CommandObserver())->observe( function (): void { $operation = new ListDatabaseNames( - ['authorizedDatabases' => true] + ['authorizedDatabases' => true], ); $operation->execute($this->getPrimaryServer()); @@ -47,7 +47,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('authorizedDatabases', $event['started']->getCommand()); $this->assertSame(true, $event['started']->getCommand()->authorizedDatabases); - } + }, ); } @@ -73,14 +73,14 @@ public function testSessionOption(): void (new CommandObserver())->observe( function (): void { $operation = new ListDatabaseNames( - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/ListDatabasesFunctionalTest.php b/tests/Operation/ListDatabasesFunctionalTest.php index 45283ccfb..525b3d94e 100644 --- a/tests/Operation/ListDatabasesFunctionalTest.php +++ b/tests/Operation/ListDatabasesFunctionalTest.php @@ -27,7 +27,7 @@ function () use (&$databases, $server): void { }, function (array $event): void { $this->assertObjectNotHasAttribute('authorizedDatabases', $event['started']->getCommand()); - } + }, ); $this->assertInstanceOf(DatabaseInfoIterator::class, $databases); @@ -42,7 +42,7 @@ public function testAuthorizedDatabasesOption(): void (new CommandObserver())->observe( function (): void { $operation = new ListDatabases( - ['authorizedDatabases' => true] + ['authorizedDatabases' => true], ); $operation->execute($this->getPrimaryServer()); @@ -50,7 +50,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('authorizedDatabases', $event['started']->getCommand()); $this->assertSame(true, $event['started']->getCommand()->authorizedDatabases); - } + }, ); } @@ -80,14 +80,14 @@ public function testSessionOption(): void (new CommandObserver())->observe( function (): void { $operation = new ListDatabases( - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/ListIndexesFunctionalTest.php b/tests/Operation/ListIndexesFunctionalTest.php index 98aef09f2..553615e4d 100644 --- a/tests/Operation/ListIndexesFunctionalTest.php +++ b/tests/Operation/ListIndexesFunctionalTest.php @@ -49,14 +49,14 @@ function (): void { $operation = new ListIndexes( $this->getDatabaseName(), $this->getCollectionName(), - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/MapReduceFunctionalTest.php b/tests/Operation/MapReduceFunctionalTest.php index 55831dd2f..cc4084c71 100644 --- a/tests/Operation/MapReduceFunctionalTest.php +++ b/tests/Operation/MapReduceFunctionalTest.php @@ -35,14 +35,14 @@ function (): void { new Javascript('function() { emit(this.x, this.y); }'), new Javascript('function(key, values) { return Array.sum(values); }'), ['inline' => 1], - ['readConcern' => $this->createDefaultReadConcern()] + ['readConcern' => $this->createDefaultReadConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand()); - } + }, ); } @@ -60,14 +60,14 @@ function (): void { new Javascript('function() { emit(this.x, this.y); }'), new Javascript('function(key, values) { return Array.sum(values); }'), $this->getCollectionName() . '.output', - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -155,14 +155,14 @@ function (): void { new Javascript('function() { emit(this.x, this.y); }'), new Javascript('function(key, values) { return Array.sum(values); }'), ['inline' => 1], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -178,7 +178,7 @@ function (): void { new Javascript('function() { emit(this.x, this.y); }'), new Javascript('function(key, values) { return Array.sum(values); }'), ['inline' => 1], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -186,7 +186,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -202,14 +202,14 @@ function (): void { new Javascript('function() { emit(this.x, this.y); }'), new Javascript('function(key, values) { return Array.sum(values); }'), ['inline' => 1], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } diff --git a/tests/Operation/ModifyCollectionFunctionalTest.php b/tests/Operation/ModifyCollectionFunctionalTest.php index 5e971a0c8..c92cdb0e8 100644 --- a/tests/Operation/ModifyCollectionFunctionalTest.php +++ b/tests/Operation/ModifyCollectionFunctionalTest.php @@ -28,7 +28,7 @@ public function testCollMod(): void $this->getDatabaseName(), $this->getCollectionName(), ['index' => ['keyPattern' => ['lastAccess' => 1], 'expireAfterSeconds' => 1000]], - ['typeMap' => ['root' => 'array', 'document' => 'array']] + ['typeMap' => ['root' => 'array', 'document' => 'array']], ); $result = $modifyCollection->execute($this->getPrimaryServer()); diff --git a/tests/Operation/RenameCollectionFunctionalTest.php b/tests/Operation/RenameCollectionFunctionalTest.php index 21a88e25d..05be70da7 100644 --- a/tests/Operation/RenameCollectionFunctionalTest.php +++ b/tests/Operation/RenameCollectionFunctionalTest.php @@ -10,14 +10,11 @@ class RenameCollectionFunctionalTest extends FunctionalTestCase { - /** @var integer */ - private static $errorCodeNamespaceNotFound = 26; + private static int $errorCodeNamespaceNotFound = 26; - /** @var integer */ - private static $errorCodeNamespaceExists = 48; + private static int $errorCodeNamespaceExists = 48; - /** @var string */ - private $toCollectionName; + private string $toCollectionName; public function setUp(): void { @@ -43,14 +40,14 @@ function (): void { $this->getCollectionName(), $this->getDatabaseName(), $this->toCollectionName, - ['writeConcern' => $this->createDefaultWriteConcern()] + ['writeConcern' => $this->createDefaultWriteConcern()], ); $operation->execute($server); }, function (array $event): void { $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand()); - } + }, ); } @@ -66,7 +63,7 @@ public function testRenameCollectionToNonexistentTarget(): void $this->getDatabaseName(), $this->getCollectionName(), $this->getDatabaseName(), - $this->toCollectionName + $this->toCollectionName, ); $commandResult = $operation->execute($server); @@ -101,7 +98,7 @@ public function testRenameCollectionExistingTarget(): void $this->getDatabaseName(), $this->getCollectionName(), $this->getDatabaseName(), - $this->toCollectionName + $this->toCollectionName, ); $operation->execute($server); } @@ -115,7 +112,7 @@ public function testRenameNonexistentCollection(): void $this->getDatabaseName(), $this->getCollectionName(), $this->getDatabaseName(), - $this->toCollectionName + $this->toCollectionName, ); $operation->execute($this->getPrimaryServer()); } @@ -135,14 +132,14 @@ function (): void { $this->getCollectionName(), $this->getDatabaseName(), $this->toCollectionName, - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($server); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } } diff --git a/tests/Operation/RenameCollectionTest.php b/tests/Operation/RenameCollectionTest.php index ceabceaa4..f1d0e15d5 100644 --- a/tests/Operation/RenameCollectionTest.php +++ b/tests/Operation/RenameCollectionTest.php @@ -16,7 +16,7 @@ public function testConstructorOptionTypeChecks(array $options): void $this->getCollectionName(), $this->getDatabaseName(), $this->getCollectionName() . '.renamed', - $options + $options, ); } diff --git a/tests/Operation/UpdateFunctionalTest.php b/tests/Operation/UpdateFunctionalTest.php index d0a92679f..e70331433 100644 --- a/tests/Operation/UpdateFunctionalTest.php +++ b/tests/Operation/UpdateFunctionalTest.php @@ -17,8 +17,7 @@ class UpdateFunctionalTest extends FunctionalTestCase { - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -36,14 +35,14 @@ function () use ($filter): void { $this->getDatabaseName(), $this->getCollectionName(), $filter, - ['$set' => ['x' => 1]] + ['$set' => ['x' => 1]], ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedFilter): void { $this->assertEquals($expectedFilter, $event['started']->getCommand()->updates[0]->q ?? null); - } + }, ); } @@ -65,14 +64,14 @@ function () use ($update): void { $this->getDatabaseName(), $this->getCollectionName(), ['x' => 1], - $update + $update, ); $operation->execute($this->getPrimaryServer()); }, function (array $event) use ($expectedUpdate): void { $this->assertEquals($expectedUpdate, $event['started']->getCommand()->updates[0]->u ?? null); - } + }, ); } @@ -97,14 +96,14 @@ function (): void { $this->getCollectionName(), ['_id' => 1], ['$inc' => ['x' => 1]], - ['session' => $this->createSession()] + ['session' => $this->createSession()], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectHasAttribute('lsid', $event['started']->getCommand()); - } + }, ); } @@ -117,7 +116,7 @@ function (): void { $this->getCollectionName(), ['_id' => 1], ['$inc' => ['x' => 1]], - ['bypassDocumentValidation' => true] + ['bypassDocumentValidation' => true], ); $operation->execute($this->getPrimaryServer()); @@ -125,7 +124,7 @@ function (): void { function (array $event): void { $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation); - } + }, ); } @@ -138,14 +137,14 @@ function (): void { $this->getCollectionName(), ['_id' => 1], ['$inc' => ['x' => 1]], - ['bypassDocumentValidation' => false] + ['bypassDocumentValidation' => false], ); $operation->execute($this->getPrimaryServer()); }, function (array $event): void { $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand()); - } + }, ); } @@ -158,7 +157,7 @@ public function testHintOptionAndUnacknowledgedWriteConcernUnsupportedClientSide $this->getCollectionName(), ['_id' => 1], ['$inc' => ['x' => 1]], - ['hint' => '_id_', 'writeConcern' => new WriteConcern(0)] + ['hint' => '_id_', 'writeConcern' => new WriteConcern(0)], ); $this->expectException(UnsupportedException::class); diff --git a/tests/Operation/WatchFunctionalTest.php b/tests/Operation/WatchFunctionalTest.php index bc633c191..447d8cc4a 100644 --- a/tests/Operation/WatchFunctionalTest.php +++ b/tests/Operation/WatchFunctionalTest.php @@ -40,11 +40,9 @@ class WatchFunctionalTest extends FunctionalTestCase public const INTERRUPTED = 11601; public const NOT_PRIMARY = 10107; - /** @var integer */ - private static $wireVersionForStartAtOperationTime = 7; + private static int $wireVersionForStartAtOperationTime = 7; - /** @var array */ - private $defaultOptions = ['maxAwaitTimeMS' => 500]; + private array $defaultOptions = ['maxAwaitTimeMS' => 500]; public function setUp(): void { @@ -117,7 +115,7 @@ function () use ($operation, &$changeStream): void { }, function (array $event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertCount(1, $events); @@ -139,7 +137,7 @@ function () use ($changeStream): void { }, function (array $event) use (&$lastEvent): void { $lastEvent = $event; - } + }, ); $this->assertNotNull($lastEvent); @@ -174,7 +172,7 @@ function () use ($changeStream): void { }, function (array $event) use (&$commands): void { $commands[] = $event['started']->getCommandName(); - } + }, ); $expectedCommands = [ @@ -213,7 +211,7 @@ function () use ($operation, &$changeStream): void { }, function (array $event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertCount(1, $events); @@ -235,7 +233,7 @@ function () use ($changeStream): void { }, function (array $event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertCount(3, $events); @@ -287,7 +285,7 @@ function () use ($operation, &$changeStream): void { }, function (array $event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertCount(1, $events); @@ -312,7 +310,7 @@ function () use ($changeStream): void { }, function (array $event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertCount(3, $events); @@ -1118,7 +1116,7 @@ function (array $event) use (&$originalSession): void { if (isset($command->aggregate)) { $originalSession = bin2hex((string) $command->lsid->id); } - } + }, ); $changeStream->rewind(); @@ -1131,7 +1129,7 @@ function () use (&$changeStream): void { function (array $event) use (&$sessionAfterResume, &$commands): void { $commands[] = $event['started']->getCommandName(); $sessionAfterResume[] = bin2hex((string) $event['started']->getCommand()->lsid->id); - } + }, ); $expectedCommands = [ @@ -1213,7 +1211,7 @@ function (array $event) use (&$aggregateCommands): void { } $aggregateCommands[] = (array) $command; - } + }, ); $this->assertCount(2, $aggregateCommands); @@ -1224,9 +1222,9 @@ function (array $event) use (&$aggregateCommands): void { $this->logicalOr( $this->objectHasAttribute('resumeAfter'), $this->objectHasAttribute('startAfter'), - $this->objectHasAttribute('startAtOperationTime') - ) - ) + $this->objectHasAttribute('startAtOperationTime'), + ), + ), ); $this->assertThat( @@ -1234,8 +1232,8 @@ function (array $event) use (&$aggregateCommands): void { $this->logicalOr( $this->objectHasAttribute('resumeAfter'), $this->objectHasAttribute('startAfter'), - $this->objectHasAttribute('startAtOperationTime') - ) + $this->objectHasAttribute('startAtOperationTime'), + ), ); $aggregateCommands = array_map( @@ -1244,14 +1242,14 @@ function (array $aggregateCommand) { if (isset($aggregateCommand['pipeline'][0]->{'$changeStream'})) { $aggregateCommand['pipeline'][0]->{'$changeStream'} = array_diff_key( (array) $aggregateCommand['pipeline'][0]->{'$changeStream'}, - ['resumeAfter' => false, 'startAfter' => false, 'startAtOperationTime' => false] + ['resumeAfter' => false, 'startAfter' => false, 'startAtOperationTime' => false], ); } // Remove options we don't want to compare between commands return array_diff_key($aggregateCommand, ['lsid' => false, '$clusterTime' => false]); }, - $aggregateCommands + $aggregateCommands, ); // Ensure options in original and resuming aggregate command match @@ -1284,7 +1282,7 @@ function () use ($operation): void { }, function (array $event) use (&$commandCount): void { $commandCount++; - } + }, ); $this->assertSame(1, $commandCount); @@ -1318,11 +1316,9 @@ public function testOriginalReadPreferenceIsPreservedOnResume(): void $this->assertNotSame($previousCursorId, $changeStream->getCursorId()); $getCursor = Closure::bind( - function () { - return $this->iterator->getInnerIterator(); - }, + fn () => $this->iterator->getInnerIterator(), $changeStream, - ChangeStream::class + ChangeStream::class, ); $cursor = $getCursor(); assert($cursor instanceof Cursor); @@ -1460,7 +1456,7 @@ function (array $event) use (&$aggregateCommand): void { } $aggregateCommand = $event['started']->getCommand(); - } + }, ); $this->assertNotNull($aggregateCommand); @@ -1509,7 +1505,7 @@ function (array $event) use (&$aggregateCommand): void { } $aggregateCommand = $event['started']->getCommand(); - } + }, ); $this->assertNotNull($aggregateCommand); @@ -1525,7 +1521,7 @@ private function assertNoCommandExecuted(callable $callable): void $callable, function (array $event) use (&$commands): void { $this->fail(sprintf('"%s" command was executed', $event['started']->getCommandName())); - } + }, ); $this->assertEmpty($commands); @@ -1560,7 +1556,7 @@ private function insertDocument($document): void $this->getDatabaseName(), $this->getCollectionName(), $document, - ['writeConcern' => new WriteConcern(WriteConcern::MAJORITY)] + ['writeConcern' => new WriteConcern(WriteConcern::MAJORITY)], ); $writeResult = $insertOne->execute($this->getPrimaryServer()); $this->assertEquals(1, $writeResult->getInsertedCount()); diff --git a/tests/PHPUnit/Functions.php b/tests/PHPUnit/Functions.php index 55edd3a6f..64a4eee19 100644 --- a/tests/PHPUnit/Functions.php +++ b/tests/PHPUnit/Functions.php @@ -2614,7 +2614,7 @@ function never(): InvokedCountMatcher function atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher { return new InvokedAtLeastCountMatcher( - $requiredInvocations + $requiredInvocations, ); } } diff --git a/tests/PedantryTest.php b/tests/PedantryTest.php index a46477d94..ae11134ee 100644 --- a/tests/PedantryTest.php +++ b/tests/PedantryTest.php @@ -35,7 +35,7 @@ public function testMethodsAreOrderedAlphabeticallyByVisibility($className): voi function (ReflectionMethod $method) use ($class) { return $method->getDeclaringClass() == $class // Exclude inherited methods && $method->getFileName() === $class->getFileName(); // Exclude methods inherited from traits - } + }, ); $getSortValue = function (ReflectionMethod $method) { @@ -55,17 +55,11 @@ function (ReflectionMethod $method) use ($class) { $sortedMethods = $methods; usort( $sortedMethods, - function (ReflectionMethod $a, ReflectionMethod $b) use ($getSortValue) { - return strcasecmp($getSortValue($a), $getSortValue($b)); - } + fn (ReflectionMethod $a, ReflectionMethod $b) => strcasecmp($getSortValue($a), $getSortValue($b)) ); - $methods = array_map(function (ReflectionMethod $method) { - return $method->getName(); - }, $methods); - $sortedMethods = array_map(function (ReflectionMethod $method) { - return $method->getName(); - }, $sortedMethods); + $methods = array_map(fn (ReflectionMethod $method) => $method->getName(), $methods); + $sortedMethods = array_map(fn (ReflectionMethod $method) => $method->getName(), $sortedMethods); $this->assertEquals($sortedMethods, $methods); } diff --git a/tests/SpecTests/AtlasDataLakeSpecTest.php b/tests/SpecTests/AtlasDataLakeSpecTest.php index 4b37a2f12..b0c536cc0 100644 --- a/tests/SpecTests/AtlasDataLakeSpecTest.php +++ b/tests/SpecTests/AtlasDataLakeSpecTest.php @@ -68,8 +68,8 @@ public function testAtlasDataLake(stdClass $test, ?array $runOn, array $data, ?s $this->markTestSkipped($test->skipReason); } - $databaseName = $databaseName ?? $this->getDatabaseName(); - $collectionName = $collectionName ?? $this->getCollectionName(); + $databaseName ??= $this->getDatabaseName(); + $collectionName ??= $this->getCollectionName(); $context = Context::fromCrud($test, $databaseName, $collectionName); $this->setContext($context); @@ -186,7 +186,7 @@ function (array $event) use (&$cursorId, &$cursorNamespace): void { $this->assertIsArray($reply->cursorsKilled); $this->assertArrayHasKey(0, $reply->cursorsKilled); $this->assertSame($cursorId, $reply->cursorsKilled[0]); - } + }, ); } @@ -239,7 +239,7 @@ private function isAtlasDataLake(): bool { $cursor = $this->manager->executeCommand( $this->getDatabaseName(), - new Command(['buildInfo' => 1]) + new Command(['buildInfo' => 1]), ); $document = current($cursor->toArray()); diff --git a/tests/SpecTests/ClientSideEncryption/Prose21_AutomaticDataEncryptionKeysTest.php b/tests/SpecTests/ClientSideEncryption/Prose21_AutomaticDataEncryptionKeysTest.php index aecdfeb38..05480d9d6 100644 --- a/tests/SpecTests/ClientSideEncryption/Prose21_AutomaticDataEncryptionKeysTest.php +++ b/tests/SpecTests/ClientSideEncryption/Prose21_AutomaticDataEncryptionKeysTest.php @@ -4,6 +4,7 @@ use Generator; use MongoDB\BSON\Binary; +use MongoDB\Database; use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\Exception\BulkWriteException; use MongoDB\Driver\Exception\CommandException; @@ -23,8 +24,8 @@ class Prose21_AutomaticDataEncryptionKeysTest extends FunctionalTestCase { public const SERVER_ERROR_TYPEMISMATCH = 14; - private $clientEncryption; - private $database; + private ?ClientEncryption $clientEncryption = null; + private ?Database $database = null; public function setUp(): void { @@ -73,7 +74,7 @@ public function testCase1_SimpleCreationAndValidation(string $kmsProvider, ?arra $this->clientEncryption, $kmsProvider, $masterKey, - ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null]]]] + ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null]]]], ); $this->assertCommandSucceeded($result); @@ -110,7 +111,7 @@ public function testCase2_MissingEncryptedFields(string $kmsProvider, ?array $ma $this->clientEncryption, $kmsProvider, $masterKey, - [] + [], ); } @@ -126,7 +127,7 @@ public function testCase3_InvalidKeyId(string $kmsProvider, ?array $masterKey): $this->clientEncryption, $kmsProvider, $masterKey, - ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => false]]]] + ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => false]]]], ); $this->fail('CreateEncryptedCollectionException was not thrown'); } catch (CreateEncryptedCollectionException $e) { @@ -150,7 +151,7 @@ public function testCase4_InsertEncryptedValue(string $kmsProvider, ?array $mast $this->clientEncryption, $kmsProvider, $masterKey, - ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null]]]] + ['encryptedFields' => ['fields' => [['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null]]]], ); $this->assertCommandSucceeded($result); diff --git a/tests/SpecTests/ClientSideEncryption/Prose22_RangeExplicitEncryptionTest.php b/tests/SpecTests/ClientSideEncryption/Prose22_RangeExplicitEncryptionTest.php index 14c465981..a0274b3c7 100644 --- a/tests/SpecTests/ClientSideEncryption/Prose22_RangeExplicitEncryptionTest.php +++ b/tests/SpecTests/ClientSideEncryption/Prose22_RangeExplicitEncryptionTest.php @@ -10,6 +10,8 @@ use MongoDB\BSON\Document; use MongoDB\BSON\Int64; use MongoDB\BSON\UTCDateTime; +use MongoDB\Client; +use MongoDB\Collection; use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\Exception\EncryptionException; use MultipleIterator; @@ -28,9 +30,9 @@ */ class Prose22_RangeExplicitEncryptionTest extends FunctionalTestCase { - private $clientEncryption; - private $collection; - private $encryptedClient; + private ?ClientEncryption $clientEncryption = null; + private ?Collection $collection = null; + private ?Client $encryptedClient = null; private $key1Id; public function setUp(): void @@ -446,30 +448,20 @@ private static function getCastCallableForType(string $type): callable switch ($type) { case 'DecimalNoPrecision': case 'DecimalPrecision': - return function (int $value) { - return new Decimal128((string) $value); - }; + return fn (int $value) => new Decimal128((string) $value); case 'DoubleNoPrecision': case 'DoublePrecision': - return function (int $value) { - return (double) $value; - }; + return fn (int $value) => (double) $value; case 'Date': - return function (int $value) { - return new UTCDateTime($value); - }; + return fn (int $value) => new UTCDateTime($value); case 'Int': - return function (int $value) { - return $value; - }; + return fn (int $value) => $value; case 'Long': - return function (int $value) { - return new Int64($value); - }; + return fn (int $value) => new Int64($value); default: throw new LogicException('Unsupported type: ' . $type); diff --git a/tests/SpecTests/ClientSideEncryptionSpecTest.php b/tests/SpecTests/ClientSideEncryptionSpecTest.php index b2d866496..d01c5378c 100644 --- a/tests/SpecTests/ClientSideEncryptionSpecTest.php +++ b/tests/SpecTests/ClientSideEncryptionSpecTest.php @@ -42,6 +42,8 @@ use function str_repeat; use function substr; +use const JSON_THROW_ON_ERROR; + /** * Client-side encryption spec tests. * @@ -53,8 +55,7 @@ class ClientSideEncryptionSpecTest extends FunctionalTestCase { public const LOCAL_MASTERKEY = 'Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk'; - /** @var array */ - private static $incompleteTests = [ + private static array $incompleteTests = [ 'explain: Explain a find with deterministic encryption' => 'crypt_shared does not add apiVersion field to explain commands (PHPLIB-947, SERVER-69564)', 'fle2v2-Range-Decimal-Aggregate: FLE2 Range Decimal. Aggregate.' => 'Bundled libmongocrypt does not support Decimal128 (PHPC-2207)', 'fle2v2-Range-Decimal-Correctness: Find with $gt' => 'Bundled libmongocrypt does not support Decimal128 (PHPC-2207)', @@ -169,8 +170,8 @@ public function testClientSideEncryption(stdClass $test, ?array $runOn, array $d $this->markTestSkipped($test->skipReason); } - $databaseName = $databaseName ?? $this->getDatabaseName(); - $collectionName = $collectionName ?? $this->getCollectionName(); + $databaseName ??= $this->getDatabaseName(); + $collectionName ??= $this->getCollectionName(); try { $context = Context::fromClientSideEncryption($test, $databaseName, $collectionName); @@ -330,7 +331,7 @@ function ($command) use (&$insertCommand): void { if ($command['started']->getCommandName() === 'insert') { $insertCommand = $command['started']->getCommand(); } - } + }, ); $this->assertInstanceOf(Binary::class, $dataKeyId); @@ -468,7 +469,7 @@ public static function provideBSONSizeLimitsAndBatchSplittingTests() { yield 'Test 1' => [ static function (self $test, Collection $collection): void { - $collection->insertOne(['_id' => 'over_2mib_under_16mib', 'unencrypted' => str_repeat('a', 2097152)]); + $collection->insertOne(['_id' => 'over_2mib_under_16mib', 'unencrypted' => str_repeat('a', 2_097_152)]); $test->assertCollectionCount($collection->getNamespace(), 1); }, ]; @@ -476,7 +477,7 @@ static function (self $test, Collection $collection): void { yield 'Test 2' => [ static function (self $test, Collection $collection, array $document): void { $collection->insertOne( - ['_id' => 'encryption_exceeds_2mib', 'unencrypted' => str_repeat('a', 2097152 - 2000)] + $document + ['_id' => 'encryption_exceeds_2mib', 'unencrypted' => str_repeat('a', 2_097_152 - 2000)] + $document, ); $test->assertCollectionCount($collection->getNamespace(), 1); }, @@ -488,8 +489,8 @@ static function (self $test, Collection $collection): void { (new CommandObserver())->observe( function () use ($collection): void { $collection->insertMany([ - ['_id' => 'over_2mib_1', 'unencrypted' => str_repeat('a', 2097152)], - ['_id' => 'over_2mib_2', 'unencrypted' => str_repeat('a', 2097152)], + ['_id' => 'over_2mib_1', 'unencrypted' => str_repeat('a', 2_097_152)], + ['_id' => 'over_2mib_2', 'unencrypted' => str_repeat('a', 2_097_152)], ]); }, function ($command) use (&$commands): void { @@ -498,7 +499,7 @@ function ($command) use (&$commands): void { } $commands[] = $command; - } + }, ); $test->assertCount(2, $commands); @@ -513,11 +514,11 @@ function () use ($collection, $document): void { $collection->insertMany([ [ '_id' => 'encryption_exceeds_2mib_1', - 'unencrypted' => str_repeat('a', 2097152 - 2000), + 'unencrypted' => str_repeat('a', 2_097_152 - 2000), ] + $document, [ '_id' => 'encryption_exceeds_2mib_2', - 'unencrypted' => str_repeat('a', 2097152 - 2000), + 'unencrypted' => str_repeat('a', 2_097_152 - 2000), ] + $document, ]); }, @@ -527,7 +528,7 @@ function ($command) use (&$commands): void { } $commands[] = $command; - } + }, ); $test->assertCount(2, $commands); @@ -536,7 +537,7 @@ function ($command) use (&$commands): void { yield 'Test 5' => [ static function (self $test, Collection $collection): void { - $collection->insertOne(['_id' => 'under_16mib', 'unencrypted' => str_repeat('a', 16777216 - 2000)]); + $collection->insertOne(['_id' => 'under_16mib', 'unencrypted' => str_repeat('a', 16_777_216 - 2000)]); $test->assertCollectionCount($collection->getNamespace(), 1); }, ]; @@ -545,7 +546,7 @@ static function (self $test, Collection $collection): void { static function (self $test, Collection $collection, array $document): void { $test->expectException(BulkWriteException::class); $test->expectExceptionMessageMatches('#object to insert too large#'); - $collection->insertOne(['_id' => 'encryption_exceeds_16mib', 'unencrypted' => str_repeat('a', 16777216 - 2000)] + $document); + $collection->insertOne(['_id' => 'encryption_exceeds_16mib', 'unencrypted' => str_repeat('a', 16_777_216 - 2000)] + $document); }, ]; } @@ -579,7 +580,7 @@ public function testBSONSizeLimitsAndBatchSplitting(Closure $test): void $collection = $clientEncrypted->selectCollection('db', 'coll'); - $document = json_decode(file_get_contents(__DIR__ . '/client-side-encryption/limits/limits-doc.json'), true); + $document = json_decode(file_get_contents(__DIR__ . '/client-side-encryption/limits/limits-doc.json'), true, 512, JSON_THROW_ON_ERROR); $test($this, $collection, $document); } @@ -717,7 +718,7 @@ public function testCorpus($schemaMap = true): void $this->assertEquals( $clientEncryption->decrypt($expectedData->value), $clientEncryption->decrypt($actualData->value), - 'Decrypted value for field ' . $fieldName . ' does not match.' + 'Decrypted value for field ' . $fieldName . ' does not match.', ); } else { $this->assertEquals($corpus[$fieldName]->value, $actualData->value, 'Value for field ' . $fieldName . ' does not match original value.'); @@ -1513,7 +1514,7 @@ public function testUniqueIndexOnKeyAltNames(Closure $test): void 'unique' => true, 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), - ] + ], ); $clientEncryption = new ClientEncryption([ diff --git a/tests/SpecTests/CommandExpectations.php b/tests/SpecTests/CommandExpectations.php index 86492a3ed..c293f2f69 100644 --- a/tests/SpecTests/CommandExpectations.php +++ b/tests/SpecTests/CommandExpectations.php @@ -21,31 +21,24 @@ class CommandExpectations implements CommandSubscriber { /** @var array */ - private $actualEvents = []; + private array $actualEvents = []; - /** @var array */ - private $expectedEvents = []; + private array $expectedEvents = []; - /** @var boolean */ - private $ignoreCommandFailed = false; + private bool $ignoreCommandFailed = false; - /** @var boolean */ - private $ignoreCommandStarted = false; + private bool $ignoreCommandStarted = false; - /** @var boolean */ - private $ignoreCommandSucceeded = false; + private bool $ignoreCommandSucceeded = false; - /** @var boolean */ - private $ignoreExtraEvents = false; + private bool $ignoreExtraEvents = false; - /** @var boolean */ - private $ignoreKeyVaultListCollections = false; + private bool $ignoreKeyVaultListCollections = false; /** @var string[] */ - private $ignoredCommandNames = []; + private array $ignoredCommandNames = []; - /** @var Client */ - private $observedClient; + private Client $observedClient; private function __construct(Client $observedClient, array $events) { diff --git a/tests/SpecTests/Context.php b/tests/SpecTests/Context.php index 326061639..18bbd418b 100644 --- a/tests/SpecTests/Context.php +++ b/tests/SpecTests/Context.php @@ -26,47 +26,35 @@ */ final class Context { - /** @var string|null */ - public $bucketName; + public ?string $bucketName = null; - /** @var Client|null */ - private $client; + private ?Client $client = null; - /** @var string|null */ - public $collectionName; + public ?string $collectionName = null; - /** @var string */ - public $databaseName; + public string $databaseName; /** @var array */ - public $defaultWriteOptions = []; + public array $defaultWriteOptions = []; /** @var array */ - public $outcomeReadOptions = []; + public array $outcomeReadOptions = []; - /** @var string|null */ - public $outcomeCollectionName; + public ?string $outcomeCollectionName = null; - /** @var Session|null */ - public $session0; + public ?Session $session0 = null; - /** @var object */ - public $session0Lsid; + public object $session0Lsid; - /** @var Session|null */ - public $session1; + public ?Session $session1 = null; - /** @var object */ - public $session1Lsid; + public object $session1Lsid; - /** @var bool */ - public $useEncryptedClientIfConfigured = false; + public bool $useEncryptedClientIfConfigured = false; - /** @var Client */ - private $internalClient; + private Client $internalClient; - /** @var Client|null */ - private $encryptedClient; + private ?Client $encryptedClient = null; private function __construct(string $databaseName, ?string $collectionName) { @@ -306,7 +294,7 @@ public function getCollection(array $collectionOptions = [], array $databaseOpti $this->databaseName, $this->collectionName, $collectionOptions, - $databaseOptions + $databaseOptions, ); } @@ -446,7 +434,7 @@ public function selectDatabase($databaseName, array $databaseOptions = []) { return $this->getClient()->selectDatabase( $databaseName, - $this->prepareOptions($databaseOptions) + $this->prepareOptions($databaseOptions), ); } diff --git a/tests/SpecTests/DocumentsMatchConstraint.php b/tests/SpecTests/DocumentsMatchConstraint.php index cf5f98ee7..1b3680d3f 100644 --- a/tests/SpecTests/DocumentsMatchConstraint.php +++ b/tests/SpecTests/DocumentsMatchConstraint.php @@ -39,11 +39,9 @@ class DocumentsMatchConstraint extends Constraint { use ConstraintTrait; - /** @var boolean */ - private $ignoreExtraKeysInRoot = false; + private bool $ignoreExtraKeysInRoot = false; - /** @var boolean */ - private $ignoreExtraKeysInEmbedded = false; + private bool $ignoreExtraKeysInEmbedded = false; /** * TODO: This is not currently used, but was preserved from the design of @@ -51,19 +49,15 @@ class DocumentsMatchConstraint extends Constraint * documents as JSON strings. If the TODO item in matches() is implemented * to make document comparisons more efficient, we may consider supporting * this option. - * - * @var boolean */ - private $sortKeys = false; + private bool $sortKeys = false; /** @var BSONArray|BSONDocument */ private $value; - /** @var ComparisonFailure|null */ - private $lastFailure; + private ?ComparisonFailure $lastFailure = null; - /** @var Factory */ - private $comparatorFactory; + private Factory $comparatorFactory; /** * Creates a new constraint. @@ -104,7 +98,7 @@ private function doEvaluate($other, $description = '', $returnResult = false) $this->exporter()->export($this->value), $this->exporter()->export($other), false, - $e->getMessage() + $e->getMessage(), ); } @@ -126,7 +120,7 @@ private function assertBSONType($expectedType, $actualValue): void assertThat( $expectedType, logicalOr(isType('string'), logicalAnd(isInstanceOf(BSONArray::class), containsOnly('string'))), - '$$type requires string or string[]' + '$$type requires string or string[]', ); IsBsonType::anyOf(...(array) $expectedType)->evaluate($actualValue); @@ -143,7 +137,7 @@ private function assertEquals(ArrayObject $expected, ArrayObject $actual, bool $ throw new RuntimeException(sprintf( '%s is not instance of expected class "%s"', $this->exporter()->shortenedExport($actual), - get_class($expected) + get_class($expected), )); } @@ -186,8 +180,8 @@ private function assertEquals(ArrayObject $expected, ArrayObject $actual, bool $ 'Field path "%s": %s is not instance of expected type "%s".', $keyPrefix . $key, $this->exporter()->shortenedExport($actualValue), - $expectedType - ) + $expectedType, + ), ); } @@ -200,7 +194,7 @@ private function assertEquals(ArrayObject $expected, ArrayObject $actual, bool $ '', '', false, - sprintf('Field path "%s": %s', $keyPrefix . $key, $failure->getMessage()) + sprintf('Field path "%s": %s', $keyPrefix . $key, $failure->getMessage()), ); } } diff --git a/tests/SpecTests/DocumentsMatchConstraintTest.php b/tests/SpecTests/DocumentsMatchConstraintTest.php index e71efc5a8..8a238f272 100644 --- a/tests/SpecTests/DocumentsMatchConstraintTest.php +++ b/tests/SpecTests/DocumentsMatchConstraintTest.php @@ -86,7 +86,7 @@ public function provideBSONTypes() $symbol = toPHP(fromJSON('{ "x": {"$symbol": "test"} }'))->x; $dbPointer = toPHP(fromJSON('{ "x": {"$dbPointer": {"$ref": "db.coll", "$id" : { "$oid" : "5a2e78accd485d55b405ac12" } }} }'))->x; $int64 = new Int64(1); - $long = PHP_INT_SIZE == 4 ? new Int64('4294967296') : 4294967296; + $long = PHP_INT_SIZE == 4 ? new Int64('4294967296') : 4_294_967_296; return [ 'double' => ['double', 1.4], diff --git a/tests/SpecTests/ErrorExpectation.php b/tests/SpecTests/ErrorExpectation.php index 56d271427..ba7f9d8f1 100644 --- a/tests/SpecTests/ErrorExpectation.php +++ b/tests/SpecTests/ErrorExpectation.php @@ -22,12 +22,8 @@ */ final class ErrorExpectation { - /** - * @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err - * - * @var array - */ - private static $codeNameMap = [ + /** @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err */ + private static array $codeNameMap = [ 'Interrupted' => 11601, 'MaxTimeMSExpired' => 50, 'NoSuchTransaction' => 251, @@ -35,23 +31,19 @@ final class ErrorExpectation 'WriteConflict' => 112, ]; - /** @var integer */ - private $code; + private int $code; - /** @var string */ - private $codeName; + private string $codeName; - /** @var boolean */ - private $isExpected = false; + private bool $isExpected = false; /** @var string[] */ - private $excludedLabels = []; + private array $excludedLabels = []; /** @var string[] */ - private $includedLabels = []; + private array $includedLabels = []; - /** @var string */ - private $messageContains; + private string $messageContains; private function __construct() { diff --git a/tests/SpecTests/FunctionalTestCase.php b/tests/SpecTests/FunctionalTestCase.php index ffab8a20a..9a5ab4d6d 100644 --- a/tests/SpecTests/FunctionalTestCase.php +++ b/tests/SpecTests/FunctionalTestCase.php @@ -19,6 +19,8 @@ use function sprintf; use function version_compare; +use const JSON_THROW_ON_ERROR; + /** * Base class for spec test runners. * @@ -35,8 +37,7 @@ class FunctionalTestCase extends BaseFunctionalTestCase public const SERVERLESS_FORBID = 'forbid'; public const SERVERLESS_REQUIRE = 'require'; - /** @var Context|null */ - private $context; + private ?Context $context = null; public function setUp(): void { @@ -165,7 +166,7 @@ protected function checkServerRequirements(array $runOn): void $serverVersion = $this->getServerVersion(); $topology = $this->getTopology(); - $this->markTestSkipped(sprintf('Server version "%s" and topology "%s" do not meet test requirements: %s', $serverVersion, $topology, json_encode($runOn))); + $this->markTestSkipped(sprintf('Server version "%s" and topology "%s" do not meet test requirements: %s', $serverVersion, $topology, json_encode($runOn, JSON_THROW_ON_ERROR))); } /** diff --git a/tests/SpecTests/Operation.php b/tests/SpecTests/Operation.php index 9d299bd7b..0950d856f 100644 --- a/tests/SpecTests/Operation.php +++ b/tests/SpecTests/Operation.php @@ -43,32 +43,23 @@ final class Operation public const OBJECT_SESSION1 = 'session1'; public const OBJECT_TEST_RUNNER = 'testRunner'; - /** @var ErrorExpectation|null */ - public $errorExpectation; + public ?ErrorExpectation $errorExpectation = null; - /** @var ResultExpectation|null */ - public $resultExpectation; + public ?ResultExpectation $resultExpectation = null; - /** @var array */ - private $arguments = []; + private array $arguments = []; - /** @var string|null */ - private $collectionName; + private ?string $collectionName = null; - /** @var array */ - private $collectionOptions = []; + private array $collectionOptions = []; - /** @var string|null */ - private $databaseName; + private ?string $databaseName = null; - /** @var array */ - private $databaseOptions = []; + private array $databaseOptions = []; - /** @var string */ - private $name; + private string $name; - /** @var string */ - private $object = self::OBJECT_COLLECTION; + private string $object = self::OBJECT_COLLECTION; private function __construct(stdClass $operation) { @@ -304,7 +295,7 @@ private function executeForClient(Client $client, Context $context) case 'watch': return $client->watch( $args['pipeline'] ?? [], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); default: @@ -327,7 +318,7 @@ private function executeForCollection(Collection $collection, Context $context) case 'aggregate': return $collection->aggregate( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); case 'bulkWrite': @@ -338,19 +329,19 @@ private function executeForCollection(Collection $collection, Context $context) return $collection->bulkWrite( // TODO: Check if self can be used with a private static function array_map([$this, 'prepareBulkWriteRequest'], $args['requests']), - $options + $options, ); case 'createIndex': return $collection->createIndex( $args['keys'], - array_diff_key($args, ['keys' => 1]) + array_diff_key($args, ['keys' => 1]), ); case 'dropIndex': return $collection->dropIndex( $args['name'], - array_diff_key($args, ['name' => 1]) + array_diff_key($args, ['name' => 1]), ); case 'count': @@ -376,7 +367,7 @@ private function executeForCollection(Collection $collection, Context $context) return $collection->distinct( $args['fieldName'], $args['filter'] ?? [], - array_diff_key($args, ['fieldName' => 1, 'filter' => 1]) + array_diff_key($args, ['fieldName' => 1, 'filter' => 1]), ); case 'drop': @@ -421,13 +412,13 @@ private function executeForCollection(Collection $collection, Context $context) return $collection->insertMany( $args['documents'], - $options + $options, ); case 'insertOne': return $collection->insertOne( $args['document'], - array_diff_key($args, ['document' => 1]) + array_diff_key($args, ['document' => 1]), ); case 'listIndexes': @@ -438,13 +429,13 @@ private function executeForCollection(Collection $collection, Context $context) $args['map'], $args['reduce'], $args['out'], - array_diff_key($args, ['map' => 1, 'reduce' => 1, 'out' => 1]) + array_diff_key($args, ['map' => 1, 'reduce' => 1, 'out' => 1]), ); case 'watch': return $collection->watch( $args['pipeline'] ?? [], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); default: @@ -467,19 +458,19 @@ private function executeForDatabase(Database $database, Context $context) case 'aggregate': return $database->aggregate( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); case 'createCollection': return $database->createCollection( $args['collection'], - array_diff_key($args, ['collection' => 1]) + array_diff_key($args, ['collection' => 1]), ); case 'dropCollection': return $database->dropCollection( $args['collection'], - array_diff_key($args, ['collection' => 1]) + array_diff_key($args, ['collection' => 1]), ); case 'listCollectionNames': @@ -491,13 +482,13 @@ private function executeForDatabase(Database $database, Context $context) case 'runCommand': return $database->command( $args['command'], - array_diff_key($args, ['command' => 1]) + array_diff_key($args, ['command' => 1]), )->toArray()[0]; case 'watch': return $database->watch( $args['pipeline'] ?? [], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); default: @@ -568,9 +559,7 @@ private function executeForSession(Session $session, FunctionalTestCase $test, C case 'withTransaction': /** @var self[] $callbackOperations */ - $callbackOperations = array_map(function ($operation) { - return self::fromConvenientTransactions($operation); - }, $this->arguments['callback']->operations); + $callbackOperations = array_map(fn ($operation) => self::fromConvenientTransactions($operation), $this->arguments['callback']->operations); $callback = function () use ($callbackOperations, $test, $context): void { foreach ($callbackOperations as $operation) { @@ -659,10 +648,8 @@ private function executeForTestRunner(FunctionalTestCase $test, Context $context private function getIndexNames(Context $context, string $databaseName, string $collectionName): array { return array_map( - function (IndexInfo $indexInfo) { - return $indexInfo->getName(); - }, - iterator_to_array($context->getInternalClient()->selectCollection($databaseName, $collectionName)->listIndexes()) + fn (IndexInfo $indexInfo) => $indexInfo->getName(), + iterator_to_array($context->getInternalClient()->selectCollection($databaseName, $collectionName)->listIndexes()), ); } diff --git a/tests/SpecTests/PrimaryStepDownSpecTest.php b/tests/SpecTests/PrimaryStepDownSpecTest.php index db028d7d9..7fd0be6e1 100644 --- a/tests/SpecTests/PrimaryStepDownSpecTest.php +++ b/tests/SpecTests/PrimaryStepDownSpecTest.php @@ -24,11 +24,9 @@ class PrimaryStepDownSpecTest extends FunctionalTestCase public const NOT_PRIMARY = 10107; public const SHUTDOWN_IN_PROGRESS = 91; - /** @var Client */ - private $client; + private Client $client; - /** @var Collection */ - private $collection; + private Collection $collection; public function setUp(): void { @@ -233,7 +231,7 @@ function () use ($cursor): void { }, function ($event) use (&$events): void { $events[] = $event; - } + }, ); $this->assertTrue($cursor->valid()); $this->assertCount(1, $events); @@ -272,7 +270,7 @@ private function getTotalConnectionsCreated(?Server $server = null) $cursor = $server->executeCommand( $this->getDatabaseName(), new Command(['serverStatus' => 1]), - new ReadPreference(ReadPreference::PRIMARY) + new ReadPreference(ReadPreference::PRIMARY), ); $cursor->setTypeMap(['root' => 'array', 'document' => 'array']); diff --git a/tests/SpecTests/ReadWriteConcernSpecTest.php b/tests/SpecTests/ReadWriteConcernSpecTest.php index ae5ec27f1..cefbd6720 100644 --- a/tests/SpecTests/ReadWriteConcernSpecTest.php +++ b/tests/SpecTests/ReadWriteConcernSpecTest.php @@ -12,8 +12,7 @@ /** @see https://github.com/mongodb/specifications/tree/master/source/read-write-concern */ class ReadWriteConcernSpecTest extends FunctionalTestCase { - /** @var array */ - private static $incompleteTests = []; + private static array $incompleteTests = []; /** * Assert that the expected and actual command documents match. @@ -57,8 +56,8 @@ public function testReadWriteConcern(stdClass $test, ?array $runOn, array $data, $this->markTestSkipped($test->skipReason); } - $databaseName = $databaseName ?? $this->getDatabaseName(); - $collectionName = $collectionName ?? $this->getCollectionName(); + $databaseName ??= $this->getDatabaseName(); + $collectionName ??= $this->getCollectionName(); $context = Context::fromReadWriteConcern($test, $databaseName, $collectionName); $this->setContext($context); diff --git a/tests/SpecTests/ResultExpectation.php b/tests/SpecTests/ResultExpectation.php index 9626719e2..4fcd0170f 100644 --- a/tests/SpecTests/ResultExpectation.php +++ b/tests/SpecTests/ResultExpectation.php @@ -36,8 +36,7 @@ final class ResultExpectation public const ASSERT_CALLABLE = 11; public const ASSERT_DOCUMENTS_MATCH = 12; - /** @var integer */ - private $assertionType = self::ASSERT_NOTHING; + private int $assertionType = self::ASSERT_NOTHING; /** @var mixed */ private $expectedValue; @@ -167,7 +166,7 @@ public function assert(FunctionalTestCase $test, $actual): void * from the BulkWriteException. */ $test->assertThat($actual, $test->logicalOr( $test->isInstanceOf(BulkWriteResult::class), - $test->isInstanceOf(WriteResult::class) + $test->isInstanceOf(WriteResult::class), )); if (! $actual->isAcknowledged()) { @@ -224,7 +223,7 @@ public function assert(FunctionalTestCase $test, $actual): void * from the BulkWriteException. */ $test->assertThat($actual, $test->logicalOr( $test->isInstanceOf(InsertManyResult::class), - $test->isInstanceOf(WriteResult::class) + $test->isInstanceOf(WriteResult::class), )); if (isset($expected->insertedCount)) { @@ -241,7 +240,7 @@ public function assert(FunctionalTestCase $test, $actual): void case self::ASSERT_INSERTONE: $test->assertThat($actual, $test->logicalOr( $test->isInstanceOf(InsertOneResult::class), - $test->isInstanceOf(WriteResult::class) + $test->isInstanceOf(WriteResult::class), )); if (isset($expected->insertedCount)) { @@ -251,7 +250,7 @@ public function assert(FunctionalTestCase $test, $actual): void if (property_exists($expected, 'insertedId')) { $test->assertSameDocument( ['insertedId' => $expected->insertedId], - ['insertedId' => $actual->getInsertedId()] + ['insertedId' => $actual->getInsertedId()], ); } @@ -261,7 +260,7 @@ public function assert(FunctionalTestCase $test, $actual): void $test->assertIsObject($expected); $test->assertThat($actual, $test->logicalOr( $test->isType('array'), - $test->isType('object') + $test->isType('object'), )); $test->assertMatchesDocument($expected, $actual); break; @@ -281,7 +280,7 @@ public function assert(FunctionalTestCase $test, $actual): void $test->assertIsObject($expected); $test->assertThat($actual, $test->logicalOr( $test->isType('array'), - $test->isType('object') + $test->isType('object'), )); $test->assertSameDocument($expected, $actual); break; @@ -312,7 +311,7 @@ public function assert(FunctionalTestCase $test, $actual): void if (property_exists($expected, 'upsertedId')) { $test->assertSameDocument( ['upsertedId' => $expected->upsertedId], - ['upsertedId' => $actual->getUpsertedId()] + ['upsertedId' => $actual->getUpsertedId()], ); } diff --git a/tests/SpecTests/RetryableReadsSpecTest.php b/tests/SpecTests/RetryableReadsSpecTest.php index 37465aff9..7c6987d01 100644 --- a/tests/SpecTests/RetryableReadsSpecTest.php +++ b/tests/SpecTests/RetryableReadsSpecTest.php @@ -18,15 +18,14 @@ */ class RetryableReadsSpecTest extends FunctionalTestCase { - /** @var array */ - private static $skippedOperations = [ + /** @var array */ + private static array $skippedOperations = [ 'listCollectionObjects' => 'Not implemented', 'listDatabaseObjects' => 'Not implemented', 'listIndexNames' => 'Not implemented', ]; - /** @var array */ - private static $incompleteTests = []; + private static array $incompleteTests = []; /** * Assert that the expected and actual command documents match. diff --git a/tests/SpecTests/RetryableWritesSpecTest.php b/tests/SpecTests/RetryableWritesSpecTest.php index a0506cadc..3b07cdd1e 100644 --- a/tests/SpecTests/RetryableWritesSpecTest.php +++ b/tests/SpecTests/RetryableWritesSpecTest.php @@ -107,7 +107,7 @@ public function testNoWritesPerformedErrorReturnsOriginalError(): void ]); $subscriber = new class ($this) implements CommandSubscriber { - private $testCase; + private FunctionalTestCase $testCase; public function __construct(FunctionalTestCase $testCase) { diff --git a/tests/SpecTests/TransactionsSpecTest.php b/tests/SpecTests/TransactionsSpecTest.php index e88fee203..226ece4ae 100644 --- a/tests/SpecTests/TransactionsSpecTest.php +++ b/tests/SpecTests/TransactionsSpecTest.php @@ -29,10 +29,8 @@ class TransactionsSpecTest extends FunctionalTestCase /** * In addition to the useMultipleMongoses tests, these should all pass * before the driver can be considered compatible with MongoDB 4.2. - * - * @var array */ - private static $incompleteTests = [ + private static array $incompleteTests = [ 'transactions/mongos-recovery-token: commitTransaction retry fails on new mongos' => 'isMaster failpoints cannot be disabled', 'transactions/pin-mongos: remain pinned after non-transient error on commit' => 'Blocked on SPEC-1320', 'transactions/pin-mongos: unpin after transient error within a transaction and commit' => 'isMaster failpoints cannot be disabled', @@ -71,7 +69,7 @@ public static function assertCommandMatches(stdClass $expected, stdClass $actual static::assertObjectHasAttribute('getMore', $actual); static::assertThat($actual->getMore, static::logicalOr( static::isInstanceOf(Int64::class), - static::isType('integer') + static::isType('integer'), )); unset($expected->getMore); } @@ -155,8 +153,8 @@ private function runTransactionTest(stdClass $test, ?array $runOn, array $data, $this->markTestSkipped($test->skipReason); } - $databaseName = $databaseName ?? $this->getDatabaseName(); - $collectionName = $collectionName ?? $this->getCollectionName(); + $databaseName ??= $this->getDatabaseName(); + $collectionName ??= $this->getCollectionName(); $context = Context::fromTransactions($test, $databaseName, $collectionName, $useMultipleMongoses); $this->setContext($context); diff --git a/tests/TestCase.php b/tests/TestCase.php index db356db39..a5d20b837 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -115,7 +115,7 @@ public function assertMatchesDocument($expectedDocument, $actualDocument): void $this->assertEquals( toJSON(fromPHP($normalizedExpectedDocument)), - toJSON(fromPHP($normalizedActualDocument)) + toJSON(fromPHP($normalizedActualDocument)), ); } @@ -132,7 +132,7 @@ public function assertSameDocument($expectedDocument, $actualDocument): void { $this->assertEquals( toJSON(fromPHP($this->normalizeBSON($expectedDocument))), - toJSON(fromPHP($this->normalizeBSON($actualDocument))) + toJSON(fromPHP($this->normalizeBSON($actualDocument))), ); } @@ -146,13 +146,11 @@ public function assertSameDocuments(array $expectedDocuments, $actualDocuments): throw new InvalidArgumentException('$actualDocuments is not an array or Traversable'); } - $normalizeRootDocuments = function ($document) { - return toJSON(fromPHP($this->normalizeBSON($document))); - }; + $normalizeRootDocuments = fn ($document) => toJSON(fromPHP($this->normalizeBSON($document))); $this->assertEquals( array_map($normalizeRootDocuments, $expectedDocuments), - array_map($normalizeRootDocuments, $actualDocuments) + array_map($normalizeRootDocuments, $actualDocuments), ); } @@ -282,7 +280,7 @@ protected function getInvalidReadConcernValues(bool $includeNull = false): array new ReadPreference(ReadPreference::PRIMARY), new WriteConcern(1), ], - $includeNull ? ['null' => null] : [] + $includeNull ? ['null' => null] : [], ); } @@ -302,7 +300,7 @@ protected function getInvalidReadPreferenceValues(bool $includeNull = false): ar new ReadConcern(), new WriteConcern(1), ], - $includeNull ? ['null' => null] : [] + $includeNull ? ['null' => null] : [], ); } @@ -323,7 +321,7 @@ protected function getInvalidSessionValues(bool $includeNull = false): array new ReadPreference(ReadPreference::PRIMARY), new WriteConcern(1), ], - $includeNull ? ['null' => null] : [] + $includeNull ? ['null' => null] : [], ); } @@ -351,7 +349,7 @@ protected function getInvalidWriteConcernValues(bool $includeNull = false): arra new ReadConcern(), new ReadPreference(ReadPreference::PRIMARY), ], - $includeNull ? ['null' => null] : [] + $includeNull ? ['null' => null] : [], ); } @@ -370,9 +368,7 @@ protected function getNamespace(): string */ protected function wrapValuesForDataProvider(array $values): array { - return array_map(function ($value) { - return [$value]; - }, $values); + return array_map(fn ($value) => [$value], $values); } /** diff --git a/tests/UnifiedSpecTests/CollectionData.php b/tests/UnifiedSpecTests/CollectionData.php index 46d7e2ec2..9182babaf 100644 --- a/tests/UnifiedSpecTests/CollectionData.php +++ b/tests/UnifiedSpecTests/CollectionData.php @@ -20,14 +20,11 @@ class CollectionData { - /** @var string */ - private $collectionName; + private string $collectionName; - /** @var string */ - private $databaseName; + private string $databaseName; - /** @var array */ - private $documents; + private array $documents; public function __construct(stdClass $o) { @@ -46,7 +43,7 @@ public function prepareInitialData(Client $client): void { $database = $client->selectDatabase( $this->databaseName, - ['writeConcern' => new WriteConcern(WriteConcern::MAJORITY)] + ['writeConcern' => new WriteConcern(WriteConcern::MAJORITY)], ); $database->dropCollection($this->collectionName); @@ -68,7 +65,7 @@ public function assertOutcome(Client $client): void [ 'readConcern' => new ReadConcern(ReadConcern::LOCAL), 'readPreference' => new ReadPreference(ReadPreference::PRIMARY), - ] + ], ); $cursor = $collection->find([], ['sort' => ['_id' => 1]]); diff --git a/tests/UnifiedSpecTests/Constraint/IsBsonType.php b/tests/UnifiedSpecTests/Constraint/IsBsonType.php index 16cbdb5bc..da88aca39 100644 --- a/tests/UnifiedSpecTests/Constraint/IsBsonType.php +++ b/tests/UnifiedSpecTests/Constraint/IsBsonType.php @@ -42,8 +42,7 @@ final class IsBsonType extends Constraint { use ConstraintTrait; - /** @var array */ - private static $types = [ + private static array $types = [ 'double', 'string', 'object', @@ -68,8 +67,7 @@ final class IsBsonType extends Constraint 'number', ]; - /** @var string */ - private $type; + private string $type; public function __construct(string $type) { @@ -91,9 +89,7 @@ public static function anyOf(string ...$types): Constraint return new self(...$types); } - return LogicalOr::fromConstraints(...array_map(function ($type) { - return new self($type); - }, $types)); + return LogicalOr::fromConstraints(...array_map(fn ($type) => new self($type), $types)); } private function doMatches($other): bool diff --git a/tests/UnifiedSpecTests/Constraint/IsBsonTypeTest.php b/tests/UnifiedSpecTests/Constraint/IsBsonTypeTest.php index 59b40f70d..cdc371cb2 100644 --- a/tests/UnifiedSpecTests/Constraint/IsBsonTypeTest.php +++ b/tests/UnifiedSpecTests/Constraint/IsBsonTypeTest.php @@ -40,7 +40,7 @@ public function provideTypes() $symbol = toPHP(fromJSON('{ "x": {"$symbol": "test"} }'))->x; $dbPointer = toPHP(fromJSON('{ "x": {"$dbPointer": {"$ref": "db.coll", "$id" : { "$oid" : "5a2e78accd485d55b405ac12" } }} }'))->x; $int64 = new Int64(1); - $long = PHP_INT_SIZE == 4 ? new Int64('4294967296') : 4294967296; + $long = PHP_INT_SIZE == 4 ? new Int64('4294967296') : 4_294_967_296; return [ 'double' => ['double', 1.4], diff --git a/tests/UnifiedSpecTests/Constraint/Matches.php b/tests/UnifiedSpecTests/Constraint/Matches.php index 4f1586625..8cc86fa00 100644 --- a/tests/UnifiedSpecTests/Constraint/Matches.php +++ b/tests/UnifiedSpecTests/Constraint/Matches.php @@ -51,23 +51,18 @@ class Matches extends Constraint { use ConstraintTrait; - /** @var EntityMap */ - private $entityMap; + private ?EntityMap $entityMap = null; /** @var mixed */ private $value; - /** @var bool */ - private $allowExtraRootKeys; + private bool $allowExtraRootKeys; - /** @var bool */ - private $allowOperators; + private bool $allowOperators; - /** @var ComparisonFailure|null */ - private $lastFailure; + private ?ComparisonFailure $lastFailure = null; - /** @var Factory */ - private $comparatorFactory; + private Factory $comparatorFactory; public function __construct($value, ?EntityMap $entityMap = null, $allowExtraRootKeys = true, $allowOperators = true) { @@ -102,7 +97,7 @@ private function doEvaluate($other, $description = '', $returnResult = false) $this->exporter()->export($this->value), $this->exporter()->export($other), false, - $e->getMessage() + $e->getMessage(), ); } @@ -168,7 +163,7 @@ private function assertMatchesArray(BSONArray $expected, $actual, string $keyPat $this->assertMatches( $expectedValue, $actual[$key], - (empty($keyPath) ? $key : $keyPath . '.' . $key) + (empty($keyPath) ? $key : $keyPath . '.' . $key), ); } } @@ -222,7 +217,7 @@ private function assertMatchesDocument(BSONDocument $expected, $actual, string $ $this->assertMatches( $expectedValue, $actual[$key], - (empty($keyPath) ? $key : $keyPath . '.' . $key) + (empty($keyPath) ? $key : $keyPath . '.' . $key), ); } @@ -260,7 +255,7 @@ private function assertMatchesOperator(BSONDocument $operator, $actual, string $ assertThat( $operator['$$type'], logicalOr(isType('string'), logicalAnd(isInstanceOf(BSONArray::class), containsOnly('string'))), - '$$type requires string or string[]' + '$$type requires string or string[]', ); $constraint = IsBsonType::anyOf(...(array) $operator['$$type']); @@ -282,7 +277,7 @@ private function assertMatchesOperator(BSONDocument $operator, $actual, string $ $this->assertMatches( self::prepare($this->entityMap[$operator['$$matchesEntity']]), $actual, - $keyPath + $keyPath, ); return; @@ -311,7 +306,7 @@ private function assertMatchesOperator(BSONDocument $operator, $actual, string $ $this->assertMatches( self::prepare($operator['$$unsetOrMatches']), $actual, - $keyPath + $keyPath, ); return; diff --git a/tests/UnifiedSpecTests/Context.php b/tests/UnifiedSpecTests/Context.php index 2300965f3..b5c6843c0 100644 --- a/tests/UnifiedSpecTests/Context.php +++ b/tests/UnifiedSpecTests/Context.php @@ -38,32 +38,25 @@ */ final class Context { - /** @var string */ - private $activeClient; + private ?string $activeClient = null; - /** @var EntityMap */ - private $entityMap; + private EntityMap $entityMap; /** @var EventCollector[] */ - private $eventCollectors = []; + private array $eventCollectors = []; /** @var EventObserver[] */ - private $eventObserversByClient = []; + private array $eventObserversByClient = []; - /** @var Client */ - private $internalClient; + private Client $internalClient; - /** @var boolean */ - private $inLoop = false; + private bool $inLoop = false; - /** @var string */ - private $uri; + private string $uri; - /** @var string */ - private $singleMongosUri; + private string $singleMongosUri; - /** @var string */ - private $multiMongosUri; + private string $multiMongosUri; public function __construct(Client $internalClient, string $uri) { @@ -239,10 +232,10 @@ static function (string $tag): array { return [$key => $value]; }, - $tags + $tags, ); }, - (array) $readPreferenceTags + (array) $readPreferenceTags, ); } @@ -316,7 +309,7 @@ private function createClient(string $id, stdClass $o): void $driverOptions['serverApi'] = new ServerApi( $serverApi->version, $serverApi->strict ?? null, - $serverApi->deprecationErrors ?? null + $serverApi->deprecationErrors ?? null, ); } diff --git a/tests/UnifiedSpecTests/EntityMap.php b/tests/UnifiedSpecTests/EntityMap.php index 0eaddb53f..51cb64c47 100644 --- a/tests/UnifiedSpecTests/EntityMap.php +++ b/tests/UnifiedSpecTests/EntityMap.php @@ -29,8 +29,7 @@ class EntityMap implements ArrayAccess { - /** @var array */ - private $map = []; + private array $map = []; /** * Track lsids so they can be accessed after Session::getLogicalSessionId() @@ -38,10 +37,9 @@ class EntityMap implements ArrayAccess * * @var stdClass[] */ - private $lsidsBySession = []; + private array $lsidsBySession = []; - /** @var Constraint */ - private static $isSupportedType; + private static Constraint $isSupportedType; public function __destruct() { @@ -102,12 +100,10 @@ public function set(string $id, $value, ?string $parentId = null): void $parent = $parentId === null ? null : $this->map[$parentId]; $this->map[$id] = new class ($id, $value, $parent) { - /** @var string */ - public $id; + public string $id; /** @var mixed */ public $value; - /** @var self */ - public $parent; + public ?self $parent; public function __construct(string $id, $value, ?self $parent = null) { @@ -174,19 +170,17 @@ public function getRootClientIdOf(string $id) private static function isSupportedType(): Constraint { - if (self::$isSupportedType === null) { - self::$isSupportedType = logicalOr( - isInstanceOf(Client::class), - isInstanceOf(ClientEncryption::class), - isInstanceOf(Database::class), - isInstanceOf(Collection::class), - isInstanceOf(Session::class), - isInstanceOf(Bucket::class), - isInstanceOf(ChangeStream::class), - isInstanceOf(Cursor::class), - IsBsonType::any() - ); - } + self::$isSupportedType ??= logicalOr( + isInstanceOf(Client::class), + isInstanceOf(ClientEncryption::class), + isInstanceOf(Database::class), + isInstanceOf(Collection::class), + isInstanceOf(Session::class), + isInstanceOf(Bucket::class), + isInstanceOf(ChangeStream::class), + isInstanceOf(Cursor::class), + IsBsonType::any(), + ); return self::$isSupportedType; } diff --git a/tests/UnifiedSpecTests/EventCollector.php b/tests/UnifiedSpecTests/EventCollector.php index 8ffcd6287..0a688e41a 100644 --- a/tests/UnifiedSpecTests/EventCollector.php +++ b/tests/UnifiedSpecTests/EventCollector.php @@ -29,8 +29,7 @@ */ final class EventCollector implements CommandSubscriber { - /** @var array */ - private static $supportedEvents = [ + private static array $supportedEvents = [ 'PoolCreatedEvent' => null, 'PoolReadyEvent' => null, 'PoolClearedEvent' => null, @@ -47,17 +46,13 @@ final class EventCollector implements CommandSubscriber 'CommandFailedEvent' => CommandFailedEvent::class, ]; - /** @var string */ - private $clientId; + private string $clientId; - /** @var Context */ - private $context; + private Context $context; - /** @var array */ - private $collectEvents = []; + private array $collectEvents = []; - /** @var BSONArray */ - private $eventList; + private BSONArray $eventList; public function __construct(BSONArray $eventList, array $collectEvents, string $clientId, Context $context) { diff --git a/tests/UnifiedSpecTests/EventObserver.php b/tests/UnifiedSpecTests/EventObserver.php index 6995dd995..dea4145fa 100644 --- a/tests/UnifiedSpecTests/EventObserver.php +++ b/tests/UnifiedSpecTests/EventObserver.php @@ -44,9 +44,8 @@ final class EventObserver implements CommandSubscriber * documents should be redacted). * * @see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst#security - * @var array */ - private static $sensitiveCommands = [ + private static array $sensitiveCommands = [ 'authenticate' => 1, 'saslStart' => 1, 'saslContinue' => 1, @@ -63,16 +62,14 @@ final class EventObserver implements CommandSubscriber * document includes a speculativeAuthenticate field. * * @see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst#security - * @var array */ - private static $sensitiveCommandsWithSpeculativeAuthenticate = [ + private static array $sensitiveCommandsWithSpeculativeAuthenticate = [ 'ismaster' => 1, 'isMaster' => 1, 'hello' => 1, ]; - /** @var array */ - private static $supportedEvents = [ + private static array $supportedEvents = [ 'commandStartedEvent' => CommandStartedEvent::class, 'commandSucceededEvent' => CommandSucceededEvent::class, 'commandFailedEvent' => CommandFailedEvent::class, @@ -81,10 +78,8 @@ final class EventObserver implements CommandSubscriber /** * These events are defined in the specification but unsupported by PHPLIB * (e.g. CMAP events). - * - * @var array */ - private static $unsupportedEvents = [ + private static array $unsupportedEvents = [ 'poolCreatedEvent' => 1, 'poolReadyEvent' => 1, 'poolClearedEvent' => 1, @@ -98,28 +93,21 @@ final class EventObserver implements CommandSubscriber 'connectionCheckedInEvent' => 1, ]; - /** @var array */ - private $actualEvents = []; + private array $actualEvents = []; - /** @var string */ - private $clientId; + private string $clientId; - /** @var Context */ - private $context; + private Context $context; /** * The configureFailPoint command (used by failPoint and targetedFailPoint * operations) is always ignored. - * - * @var array */ - private $ignoreCommands = ['configureFailPoint' => 1]; + private array $ignoreCommands = ['configureFailPoint' => 1]; - /** @var array */ - private $observeEvents = []; + private array $observeEvents = []; - /** @var bool */ - private $observeSensitiveCommands; + private bool $observeSensitiveCommands; public function __construct(array $observeEvents, array $ignoreCommands, bool $observeSensitiveCommands, string $clientId, Context $context) { diff --git a/tests/UnifiedSpecTests/ExpectedError.php b/tests/UnifiedSpecTests/ExpectedError.php index a57ef341a..af28b0ece 100644 --- a/tests/UnifiedSpecTests/ExpectedError.php +++ b/tests/UnifiedSpecTests/ExpectedError.php @@ -39,11 +39,8 @@ final class ExpectedError { - /** - * @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err - * @var array - */ - private static $codeNameMap = [ + /** @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err */ + private static array $codeNameMap = [ 'Interrupted' => 11601, 'MaxTimeMSExpired' => 50, 'NoSuchTransaction' => 251, @@ -51,32 +48,23 @@ final class ExpectedError 'WriteConflict' => 112, ]; - /** @var bool */ - private $isError = false; + private bool $isError = false; - /** @var bool|null */ - private $isClientError; + private ?bool $isClientError = null; - /** @var string|null */ - private $messageContains; + private ?string $messageContains = null; - /** @var int|null */ - private $code; + private ?int $code = null; - /** @var string|null */ - private $codeName; + private ?string $codeName = null; - /** @var Matches|null */ - private $matchesResultDocument; + private ?Matches $matchesResultDocument = null; - /** @var array */ - private $includedLabels = []; + private array $includedLabels = []; - /** @var array */ - private $excludedLabels = []; + private array $excludedLabels = []; - /** @var ExpectedResult|null */ - private $expectedResult; + private ?ExpectedResult $expectedResult = null; public function __construct(?stdClass $o, EntityMap $entityMap) { diff --git a/tests/UnifiedSpecTests/ExpectedResult.php b/tests/UnifiedSpecTests/ExpectedResult.php index 618a2983d..88166eea5 100644 --- a/tests/UnifiedSpecTests/ExpectedResult.php +++ b/tests/UnifiedSpecTests/ExpectedResult.php @@ -17,19 +17,15 @@ final class ExpectedResult { - /** @var Matches */ - private $constraint; + private ?Matches $constraint = null; - /** @var EntityMap */ - private $entityMap; + private EntityMap $entityMap; /** * ID of the entity yielding the result. This is mainly used to associate * entities with a root client for collation of observed events. - * - * @var ?string */ - private $yieldingEntityId; + private ?string $yieldingEntityId = null; public function __construct(stdClass $o, EntityMap $entityMap, ?string $yieldingEntityId = null) { diff --git a/tests/UnifiedSpecTests/FailPointObserver.php b/tests/UnifiedSpecTests/FailPointObserver.php index 7f8c3a9e6..3d845887b 100644 --- a/tests/UnifiedSpecTests/FailPointObserver.php +++ b/tests/UnifiedSpecTests/FailPointObserver.php @@ -14,7 +14,7 @@ class FailPointObserver implements CommandSubscriber { /** @var array */ - private $failPointsAndServers = []; + private array $failPointsAndServers = []; /** @see https://php.net/manual/en/mongodb-driver-monitoring-commandsubscriber.commandfailed.php */ public function commandFailed(CommandFailedEvent $event): void diff --git a/tests/UnifiedSpecTests/Loop.php b/tests/UnifiedSpecTests/Loop.php index 3351e22b8..69c0b9a79 100644 --- a/tests/UnifiedSpecTests/Loop.php +++ b/tests/UnifiedSpecTests/Loop.php @@ -22,29 +22,21 @@ final class Loop { - /** @var boolean */ - private static $allowIteration = true; + private static bool $allowIteration = true; - /** @var integer */ - private static $sleepUsecBetweenIterations = 0; + private static int $sleepUsecBetweenIterations = 0; - /** @var Context */ - private $context; + private Context $context; - /** @var array */ - private $operations = []; + private array $operations = []; - /** @var BSONArray */ - private $errorList; + private ?BSONArray $errorList = null; - /** @var BSONArray */ - private $failureList; + private ?BSONArray $failureList = null; - /** @var string */ - private $numSuccessfulOperationsEntityId; + private string $numSuccessfulOperationsEntityId; - /** @var string */ - private $numIterationsEntityId; + private string $numIterationsEntityId; public function __construct(array $operations, Context $context, array $options = []) { diff --git a/tests/UnifiedSpecTests/Operation.php b/tests/UnifiedSpecTests/Operation.php index d2793a239..2eadc7eb0 100644 --- a/tests/UnifiedSpecTests/Operation.php +++ b/tests/UnifiedSpecTests/Operation.php @@ -67,35 +67,25 @@ final class Operation { public const OBJECT_TEST_RUNNER = 'testRunner'; - /** @var bool */ - private $isTestRunnerOperation; + private bool $isTestRunnerOperation; - /** @var string */ - private $name; + private string $name; - /** @var ?string */ - private $object; + private ?string $object = null; - /** @var array */ - private $arguments = []; + private array $arguments = []; - /** @var Context */ - private $context; + private Context $context; - /** @var EntityMap */ - private $entityMap; + private EntityMap $entityMap; - /** @var ExpectedError */ - private $expectError; + private ExpectedError $expectError; - /** @var ExpectedResult */ - private $expectResult; + private ExpectedResult $expectResult; - /** @var bool */ - private $ignoreResultAndError; + private bool $ignoreResultAndError; - /** @var string */ - private $saveResultAsEntity; + private ?string $saveResultAsEntity = null; public function __construct(stdClass $o, Context $context) { @@ -260,7 +250,7 @@ private function executeForClient(Client $client) return $client->watch( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); case 'listDatabaseNames': @@ -268,10 +258,8 @@ private function executeForClient(Client $client) case 'listDatabases': return array_map( - function (DatabaseInfo $info) { - return $info->__debugInfo(); - }, - iterator_to_array($client->listDatabases($args)) + fn (DatabaseInfo $info) => $info->__debugInfo(), + iterator_to_array($client->listDatabases($args)), ); default: @@ -346,7 +334,7 @@ private function executeForCollection(Collection $collection) return iterator_to_array($collection->aggregate( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), )); case 'bulkWrite': @@ -355,12 +343,10 @@ private function executeForCollection(Collection $collection) return $collection->bulkWrite( array_map( - static function ($request) { - return self::prepareBulkWriteRequest($request); - }, - $args['requests'] + static fn ($request) => self::prepareBulkWriteRequest($request), + $args['requests'], ), - array_diff_key($args, ['requests' => 1]) + array_diff_key($args, ['requests' => 1]), ); case 'createChangeStream': @@ -369,7 +355,7 @@ static function ($request) { return $collection->watch( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); case 'createFindCursor': @@ -378,7 +364,7 @@ static function ($request) { return $collection->find( $args['filter'], - array_diff_key($args, ['filter' => 1]) + array_diff_key($args, ['filter' => 1]), ); case 'createIndex': @@ -387,7 +373,7 @@ static function ($request) { return $collection->createIndex( $args['keys'], - array_diff_key($args, ['keys' => 1]) + array_diff_key($args, ['keys' => 1]), ); case 'dropIndex': @@ -396,7 +382,7 @@ static function ($request) { return $collection->dropIndex( $args['name'], - array_diff_key($args, ['name' => 1]) + array_diff_key($args, ['name' => 1]), ); case 'count': @@ -437,7 +423,7 @@ static function ($request) { return $collection->distinct( $args['fieldName'], $args['filter'], - array_diff_key($args, ['fieldName' => 1, 'filter' => 1]) + array_diff_key($args, ['fieldName' => 1, 'filter' => 1]), ); case 'drop': @@ -449,7 +435,7 @@ static function ($request) { return iterator_to_array($collection->find( $args['filter'], - array_diff_key($args, ['filter' => 1]) + array_diff_key($args, ['filter' => 1]), )); case 'findOne': @@ -458,7 +444,7 @@ static function ($request) { return $collection->findOne( $args['filter'], - array_diff_key($args, ['filter' => 1]) + array_diff_key($args, ['filter' => 1]), ); case 'findOneAndReplace': @@ -512,7 +498,7 @@ static function ($request) { return $collection->insertMany( $args['documents'], - array_diff_key($args, ['documents' => 1]) + array_diff_key($args, ['documents' => 1]), ); case 'insertOne': @@ -521,15 +507,13 @@ static function ($request) { return $collection->insertOne( $args['document'], - array_diff_key($args, ['document' => 1]) + array_diff_key($args, ['document' => 1]), ); case 'listIndexes': return array_map( - function (IndexInfo $info) { - return $info->__debugInfo(); - }, - iterator_to_array($collection->listIndexes($args)) + fn (IndexInfo $info) => $info->__debugInfo(), + iterator_to_array($collection->listIndexes($args)), ); case 'mapReduce': @@ -544,7 +528,7 @@ function (IndexInfo $info) { $args['map'], $args['reduce'], $args['out'], - array_diff_key($args, ['map' => 1, 'reduce' => 1, 'out' => 1]) + array_diff_key($args, ['map' => 1, 'reduce' => 1, 'out' => 1]), ); case 'rename': @@ -554,7 +538,7 @@ function (IndexInfo $info) { return $collection->rename( $args['to'], null, /* $toDatabaseName */ - array_diff_key($args, ['to' => 1]) + array_diff_key($args, ['to' => 1]), ); default: @@ -622,7 +606,7 @@ private function executeForDatabase(Database $database) return iterator_to_array($database->aggregate( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), )); case 'createChangeStream': @@ -631,7 +615,7 @@ private function executeForDatabase(Database $database) return $database->watch( $args['pipeline'], - array_diff_key($args, ['pipeline' => 1]) + array_diff_key($args, ['pipeline' => 1]), ); case 'createCollection': @@ -640,7 +624,7 @@ private function executeForDatabase(Database $database) return $database->createCollection( $args['collection'], - array_diff_key($args, ['collection' => 1]) + array_diff_key($args, ['collection' => 1]), ); case 'dropCollection': @@ -649,7 +633,7 @@ private function executeForDatabase(Database $database) return $database->dropCollection( $args['collection'], - array_diff_key($args, ['collection' => 1]) + array_diff_key($args, ['collection' => 1]), ); case 'listCollectionNames': @@ -657,10 +641,8 @@ private function executeForDatabase(Database $database) case 'listCollections': return array_map( - function (CollectionInfo $info) { - return $info->__debugInfo(); - }, - iterator_to_array($database->listCollections($args)) + fn (CollectionInfo $info) => $info->__debugInfo(), + iterator_to_array($database->listCollections($args)), ); case 'modifyCollection': @@ -757,7 +739,7 @@ private function executeForBucket(Bucket $bucket) return stream_get_contents($bucket->openDownloadStreamByName( $args['filename'], - array_diff_key($args, ['filename' => 1]) + array_diff_key($args, ['filename' => 1]), )); case 'download': @@ -778,7 +760,7 @@ private function executeForBucket(Bucket $bucket) return $bucket->uploadFromStream( $args['filename'], $args['source'], - array_diff_key($args, ['filename' => 1, 'source' => 1]) + array_diff_key($args, ['filename' => 1, 'source' => 1]), ); default: @@ -907,10 +889,8 @@ private function executeForTestRunner() private function getIndexNames(string $databaseName, string $collectionName): array { return array_map( - function (IndexInfo $indexInfo) { - return $indexInfo->getName(); - }, - iterator_to_array($this->context->getInternalClient()->selectCollection($databaseName, $collectionName)->listIndexes()) + fn (IndexInfo $indexInfo) => $indexInfo->getName(), + iterator_to_array($this->context->getInternalClient()->selectCollection($databaseName, $collectionName)->listIndexes()), ); } diff --git a/tests/UnifiedSpecTests/RunOnRequirement.php b/tests/UnifiedSpecTests/RunOnRequirement.php index 4290bda9d..950751fe8 100644 --- a/tests/UnifiedSpecTests/RunOnRequirement.php +++ b/tests/UnifiedSpecTests/RunOnRequirement.php @@ -31,29 +31,21 @@ class RunOnRequirement public const VERSION_PATTERN = '/^[0-9]+(\\.[0-9]+){1,2}$/'; - /** @var string */ - private $minServerVersion; + private ?string $minServerVersion = null; - /** @var string */ - private $maxServerVersion; + private ?string $maxServerVersion = null; - /** @var array */ - private $topologies; + private ?array $topologies = null; - /** @var stdClass */ - private $serverParameters; + private ?object $serverParameters = null; - /** @var bool */ - private $auth; + private ?bool $auth = null; - /** @var string */ - private $serverless; + private ?string $serverless = null; - /** @var bool */ - private $csfle; + private ?bool $csfle = null; - /** @var array */ - private static $supportedTopologies = [ + private static array $supportedTopologies = [ self::TOPOLOGY_SINGLE, self::TOPOLOGY_REPLICASET, self::TOPOLOGY_SHARDED, @@ -61,8 +53,7 @@ class RunOnRequirement self::TOPOLOGY_LOAD_BALANCED, ]; - /** @var array */ - private static $supportedServerless = [ + private static array $supportedServerless = [ self::SERVERLESS_REQUIRE, self::SERVERLESS_FORBID, self::SERVERLESS_ALLOW, diff --git a/tests/UnifiedSpecTests/ServerParameterHelper.php b/tests/UnifiedSpecTests/ServerParameterHelper.php index 6e14e8faa..8f716fa67 100644 --- a/tests/UnifiedSpecTests/ServerParameterHelper.php +++ b/tests/UnifiedSpecTests/ServerParameterHelper.php @@ -10,17 +10,14 @@ final class ServerParameterHelper { - /** @var Client */ - private $client; + private Client $client; /** @var array */ - private $parameters = []; + private array $parameters = []; - /** @var bool */ - private $fetchAllParametersFailed = false; + private bool $fetchAllParametersFailed = false; - /** @var bool */ - private $allParametersFetched = false; + private bool $allParametersFetched = false; public function __construct(Client $client) { @@ -66,7 +63,7 @@ private function fetchAllParameters(): void 'document' => 'array', 'array' => 'array', ], - ] + ], ); $this->parameters = $cursor->toArray()[0]; @@ -91,7 +88,7 @@ private function fetchSingleParameter(string $parameter): void 'document' => 'array', 'array' => 'array', ], - ] + ], ); $this->parameters[$parameter] = $cursor->toArray()[0][$parameter]; diff --git a/tests/UnifiedSpecTests/UnifiedSpecTest.php b/tests/UnifiedSpecTests/UnifiedSpecTest.php index 730e59e0d..1559ee439 100644 --- a/tests/UnifiedSpecTests/UnifiedSpecTest.php +++ b/tests/UnifiedSpecTests/UnifiedSpecTest.php @@ -20,8 +20,7 @@ */ class UnifiedSpecTest extends FunctionalTestCase { - /** @var array */ - private static $incompleteTests = [ + private static array $incompleteTests = [ // Many load balancer tests use CMAP events and/or assertNumberConnectionsCheckedOut 'load-balancers/cursors are correctly pinned to connections for load-balanced clusters: no connection is pinned if all documents are returned in the initial batch' => 'PHPC does not implement CMAP', 'load-balancers/cursors are correctly pinned to connections for load-balanced clusters: pinned connections are returned when the cursor is drained' => 'PHPC does not implement CMAP', @@ -67,8 +66,7 @@ class UnifiedSpecTest extends FunctionalTestCase 'valid-pass/matches-lte-operator: special lte matching operator' => 'CSOT is not yet implemented (PHPC-1760)', ]; - /** @var UnifiedTestRunner */ - private static $runner; + private static UnifiedTestRunner $runner; public static function setUpBeforeClass(): void { diff --git a/tests/UnifiedSpecTests/UnifiedTestCase.php b/tests/UnifiedSpecTests/UnifiedTestCase.php index ced1adec0..8a6e69aba 100644 --- a/tests/UnifiedSpecTests/UnifiedTestCase.php +++ b/tests/UnifiedSpecTests/UnifiedTestCase.php @@ -25,20 +25,15 @@ */ final class UnifiedTestCase implements IteratorAggregate { - /** @var stdClass */ - private $test; + private stdClass $test; - /** @var string */ - private $schemaVersion; + private string $schemaVersion; - /** @var array|null */ - private $runOnRequirements; + private ?array $runOnRequirements = null; - /** @var array|null */ - private $createEntities; + private ?array $createEntities = null; - /** @var array|null */ - private $initialData; + private ?array $initialData = null; private function __construct(stdClass $test, string $schemaVersion, ?array $runOnRequirements = null, ?array $createEntities = null, ?array $initialData = null) { diff --git a/tests/UnifiedSpecTests/UnifiedTestRunner.php b/tests/UnifiedSpecTests/UnifiedTestRunner.php index 40f2c3046..4c947b752 100644 --- a/tests/UnifiedSpecTests/UnifiedTestRunner.php +++ b/tests/UnifiedSpecTests/UnifiedTestRunner.php @@ -2,6 +2,7 @@ namespace MongoDB\Tests\UnifiedSpecTests; +use MongoDB\Client; use MongoDB\Collection; use MongoDB\Driver\Exception\ServerException; use MongoDB\Driver\Server; @@ -60,26 +61,20 @@ final class UnifiedTestRunner * however, syntax from 1.9, 1.10, and 1.11 has not been implemented. */ public const MAX_SCHEMA_VERSION = '1.12'; - /** @var MongoDB\Client */ - private $internalClient; + private Client $internalClient; - /** @var string */ - private $internalClientUri; + private string $internalClientUri; - /** @var bool */ - private $allowKillAllSessions = true; + private bool $allowKillAllSessions = true; - /** @var EntityMap */ - private $entityMap; + private ?EntityMap $entityMap = null; /** @var callable(EntityMap):void */ private $entityMapObserver; - /** @var FailPointObserver */ - private $failPointObserver; + private ?FailPointObserver $failPointObserver = null; - /** @var ServerParameterHelper */ - private $serverParameterHelper; + private ServerParameterHelper $serverParameterHelper; public function __construct(string $internalClientUri) { @@ -266,7 +261,7 @@ private function checkRunOnRequirements(array $runOnRequirements): void 'Server (version=%s, topology=%s, auth=%s) does not meet test requirements', $cachedIsSatisfiedArgs[0], $cachedIsSatisfiedArgs[1], - $cachedIsSatisfiedArgs[3] ? 'yes' : 'no' + $cachedIsSatisfiedArgs[3] ? 'yes' : 'no', )); } diff --git a/tests/UnifiedSpecTests/Util.php b/tests/UnifiedSpecTests/Util.php index 351d9ad0f..84aa15129 100644 --- a/tests/UnifiedSpecTests/Util.php +++ b/tests/UnifiedSpecTests/Util.php @@ -38,7 +38,7 @@ final class Util /** * Array to fill, which contains the schema of allowed attributes for operations. */ - private static $args = [ + private static array $args = [ Operation::OBJECT_TEST_RUNNER => [ 'assertCollectionExists' => ['databaseName', 'collectionName'], 'assertCollectionNotExists' => ['databaseName', 'collectionName'], diff --git a/tools/connect.php b/tools/connect.php index 121f727c7..136ac106e 100644 --- a/tools/connect.php +++ b/tools/connect.php @@ -92,7 +92,7 @@ function connect(string $host, bool $ssl): void 'admin.$cmd', /* namespace */ 0, /* numberToSkip */ 1, /* numberToReturn */ - hex2bin('130000001069734d6173746572000100000000') /* { "isMaster": 1 } */ + hex2bin('130000001069734d6173746572000100000000'), /* { "isMaster": 1 } */ ); $requestLength = 16 /* MsgHeader length */ + strlen($request); $header = pack('V4', $requestLength, 0 /* requestID */, 0 /* responseTo */, 2004 /* OP_QUERY */); From 99c2d47ecbe71d6927e8a7650610501014033419 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 08:38:04 +0200 Subject: [PATCH 03/11] Skip rector rule creating adding wrong property type --- rector.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rector.php b/rector.php index 06d194141..8c744016d 100644 --- a/rector.php +++ b/rector.php @@ -5,6 +5,7 @@ use Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector; use Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector; use Rector\Set\ValueObject\LevelSetList; +use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->paths([ @@ -26,6 +27,10 @@ RemoveExtraParametersRector::class => [ __DIR__ . '/src/Operation/', ], + // Assigns wrong type due to outdated PHPStan stubs + TypedPropertyFromAssignsRector::class => [ + __DIR__ . '/src/Model/BSONIterator.php', + ], ]); // All classes are public API by default, unless marked with @internal. From fbb04e462333d25e0de3884da946082ee40b2b81 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 08:45:38 +0200 Subject: [PATCH 04/11] Add more missing property types --- phpcs.xml.dist | 3 --- src/ChangeStream.php | 3 +-- src/Codec/CodecLibrary.php | 8 ++++---- src/Collection.php | 12 ++++-------- src/Database.php | 12 ++++-------- src/GridFS/Bucket.php | 12 ++++-------- src/MapReduceResult.php | 6 ++---- src/Model/CallbackIterator.php | 2 +- src/Operation/CreateEncryptedCollection.php | 2 +- src/Operation/DropEncryptedCollection.php | 2 +- src/Operation/InsertMany.php | 2 +- src/Operation/Watch.php | 6 ++---- tests/FunctionalTestCase.php | 1 - tests/SpecTests/CommandExpectations.php | 3 +-- tests/SpecTests/Context.php | 2 -- tests/SpecTests/ErrorExpectation.php | 4 ++-- tests/SpecTests/Operation.php | 2 +- tests/UnifiedSpecTests/Context.php | 4 ++-- tests/UnifiedSpecTests/EntityMap.php | 2 +- tests/UnifiedSpecTests/FailPointObserver.php | 1 - 20 files changed, 32 insertions(+), 57 deletions(-) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index dcbfb45e6..266c367d4 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -152,9 +152,6 @@ - - src - src diff --git a/src/ChangeStream.php b/src/ChangeStream.php index 09ebf7a6a..e94160874 100644 --- a/src/ChangeStream.php +++ b/src/ChangeStream.php @@ -71,8 +71,7 @@ class ChangeStream implements Iterator /** @var ResumeCallable|null */ private $resumeCallable; - /** @var ChangeStreamIterator */ - private $iterator; + private ChangeStreamIterator $iterator; private int $key = 0; diff --git a/src/Codec/CodecLibrary.php b/src/Codec/CodecLibrary.php index 82acb2187..d3cbf5461 100644 --- a/src/Codec/CodecLibrary.php +++ b/src/Codec/CodecLibrary.php @@ -25,11 +25,11 @@ class CodecLibrary implements Codec use DecodeIfSupported; use EncodeIfSupported; - /** @var array */ - private $decoders = []; + /** @var list */ + private array $decoders = []; - /** @var array */ - private $encoders = []; + /** @var list */ + private array $encoders = []; /** @param Decoder|Encoder $items */ public function __construct(...$items) diff --git a/src/Collection.php b/src/Collection.php index a6d911f20..41833a24e 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -83,17 +83,13 @@ class Collection private Manager $manager; - /** @var ReadConcern */ - private $readConcern; + private ReadConcern $readConcern; - /** @var ReadPreference */ - private $readPreference; + private ReadPreference $readPreference; - /** @var array */ - private $typeMap; + private array $typeMap; - /** @var WriteConcern */ - private $writeConcern; + private WriteConcern $writeConcern; /** * Constructs new Collection instance. diff --git a/src/Database.php b/src/Database.php index 9804b1b67..c4057356f 100644 --- a/src/Database.php +++ b/src/Database.php @@ -65,17 +65,13 @@ class Database private Manager $manager; - /** @var ReadConcern */ - private $readConcern; + private ReadConcern $readConcern; - /** @var ReadPreference */ - private $readPreference; + private ReadPreference $readPreference; - /** @var array */ - private $typeMap; + private array $typeMap; - /** @var WriteConcern */ - private $writeConcern; + private WriteConcern $writeConcern; /** * Constructs new Database instance. diff --git a/src/GridFS/Bucket.php b/src/GridFS/Bucket.php index 4d2c6da44..9b46d7b91 100644 --- a/src/GridFS/Bucket.php +++ b/src/GridFS/Bucket.php @@ -86,17 +86,13 @@ class Bucket private int $chunkSizeBytes; - /** @var ReadConcern */ - private $readConcern; + private ReadConcern $readConcern; - /** @var ReadPreference */ - private $readPreference; + private ReadPreference $readPreference; - /** @var array */ - private $typeMap; + private array $typeMap; - /** @var WriteConcern */ - private $writeConcern; + private WriteConcern $writeConcern; /** * Constructs a GridFS bucket. diff --git a/src/MapReduceResult.php b/src/MapReduceResult.php index 7095f5e2d..61f5d2667 100644 --- a/src/MapReduceResult.php +++ b/src/MapReduceResult.php @@ -41,11 +41,9 @@ class MapReduceResult implements IteratorAggregate private int $executionTimeMS; - /** @var array */ - private $counts; + private array $counts; - /** @var array */ - private $timing; + private array $timing; /** * @internal diff --git a/src/Model/CallbackIterator.php b/src/Model/CallbackIterator.php index 49d04ce48..ea429ccbc 100644 --- a/src/Model/CallbackIterator.php +++ b/src/Model/CallbackIterator.php @@ -40,7 +40,7 @@ class CallbackIterator implements Iterator private $callback; /** @var Iterator */ - private $iterator; + private Iterator $iterator; /** * @param Traversable $traversable diff --git a/src/Operation/CreateEncryptedCollection.php b/src/Operation/CreateEncryptedCollection.php index 973720199..113b83171 100644 --- a/src/Operation/CreateEncryptedCollection.php +++ b/src/Operation/CreateEncryptedCollection.php @@ -54,7 +54,7 @@ class CreateEncryptedCollection implements Executable private CreateCollection $createCollection; - /** @var CreateCollection[] */ + /** @var list */ private array $createMetadataCollections; private CreateIndexes $createSafeContentIndex; diff --git a/src/Operation/DropEncryptedCollection.php b/src/Operation/DropEncryptedCollection.php index 381ab8af5..491a8e9eb 100644 --- a/src/Operation/DropEncryptedCollection.php +++ b/src/Operation/DropEncryptedCollection.php @@ -41,7 +41,7 @@ class DropEncryptedCollection implements Executable { private DropCollection $dropCollection; - /** @var DropCollection[] */ + /** @var list */ private array $dropMetadataCollections; /** diff --git a/src/Operation/InsertMany.php b/src/Operation/InsertMany.php index db9bd36f1..b70daf90d 100644 --- a/src/Operation/InsertMany.php +++ b/src/Operation/InsertMany.php @@ -43,7 +43,7 @@ class InsertMany implements Executable private string $collectionName; - /** @var object[]|array[] */ + /** @var list|list */ private array $documents; private array $options; diff --git a/src/Operation/Watch.php b/src/Operation/Watch.php index 6d0418c0c..8a5d50f40 100644 --- a/src/Operation/Watch.php +++ b/src/Operation/Watch.php @@ -72,11 +72,9 @@ class Watch implements Executable, /* @internal */ CommandSubscriber private Aggregate $aggregate; - /** @var array */ - private $aggregateOptions; + private array $aggregateOptions; - /** @var array */ - private $changeStreamOptions; + private array $changeStreamOptions; private ?string $collectionName = null; diff --git a/tests/FunctionalTestCase.php b/tests/FunctionalTestCase.php index 0b603ed23..1820641d7 100644 --- a/tests/FunctionalTestCase.php +++ b/tests/FunctionalTestCase.php @@ -54,7 +54,6 @@ abstract class FunctionalTestCase extends TestCase { protected Manager $manager; - /** @var array */ private array $configuredFailPoints = []; /** @var array{int,{Collection,array}} */ diff --git a/tests/SpecTests/CommandExpectations.php b/tests/SpecTests/CommandExpectations.php index c293f2f69..76a3a0a0a 100644 --- a/tests/SpecTests/CommandExpectations.php +++ b/tests/SpecTests/CommandExpectations.php @@ -20,7 +20,6 @@ */ class CommandExpectations implements CommandSubscriber { - /** @var array */ private array $actualEvents = []; private array $expectedEvents = []; @@ -35,7 +34,7 @@ class CommandExpectations implements CommandSubscriber private bool $ignoreKeyVaultListCollections = false; - /** @var string[] */ + /** @var list */ private array $ignoredCommandNames = []; private Client $observedClient; diff --git a/tests/SpecTests/Context.php b/tests/SpecTests/Context.php index 18bbd418b..924f1b6ad 100644 --- a/tests/SpecTests/Context.php +++ b/tests/SpecTests/Context.php @@ -34,10 +34,8 @@ final class Context public string $databaseName; - /** @var array */ public array $defaultWriteOptions = []; - /** @var array */ public array $outcomeReadOptions = []; public ?string $outcomeCollectionName = null; diff --git a/tests/SpecTests/ErrorExpectation.php b/tests/SpecTests/ErrorExpectation.php index ba7f9d8f1..1b6c77c81 100644 --- a/tests/SpecTests/ErrorExpectation.php +++ b/tests/SpecTests/ErrorExpectation.php @@ -37,10 +37,10 @@ final class ErrorExpectation private bool $isExpected = false; - /** @var string[] */ + /** @var list */ private array $excludedLabels = []; - /** @var string[] */ + /** @var list */ private array $includedLabels = []; private string $messageContains; diff --git a/tests/SpecTests/Operation.php b/tests/SpecTests/Operation.php index 0950d856f..75b113c4f 100644 --- a/tests/SpecTests/Operation.php +++ b/tests/SpecTests/Operation.php @@ -558,7 +558,7 @@ private function executeForSession(Session $session, FunctionalTestCase $test, C return $session->startTransaction($context->prepareOptions($options)); case 'withTransaction': - /** @var self[] $callbackOperations */ + /** @var list $callbackOperations */ $callbackOperations = array_map(fn ($operation) => self::fromConvenientTransactions($operation), $this->arguments['callback']->operations); $callback = function () use ($callbackOperations, $test, $context): void { diff --git a/tests/UnifiedSpecTests/Context.php b/tests/UnifiedSpecTests/Context.php index b5c6843c0..110695683 100644 --- a/tests/UnifiedSpecTests/Context.php +++ b/tests/UnifiedSpecTests/Context.php @@ -42,10 +42,10 @@ final class Context private EntityMap $entityMap; - /** @var EventCollector[] */ + /** @var list */ private array $eventCollectors = []; - /** @var EventObserver[] */ + /** @var array */ private array $eventObserversByClient = []; private Client $internalClient; diff --git a/tests/UnifiedSpecTests/EntityMap.php b/tests/UnifiedSpecTests/EntityMap.php index 51cb64c47..e693d08c5 100644 --- a/tests/UnifiedSpecTests/EntityMap.php +++ b/tests/UnifiedSpecTests/EntityMap.php @@ -35,7 +35,7 @@ class EntityMap implements ArrayAccess * Track lsids so they can be accessed after Session::getLogicalSessionId() * has been called. * - * @var stdClass[] + * @var list */ private array $lsidsBySession = []; diff --git a/tests/UnifiedSpecTests/FailPointObserver.php b/tests/UnifiedSpecTests/FailPointObserver.php index 3d845887b..f843d43fb 100644 --- a/tests/UnifiedSpecTests/FailPointObserver.php +++ b/tests/UnifiedSpecTests/FailPointObserver.php @@ -13,7 +13,6 @@ class FailPointObserver implements CommandSubscriber { - /** @var array */ private array $failPointsAndServers = []; /** @see https://php.net/manual/en/mongodb-driver-monitoring-commandsubscriber.commandfailed.php */ From 879881383c039d92e9f6a2b6a3de35c75d2262e9 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 08:50:37 +0200 Subject: [PATCH 05/11] Use strval instead of closure --- src/Operation/CreateIndexes.php | 3 ++- src/Operation/ListCollectionNames.php | 2 +- tests/SpecTests/Operation.php | 10 +++++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Operation/CreateIndexes.php b/src/Operation/CreateIndexes.php index a71825812..e5fc9b73c 100644 --- a/src/Operation/CreateIndexes.php +++ b/src/Operation/CreateIndexes.php @@ -49,6 +49,7 @@ class CreateIndexes implements Executable private string $collectionName; + /** @var list */ private array $indexes = []; private array $options = []; @@ -140,7 +141,7 @@ public function execute(Server $server) $this->executeCommand($server); return array_map( - fn (IndexInput $index): string => (string) $index, + 'strval', $this->indexes, ); } diff --git a/src/Operation/ListCollectionNames.php b/src/Operation/ListCollectionNames.php index 064e39765..f2124c4d4 100644 --- a/src/Operation/ListCollectionNames.php +++ b/src/Operation/ListCollectionNames.php @@ -75,7 +75,7 @@ public function execute(Server $server): Iterator { return new CallbackIterator( $this->listCollections->execute($server), - fn (array $collectionInfo): string => (string) $collectionInfo['name'] + fn (array $collectionInfo): string => (string) $collectionInfo['name'], ); } } diff --git a/tests/SpecTests/Operation.php b/tests/SpecTests/Operation.php index 75b113c4f..5c87746a1 100644 --- a/tests/SpecTests/Operation.php +++ b/tests/SpecTests/Operation.php @@ -13,7 +13,6 @@ use MongoDB\Driver\Session; use MongoDB\GridFS\Bucket; use MongoDB\MapReduceResult; -use MongoDB\Model\IndexInfo; use MongoDB\Operation\FindOneAndReplace; use MongoDB\Operation\FindOneAndUpdate; use stdClass; @@ -648,8 +647,13 @@ private function executeForTestRunner(FunctionalTestCase $test, Context $context private function getIndexNames(Context $context, string $databaseName, string $collectionName): array { return array_map( - fn (IndexInfo $indexInfo) => $indexInfo->getName(), - iterator_to_array($context->getInternalClient()->selectCollection($databaseName, $collectionName)->listIndexes()), + 'strval', + iterator_to_array( + $context + ->getInternalClient() + ->selectCollection($databaseName, $collectionName) + ->listIndexes(), + ), ); } From 75d434df6a60af892913ccd1c288291ed26cff15 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 08:50:49 +0200 Subject: [PATCH 06/11] Use FQN for constant in documentation examples --- tests/DocumentationExamplesTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/DocumentationExamplesTest.php b/tests/DocumentationExamplesTest.php index c44038bf4..c169943a4 100644 --- a/tests/DocumentationExamplesTest.php +++ b/tests/DocumentationExamplesTest.php @@ -1711,7 +1711,7 @@ public function testVersionedApiMigration(): void try { $count = $db->sales->count(); } catch (\MongoDB\Driver\Exception\CommandException $e) { - echo json_encode($e->getResultDocument(), JSON_THROW_ON_ERROR); + echo json_encode($e->getResultDocument(), \JSON_THROW_ON_ERROR); // { "ok": 0, "errmsg": "Provided apiStrict:true, but the command count is not in API Version 1", "code": 323, "codeName": "APIStrictError" } } From fb6ff9aac6536063e371f6d7486ecb34b75c8a04 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 09:02:00 +0200 Subject: [PATCH 07/11] Add undectected missing trailing commas --- src/Operation/Watch.php | 2 +- tests/Collection/CollectionFunctionalTest.php | 4 ++-- tests/GridFS/ReadableStreamFunctionalTest.php | 2 +- tests/PedantryTest.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Operation/Watch.php b/src/Operation/Watch.php index 8a5d50f40..0a7d6f07f 100644 --- a/src/Operation/Watch.php +++ b/src/Operation/Watch.php @@ -314,7 +314,7 @@ public function execute(Server $server) { return new ChangeStream( $this->createChangeStreamIterator($server), - fn ($resumeToken, $hasAdvanced): ChangeStreamIterator => $this->resume($resumeToken, $hasAdvanced) + fn ($resumeToken, $hasAdvanced): ChangeStreamIterator => $this->resume($resumeToken, $hasAdvanced), ); } diff --git a/tests/Collection/CollectionFunctionalTest.php b/tests/Collection/CollectionFunctionalTest.php index dd62133f8..ee38671df 100644 --- a/tests/Collection/CollectionFunctionalTest.php +++ b/tests/Collection/CollectionFunctionalTest.php @@ -705,7 +705,7 @@ public function collectionReadMethodClosures(): array { return array_filter( $this->collectionMethodClosures(), - fn ($rw) => str_contains($rw[1], 'r') + fn ($rw) => str_contains($rw[1], 'r'), ); } @@ -713,7 +713,7 @@ public function collectionWriteMethodClosures(): array { return array_filter( $this->collectionMethodClosures(), - fn ($rw) => str_contains($rw[1], 'w') + fn ($rw) => str_contains($rw[1], 'w'), ); } diff --git a/tests/GridFS/ReadableStreamFunctionalTest.php b/tests/GridFS/ReadableStreamFunctionalTest.php index 7e30b8c93..dba7e0016 100644 --- a/tests/GridFS/ReadableStreamFunctionalTest.php +++ b/tests/GridFS/ReadableStreamFunctionalTest.php @@ -115,7 +115,7 @@ public function provideFilteredFileIdAndExpectedBytes() { return array_filter( $this->provideFileIdAndExpectedBytes(), - fn (array $args) => $args[1] > 0 + fn (array $args) => $args[1] > 0, ); } diff --git a/tests/PedantryTest.php b/tests/PedantryTest.php index ae11134ee..d0068d527 100644 --- a/tests/PedantryTest.php +++ b/tests/PedantryTest.php @@ -55,7 +55,7 @@ function (ReflectionMethod $method) use ($class) { $sortedMethods = $methods; usort( $sortedMethods, - fn (ReflectionMethod $a, ReflectionMethod $b) => strcasecmp($getSortValue($a), $getSortValue($b)) + fn (ReflectionMethod $a, ReflectionMethod $b) => strcasecmp($getSortValue($a), $getSortValue($b)), ); $methods = array_map(fn (ReflectionMethod $method) => $method->getName(), $methods); From a39cc24142de638dc9d423a3515c99ad2a17430a Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 09:02:21 +0200 Subject: [PATCH 08/11] Split line for readability --- tests/SpecTests/Operation.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/SpecTests/Operation.php b/tests/SpecTests/Operation.php index 5c87746a1..9e7776d09 100644 --- a/tests/SpecTests/Operation.php +++ b/tests/SpecTests/Operation.php @@ -558,7 +558,10 @@ private function executeForSession(Session $session, FunctionalTestCase $test, C case 'withTransaction': /** @var list $callbackOperations */ - $callbackOperations = array_map(fn ($operation) => self::fromConvenientTransactions($operation), $this->arguments['callback']->operations); + $callbackOperations = array_map( + fn ($operation) => self::fromConvenientTransactions($operation), + $this->arguments['callback']->operations, + ); $callback = function () use ($callbackOperations, $test, $context): void { foreach ($callbackOperations as $operation) { From 17f395a01b86a600051124bc927b15b30b5e65fc Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 09:02:37 +0200 Subject: [PATCH 09/11] Fix wrong property type --- tests/UnifiedSpecTests/RunOnRequirement.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/UnifiedSpecTests/RunOnRequirement.php b/tests/UnifiedSpecTests/RunOnRequirement.php index 950751fe8..ba00e15a8 100644 --- a/tests/UnifiedSpecTests/RunOnRequirement.php +++ b/tests/UnifiedSpecTests/RunOnRequirement.php @@ -10,9 +10,9 @@ use function PHPUnit\Framework\assertContains; use function PHPUnit\Framework\assertContainsOnly; use function PHPUnit\Framework\assertEmpty; +use function PHPUnit\Framework\assertInstanceOf; use function PHPUnit\Framework\assertIsArray; use function PHPUnit\Framework\assertIsBool; -use function PHPUnit\Framework\assertIsObject; use function PHPUnit\Framework\assertIsString; use function PHPUnit\Framework\assertMatchesRegularExpression; use function version_compare; @@ -37,7 +37,7 @@ class RunOnRequirement private ?array $topologies = null; - private ?object $serverParameters = null; + private ?stdClass $serverParameters = null; private ?bool $auth = null; @@ -83,7 +83,7 @@ public function __construct(stdClass $o) } if (isset($o->serverParameters)) { - assertIsObject($o->serverParameters); + assertInstanceOf(stdClass::class, $o->serverParameters); $this->serverParameters = $o->serverParameters; } From ebf877e9fb4d32d961865bbe3150af2eac7765bf Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 10:27:43 +0200 Subject: [PATCH 10/11] Remove requirement for JSON_THROW_ON_ERROR in docs examples --- rector.php | 5 +++++ tests/DocumentationExamplesTest.php | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/rector.php b/rector.php index 8c744016d..714486473 100644 --- a/rector.php +++ b/rector.php @@ -4,6 +4,7 @@ use Rector\DeadCode\Rector\ClassLike\RemoveAnnotationRector; use Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector; use Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector; +use Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector; use Rector\Set\ValueObject\LevelSetList; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector; @@ -31,6 +32,10 @@ TypedPropertyFromAssignsRector::class => [ __DIR__ . '/src/Model/BSONIterator.php', ], + // Not necessary in documentation examples + JsonThrowOnErrorRector::class => [ + __DIR__ . '/tests/DocumentationExamplesTest.php', + ], ]); // All classes are public API by default, unless marked with @internal. diff --git a/tests/DocumentationExamplesTest.php b/tests/DocumentationExamplesTest.php index c169943a4..9b9dac795 100644 --- a/tests/DocumentationExamplesTest.php +++ b/tests/DocumentationExamplesTest.php @@ -1711,7 +1711,7 @@ public function testVersionedApiMigration(): void try { $count = $db->sales->count(); } catch (\MongoDB\Driver\Exception\CommandException $e) { - echo json_encode($e->getResultDocument(), \JSON_THROW_ON_ERROR); + echo json_encode($e->getResultDocument()); // { "ok": 0, "errmsg": "Provided apiStrict:true, but the command count is not in API Version 1", "code": 323, "codeName": "APIStrictError" } } From e6c2595cd1ee704d25d3b2300f61173949c72b76 Mon Sep 17 00:00:00 2001 From: Andreas Braun Date: Fri, 14 Jul 2023 16:04:44 +0200 Subject: [PATCH 11/11] Address code review issues --- src/Operation/InsertMany.php | 2 +- tests/SpecTests/ErrorExpectation.php | 5 ++++- tests/SpecTests/RetryableWritesSpecTest.php | 4 ++-- tests/UnifiedSpecTests/EntityMap.php | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Operation/InsertMany.php b/src/Operation/InsertMany.php index b70daf90d..1d5cc981b 100644 --- a/src/Operation/InsertMany.php +++ b/src/Operation/InsertMany.php @@ -43,7 +43,7 @@ class InsertMany implements Executable private string $collectionName; - /** @var list|list */ + /** @var list */ private array $documents; private array $options; diff --git a/tests/SpecTests/ErrorExpectation.php b/tests/SpecTests/ErrorExpectation.php index 1b6c77c81..6c1f24bf5 100644 --- a/tests/SpecTests/ErrorExpectation.php +++ b/tests/SpecTests/ErrorExpectation.php @@ -22,7 +22,10 @@ */ final class ErrorExpectation { - /** @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err */ + /** + * @see https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.err + * @var array + */ private static array $codeNameMap = [ 'Interrupted' => 11601, 'MaxTimeMSExpired' => 50, diff --git a/tests/SpecTests/RetryableWritesSpecTest.php b/tests/SpecTests/RetryableWritesSpecTest.php index 3b07cdd1e..8f6ed2fd1 100644 --- a/tests/SpecTests/RetryableWritesSpecTest.php +++ b/tests/SpecTests/RetryableWritesSpecTest.php @@ -107,9 +107,9 @@ public function testNoWritesPerformedErrorReturnsOriginalError(): void ]); $subscriber = new class ($this) implements CommandSubscriber { - private FunctionalTestCase $testCase; + private RetryableWritesSpecTest $testCase; - public function __construct(FunctionalTestCase $testCase) + public function __construct(RetryableWritesSpecTest $testCase) { $this->testCase = $testCase; } diff --git a/tests/UnifiedSpecTests/EntityMap.php b/tests/UnifiedSpecTests/EntityMap.php index e693d08c5..00c7f9d3f 100644 --- a/tests/UnifiedSpecTests/EntityMap.php +++ b/tests/UnifiedSpecTests/EntityMap.php @@ -35,7 +35,7 @@ class EntityMap implements ArrayAccess * Track lsids so they can be accessed after Session::getLogicalSessionId() * has been called. * - * @var list + * @var array */ private array $lsidsBySession = [];