From 51f8a36a5549e696d2d8866cac64f93715ffa23a Mon Sep 17 00:00:00 2001 From: TCB13 Date: Wed, 6 Feb 2019 10:29:10 +0000 Subject: [PATCH] New Increment special function; Improved Where() operator detection; Fixed RawFilter bugs; --- src/Increment.php | 22 ++++++++++++++++++++++ src/QueryBuilder.php | 25 +++++++++++++++++++++++-- src/RawFilter.php | 2 +- 3 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 src/Increment.php diff --git a/src/Increment.php b/src/Increment.php new file mode 100644 index 0000000..16add10 --- /dev/null +++ b/src/Increment.php @@ -0,0 +1,22 @@ +name = $propertyName; + $this->by = $incrementBy; + } + + public function asArray(): array + { + return [ + "\$inc" => [$this->name => $this->by] + ]; + } +} diff --git a/src/QueryBuilder.php b/src/QueryBuilder.php index b5f7cb9..fbd886c 100644 --- a/src/QueryBuilder.php +++ b/src/QueryBuilder.php @@ -258,7 +258,7 @@ public function orWhereEndsWith(string $key, $value): self private function buildWhere(string $prefix, $key, $operator = null, $value = null): void { // Assume that the operator is = - if ($value === null && !in_array($operator, array_keys(self::$mongoOperatorMap))) { + if ($value === null && !in_array((string)$operator, array_keys(self::$mongoOperatorMap))) { $value = $operator; $operator = "="; } @@ -398,7 +398,28 @@ public function update($update): UpdateResult { if (empty($this->filters)) throw new Exception("You must set a filter (where query) to update records."); - return $this->collection->updateMany($this->getNormalizedFilters(), ["\$set" => $update]); + + $pipeline = []; + + $inc = []; + $set = \array_filter($update, function($value) use (&$inc) { + // Filter out Increments + if ($value instanceof Increment) { + $inc[] = $value->asArray(); + return false; + } + return true; + }); + + // Add set to the pipeline + if (!empty($set)) + $pipeline["\$set"] = $set; + + // Add all increments to the pipline + if (!empty($inc)) + $pipeline["\$inc"] = array_merge(...array_column($inc, "\$inc")); + + return $this->collection->updateMany($this->getNormalizedFilters(), $pipeline); } public function delete(): DeleteResult diff --git a/src/RawFilter.php b/src/RawFilter.php index 1886027..612af9c 100644 --- a/src/RawFilter.php +++ b/src/RawFilter.php @@ -29,7 +29,7 @@ public static function fromCollectionOfRawFilters($filters): self public function push($filter): self { - return $this->pushMany([$filter]); + return $this->pushMany($filter); } public function pushMany($filters): self