Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.

PHPORM-44: Throw an exception when Query\Builder::push() is used incorrectly #5

Merged
merged 1 commit into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -786,9 +786,12 @@ public function push($column, $value = null, $unique = false)
$operator = $unique ? '$addToSet' : '$push';

// Check if we are pushing multiple values.
$batch = (is_array($value) && array_keys($value) === range(0, count($value) - 1));
$batch = is_array($value) && array_is_list($value);

if (is_array($column)) {
if ($value !== null) {
throw new \InvalidArgumentException(sprintf('2nd argument of %s() must be "null" when 1st argument is an array. Got "%s" instead.', __METHOD__, get_debug_type($value)));
}
$query = [$operator => $column];
} elseif ($batch) {
$query = [$operator => [$column => ['$each' => $value]]];
Expand Down
8 changes: 8 additions & 0 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,14 @@ public function testPush()
$this->assertCount(3, $user['messages']);
}

public function testPushRefuses2ndArgumentWhen1stIsAnArray()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('2nd argument of Jenssegers\Mongodb\Query\Builder::push() must be "null" when 1st argument is an array. Got "string" instead.');

DB::collection('users')->push(['tags' => 'tag1'], 'tag2');
}

public function testPull()
{
$message1 = ['from' => 'Jane', 'body' => 'Hi John'];
Expand Down