Skip to content

Commit

Permalink
Adds support for _id of binary type (mongodb#1611)
Browse files Browse the repository at this point in the history
  • Loading branch information
mnphpexpert committed Apr 24, 2019
1 parent dbe14c8 commit 8c72d95
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/Jenssegers/Mongodb/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;
use Illuminate\Contracts\Queue\QueueableEntity;
Expand Down Expand Up @@ -63,6 +64,8 @@ public function getIdAttribute($value = null)
// Convert ObjectID to string.
if ($value instanceof ObjectID) {
return (string) $value;
} elseif ($value instanceof Binary) {
return (string) $value->getData();
}

return $value;
Expand Down Expand Up @@ -172,7 +175,7 @@ protected function getAttributeFromArray($key)
public function setAttribute($key, $value)
{
// Convert _id to ObjectID.
if ($key == '_id' && is_string($value)) {
if (($key == '_id' || Str::endsWith($key, '_id')) && is_string($value)) {
$builder = $this->newBaseQueryBuilder();

$value = $builder->convertKey($value);
Expand Down Expand Up @@ -204,6 +207,8 @@ public function attributesToArray()
foreach ($attributes as $key => &$value) {
if ($value instanceof ObjectID) {
$value = (string) $value;
} elseif ($value instanceof Binary) {
$value = (string) $value->getData();
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Connection;
use MongoCollection;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime;
Expand Down Expand Up @@ -843,6 +844,8 @@ public function convertKey($id)
{
if (is_string($id) && strlen($id) === 24 && ctype_xdigit($id)) {
return new ObjectID($id);
} elseif (strlen($id) === 16 && preg_match('~[^\x20-\x7E\t\r\n]~', $id) > 0) {
return new Binary($id, Binary::TYPE_UUID);
}

return $id;
Expand Down Expand Up @@ -903,7 +906,7 @@ protected function compileWheres()
}

// Convert id's.
if (isset($where['column']) && ($where['column'] == '_id' || Str::endsWith($where['column'], '._id'))) {
if (isset($where['column']) && ($where['column'] == '_id' || Str::endsWith($where['column'], '_id'))) {
// Multiple values.
if (isset($where['values'])) {
foreach ($where['values'] as &$value) {
Expand Down

0 comments on commit 8c72d95

Please sign in to comment.