Skip to content

Unset field #1667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
65 changes: 41 additions & 24 deletions src/Jenssegers/Mongodb/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use Jenssegers\Mongodb\Query\UnsetField;
use function MongoDB\BSON\fromPHP;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Contracts\Queue\QueueableCollection;
use MongoDB\Driver\Exception\UnexpectedValueException;

abstract class Model extends BaseModel
{
Expand Down Expand Up @@ -244,20 +247,15 @@ protected function originalIsEquivalent($key, $current)
return false;
}

if ($this->isDateAttribute($key)) {
$current = $current instanceof UTCDateTime ? $this->asDateTime($current) : $current;
$original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $original;

return $current == $original;
if ($current instanceof UnsetField) {
return false;
}

if ($this->hasCast($key)) {
return $this->castAttribute($key, $current) ===
$this->castAttribute($key, $original);
try {
return fromPHP([$current]) === fromPHP([$original]);
} catch (UnexpectedValueException $e) {
return false;
}

return is_numeric($current) && is_numeric($original)
&& strcmp((string) $current, (string) $original) === 0;
}

/**
Expand All @@ -279,6 +277,38 @@ public function drop($columns)
return $this->newQuery()->where($this->getKeyName(), $this->getKey())->unset($columns);
}

/**
* Mark columns to be unset.
*
* @param string|string[] $columns
*
* @return $this
*/
public function unset($columns)
{
$columns = Arr::wrap($columns);

// Mark attribute as unset
foreach ($columns as $column) {
$this->attributes[$column] = new UnsetField();
}

return $this;
}

public function syncChanges()
{
$unset = array_filter($this->attributes, function ($value) {
return $value instanceof UnsetField;
});

foreach ($unset as $key => $value) {
unset($this->attributes[$key], $this->original[$key]);
}

parent::syncChanges();
}

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -474,17 +504,4 @@ protected function getRelationsWithoutParent()

return $relations;
}

/**
* @inheritdoc
*/
public function __call($method, $parameters)
{
// Unset method
if ($method == 'unset') {
return call_user_func_array([$this, 'drop'], $parameters);
}

return parent::__call($method, $parameters);
}
}
13 changes: 12 additions & 1 deletion src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,18 @@ public function update(array $values, array $options = [])
{
// Use $set as default operator.
if (!Str::startsWith(key($values), '$')) {
$values = ['$set' => $values];
$changes = [
'$set' => [],
'$unset' => [],
];
foreach ($values as $key => $value) {
if ($value instanceof UnsetField) {
$changes['$unset'][$key] = true;
} else {
$changes['$set'][$key] = $value;
}
}
$values = array_filter($changes);
}

return $this->performUpdate($values, $options);
Expand Down
13 changes: 13 additions & 0 deletions src/Jenssegers/Mongodb/Query/UnsetField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Jenssegers\Mongodb\Query;

use MongoDB\BSON\Serializable;

class UnsetField implements Serializable
{
public function bsonSerialize()
{
throw new \LogicException('UnsetField is not BSON serializable');
}
}
96 changes: 89 additions & 7 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Query\UnsetField;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;

Expand Down Expand Up @@ -345,14 +346,14 @@ public function testToArray()
$this->assertInternalType('string', $array['_id']);
}

public function testUnset()
public function testDrop()
{
$user1 = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
$user2 = User::create(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']);

$user1->unset('note1');
$user1->drop('note1');

$this->assertObjectNotHasAttribute('note1', $user1);
$this->assertFalse(array_key_exists('note1', $user1->getAttributes()));
$this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2));
Expand All @@ -361,15 +362,57 @@ public function testUnset()
$user1 = User::find($user1->_id);
$user2 = User::find($user2->_id);

$this->assertObjectNotHasAttribute('note1', $user1);
$this->assertFalse(array_key_exists('note1', $user1->getAttributes()));
$this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2));

$user2->drop(['note1', 'note2']);

$this->assertFalse(array_key_exists('note1', $user2->getAttributes()));
$this->assertFalse(array_key_exists('note2', $user2->getAttributes()));
}

public function testUnset()
{
$user1 = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
$user2 = User::create(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']);

$user1->unset('note1');

$this->assertTrue(array_key_exists('note1', $user1->getOriginal()));
$this->assertInstanceOf(UnsetField::class, $user1->note1);

$user1->save();

$this->assertFalse(array_key_exists('note1', $user1->getOriginal()));
$this->assertFalse(array_key_exists('note1', $user1->getAttributes()));

// Re-fetch to be sure
$user1 = User::find($user1->_id);

$this->assertFalse(array_key_exists('note1', $user1->getOriginal()));
$this->assertFalse(array_key_exists('note1', $user1->getAttributes()));

$user2->unset(['note1', 'note2']);

$this->assertObjectNotHasAttribute('note1', $user2);
$this->assertObjectNotHasAttribute('note2', $user2);
$this->assertTrue(array_key_exists('note1', $user2->getOriginal()));
$this->assertTrue(array_key_exists('note2', $user2->getOriginal()));
$this->assertFalse(array_key_exists('note3', $user2->getAttributes()));

$this->assertInstanceOf(UnsetField::class, $user2->note1);
$this->assertInstanceOf(UnsetField::class, $user2->note2);
$this->assertFalse(array_key_exists('note3', $user2->getAttributes()));

$user2->note3 = 'GHI';
$user2->save();

$user2 = User::find($user2->_id);
$this->assertFalse(array_key_exists('note1', $user2->getAttributes()));
$this->assertFalse(array_key_exists('note2', $user2->getAttributes()));
$this->assertFalse(array_key_exists('note1', $user2->getOriginal()));
$this->assertFalse(array_key_exists('note2', $user2->getOriginal()));
$this->assertEquals('GHI', $user2->note3);
}

public function testDates()
Expand Down Expand Up @@ -528,13 +571,52 @@ public function testMultipleLevelDotNotation()
public function testGetDirtyDates()
{
$user = new User();
$user->setRawAttributes(['name' => 'John Doe', 'birthday' => new DateTime('19 august 1989')], true);
$user->name = 'John Doe';
$user->birthday = new DateTime('19 august 1989');
$user->syncOriginal();
$this->assertEmpty($user->getDirty());

$user->birthday = new DateTime('19 august 1989');
$this->assertEmpty($user->getDirty());
}

public function testGetDirty()
{
$ids = [
new ObjectId(),
new ObjectId(),
];
$item = new Item([
'numbers' => [1, 2, 3],
'number' => 4,
'ids' => $ids,
'nullable' => 'value',
'fix' => 'fix',
]);
$item->date = $item->fromDateTime(new DateTime('19 august 1989'));
$item->dates = [$item->fromDateTime(new DateTime('19 august 1989'))];
$item->save();

$item = $item->fresh();

$item->numbers = [1, 2, '3'];
$item->nullable = null;
$item->new_val = 'new';
$item->number = '4';
$item->ids = [
new ObjectId((string) $ids[0]),
new ObjectId((string) $ids[1]),
];
$item->date = $item->fromDateTime(new DateTime('19 august 1989'));
$item->dates = [$item->fromDateTime(new DateTime('19 august 1989'))];
$this->assertEquals([
'numbers' => [1, 2, '3'],
'number' => '4',
'nullable' => null,
'new_val' => 'new',
], $item->getDirty());
}

public function testChunkById()
{
User::create(['name' => 'fork', 'tags' => ['sharp', 'pointy']]);
Expand Down