Skip to content

Commit dd17163

Browse files
committed
MongoDate tweak, fixes #86
1 parent 6002aca commit dd17163

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,15 +264,30 @@ public function setRawAttributes(array $attributes, $sync = false)
264264
{
265265
$value = (string) $value;
266266
}
267+
}
268+
269+
parent::setRawAttributes($attributes, $sync);
270+
}
267271

272+
/**
273+
* Convert the model's attributes to an array.
274+
*
275+
* @return array
276+
*/
277+
public function attributesToArray()
278+
{
279+
$attributes = parent::attributesToArray();
280+
281+
foreach ($attributes as &$value)
282+
{
268283
// Convert MongoDate to string
269-
else if ($value instanceof MongoDate)
284+
if ($value instanceof MongoDate)
270285
{
271286
$value = $this->asDateTime($value)->format('Y-m-d H:i:s');
272287
}
273288
}
274289

275-
parent::setRawAttributes($attributes, $sync);
290+
return $attributes;
276291
}
277292

278293
/**

tests/ModelTest.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,9 @@ public function testCreate()
178178
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $user);
179179
$this->assertEquals(true, $user->exists);
180180
$this->assertEquals('Jane Poe', $user->name);
181+
182+
$check = User::where('name', 'Jane Poe')->first();
183+
$this->assertEquals($user, $check);
181184
}
182185

183186
public function testDestroy()
@@ -280,6 +283,14 @@ public function testToArray()
280283
$items = Item::all();
281284
$this->assertEquals($original, $items->toArray());
282285
$this->assertEquals($original[0], $items[0]->toArray());
286+
287+
// with date
288+
$item = Item::create(array('name' => 'fork', 'type' => 'sharp'));
289+
$array = $item->toArray();
290+
$this->assertTrue(array_key_exists('created_at', $array));
291+
$this->assertTrue(array_key_exists('updated_at', $array));
292+
$this->assertTrue(is_string($array['created_at']));
293+
$this->assertTrue(is_string($array['updated_at']));
283294
}
284295

285296
public function testUnset()
@@ -312,14 +323,11 @@ public function testUnset()
312323
public function testDates()
313324
{
314325
$user = User::create(array('name' => 'John Doe', 'birthday' => new DateTime('1980/1/1')));
315-
316326
$this->assertInstanceOf('Carbon\Carbon', $user->birthday);
317327

318328
$check = User::find($user->_id);
319-
320329
$this->assertInstanceOf('Carbon\Carbon', $check->birthday);
321330
$this->assertEquals($user->birthday, $check->birthday);
322-
323331

324332
$user = User::where('birthday', '>', new DateTime('1975/1/1'))->first();
325333
$this->assertEquals('John Doe', $user->name);

0 commit comments

Comments
 (0)