Skip to content

Commit

Permalink
New Increment special function;
Browse files Browse the repository at this point in the history
Improved Where() operator detection;
Fixed RawFilter bugs;
  • Loading branch information
TCB13 committed Feb 6, 2019
1 parent af030c4 commit 51f8a36
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
22 changes: 22 additions & 0 deletions src/Increment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace SequelMongo;

class Increment
{
protected $name;
protected $by;

public function __construct(string $propertyName, int $incrementBy = 1)
{
$this->name = $propertyName;
$this->by = $incrementBy;
}

public function asArray(): array
{
return [
"\$inc" => [$this->name => $this->by]
];
}
}
25 changes: 23 additions & 2 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "=";
}
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/RawFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 51f8a36

Please sign in to comment.