Skip to content

Commit d2e041b

Browse files
Merge branch 'master' into fix/delete-one
2 parents 7c541dd + 7fbf641 commit d2e041b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/MockCollection.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,20 @@ function ($acc, $op) use ($val) {
678678
$result = !$operand;
679679
}
680680
break;
681+
case '$regex':{
682+
if($operand instanceof \MongoDB\BSON\Regex){
683+
$regex = "/". $operand->getPattern() . "/". $operand->getFlags();
684+
$result = preg_match($regex,$val) === 1;
685+
}else if(is_string($operand)){
686+
if(@preg_match($operand, '') === false){
687+
throw new Exception("Invalid constraint for operator '" . $type . "'");
688+
}
689+
$result = preg_match($operand,$val) === 1;
690+
}else{
691+
throw new Exception("Invalid constraint for operator '" . $type . "'");
692+
}
693+
break;
694+
}
681695
// Custom operators
682696
case '$instanceOf':
683697
$result = is_a($val, $operand);

tests/MockCollectionTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Helmich\MongoMock\MockCollection;
66
use Helmich\MongoMock\MockCursor;
7+
use Helmich\MongoMock\Exception;
78
use MongoDB\BSON\ObjectID;
89
use MongoDB\BSON\Regex;
910
use MongoDB\Collection;
@@ -184,6 +185,9 @@ public function testFindWithInvertedFilter()
184185
$result = $find->toArray();
185186
self::assertThat(count($result), self::equalTo(1));
186187
self::assertThat($result[0]['foo'], self::equalTo('bar'));
188+
189+
$result = $this->col->count(['foo' => ['$not' => ['$regex' => "/bar/"]]]);
190+
self::assertThat($result, self::equalTo(1));
187191
}
188192

189193
/**
@@ -237,6 +241,32 @@ public function testInsertOneKeepsIdIfSet()
237241
self::assertThat($find['foo'], self::equalTo('bar'));
238242
}
239243

244+
public function testFindWithRegexFilter()
245+
{
246+
$this->col->insertMany([
247+
['foo' => 'barbazbad'],
248+
['foo' => 'bazbad'],
249+
['foo' => 'foobarbaroof']
250+
]);
251+
252+
$result = $this->col->count(['foo' => ['$regex' => "/barBar/"]]);
253+
self::assertThat($result, self::equalTo(0));
254+
255+
$result = $this->col->count(['foo' => ['$regex' => "/bar/"]]);
256+
self::assertThat($result, self::equalTo(2));
257+
258+
$result = $this->col->count(['foo' => ['$regex' => "/(bar|BAZ)/i"]]);
259+
self::assertThat($result, self::equalTo(3));
260+
261+
$result = $this->col->count(['foo' => ['$regex' => new \MongoDB\BSON\Regex("FOOBAR","i")]]);
262+
self::assertThat($result, self::equalTo(1));
263+
264+
$this->expectException(Exception::class);
265+
266+
$result = $this->col->count(['foo' => ['$regex' => "[[[[foobar{"]]);
267+
268+
}
269+
240270
public function testInsertManyInsertsDocuments()
241271
{
242272
$result = $this->col->insertMany([

0 commit comments

Comments
 (0)