Skip to content

Commit

Permalink
Updated DataMapper to, when preparing the query, convert any _id stri…
Browse files Browse the repository at this point in the history
…ng to an actual ObjectId
  • Loading branch information
Zizaco committed Jul 4, 2016
1 parent 815da99 commit b487d1c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
14 changes: 9 additions & 5 deletions src/Mongolid/DataMapper/DataMapper.php
Expand Up @@ -15,6 +15,7 @@
use Mongolid\DataMapper\SchemaMapper;
use Mongolid\Event\EventTriggerService;
use Mongolid\Schema;
use Mongolid\Util\ObjectIdUtils;

/**
* The DataMapper class will abstract how an Entity is persisted and retrieved
Expand Down Expand Up @@ -337,15 +338,18 @@ protected function getCollection(): Collection
*/
protected function prepareValueQuery($value): array
{
if (is_array($value)) {
return $value;
if (! is_array($value)) {
$value = ['_id' => $value];
}

if (is_string($value) && strlen($value) == 24 && ctype_xdigit($value)) {
$value = new ObjectID($value);
if (isset($value['_id']) &&
is_string($value['_id']) &&
ObjectIdUtils::isObjectId($value['_id'])
) {
$value['_id'] = new ObjectID($value['_id']);
}

return ['_id' => $value];
return $value;
}

/**
Expand Down
12 changes: 10 additions & 2 deletions tests/Mongolid/DataMapper/DataMapperTest.php
Expand Up @@ -622,6 +622,9 @@ public function testShouldPrepareQueryValue($value, $expectation)

// Assert
$this->assertEquals($expectation, $result);
if (isset($result['_id']) && is_object($expectation['_id'])) {
$this->assertInstanceOf(get_class($expectation['_id']), $result['_id']);
}
}

/**
Expand Down Expand Up @@ -717,16 +720,21 @@ public function eventsToBailOperations()
public function queryValueScenarios()
{
return [
'An array' => [
'An array' => [
'value' => ['age' => ['$gt' => 25]],
'expectation' => ['age' => ['$gt' => 25]],
],
// ------------------------
'An ObjectId string' => [
'An ObjectId string' => [
'value' => '507f1f77bcf86cd799439011',
'expectation' => ['_id' => new ObjectID('507f1f77bcf86cd799439011')],
],
// ------------------------
'An ObjectId string within a query' => [
'value' => ['_id' => '507f1f77bcf86cd799439011'],
'expectation' => ['_id' => new ObjectID('507f1f77bcf86cd799439011')],
],
// ------------------------
'Other type of _id, sequence for example' => [
'value' => 7,
'expectation' => ['_id' => 7],
Expand Down

0 comments on commit b487d1c

Please sign in to comment.