From 83d0b8b4a5159d22836c11d7ee52fea641679f83 Mon Sep 17 00:00:00 2001 From: Matthieu Fauveau Date: Wed, 24 Apr 2019 17:21:49 -0400 Subject: [PATCH] Adds support for _id of binary type (#1611) --- src/Jenssegers/Mongodb/Eloquent/Model.php | 7 ++++++- src/Jenssegers/Mongodb/Query/Builder.php | 5 ++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index ef5e87184..f84c4d66a 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -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; @@ -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; @@ -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); @@ -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(); } } diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index ad63d462e..84874ed96 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -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; @@ -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; @@ -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) {