From c0de34d51f368b007dee3d4fbf0976627f6a1bf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 5 Oct 2023 23:26:12 +0200 Subject: [PATCH] Introduce MongoDB\object() function --- src/functions.php | 12 ++++++++++++ tests/Builder/BuilderEncoderTest.php | 16 ++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/functions.php b/src/functions.php index 95c85380b..4f438ab45 100644 --- a/src/functions.php +++ b/src/functions.php @@ -34,6 +34,7 @@ use Psr\Log\LoggerInterface; use ReflectionClass; use ReflectionException; +use stdClass; use function array_is_list; use function array_key_first; @@ -58,6 +59,17 @@ function add_logger(LoggerInterface $logger): void PsrLogAdapter::addLogger($logger); } +/** + * Create a new stdClass instance with the provided properties. + * + * @psalm-suppress MoreSpecificReturnType + * @psalm-suppress LessSpecificReturnStatement + */ +function object(mixed ...$values): stdClass +{ + return (object) $values; +} + /** * Unregisters a PSR-3 logger. * diff --git a/tests/Builder/BuilderEncoderTest.php b/tests/Builder/BuilderEncoderTest.php index df94d7b6d..b3dee19e3 100644 --- a/tests/Builder/BuilderEncoderTest.php +++ b/tests/Builder/BuilderEncoderTest.php @@ -15,6 +15,7 @@ use function array_merge; use function array_walk; use function is_array; +use function MongoDB\object; use function var_export; /** @@ -27,8 +28,7 @@ class BuilderEncoderTest extends TestCase public function testPipeline(): void { $pipeline = new Pipeline( - // @todo array is accepted by the stage class, but we expect an object. The driver accepts both. - Stage::match((object) ['author' => 'dave']), + Stage::match(object(author: 'dave')), Stage::limit(1), ); @@ -44,7 +44,7 @@ public function testPipeline(): void public function testSort(): void { $pipeline = new Pipeline( - Stage::sort((object) ['age' => -1, 'posts' => 1]), + Stage::sort(object(age: -1, posts: 1)), ); $expected = [ @@ -60,8 +60,8 @@ public function testPerformCount(): void $pipeline = new Pipeline( Stage::match( Query::or( - (object) ['score' => [Query::gt(70), Query::lt(90)]], - (object) ['views' => Query::gte(1000)], + object(score: [Query::gt(70), Query::lt(90)]), + object(views: Query::gte(1000)), ), ), Stage::group( @@ -99,14 +99,14 @@ public function testPerformCount(): void public function testAggregationFilter(array $limit, array $expectedLimit): void { $pipeline = new Pipeline( - Stage::project(...[ - 'items' => Aggregation::filter( + Stage::project( + items: Aggregation::filter( Expression::arrayFieldPath('items'), Aggregation::gte(Expression::variable('item.price'), 100), 'item', ...$limit, ), - ]), + ), ); $expected = [