Skip to content

Commit 7fbf641

Browse files
Merge pull request #45 from kevinkl3/feature/regex-operator
Implement regex operator
2 parents 923616b + 88859da commit 7fbf641

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
@@ -673,6 +673,20 @@ function ($acc, $op) use ($val) {
673673
$result = !$operand;
674674
}
675675
break;
676+
case '$regex':{
677+
if($operand instanceof \MongoDB\BSON\Regex){
678+
$regex = "/". $operand->getPattern() . "/". $operand->getFlags();
679+
$result = preg_match($regex,$val) === 1;
680+
}else if(is_string($operand)){
681+
if(@preg_match($operand, '') === false){
682+
throw new Exception("Invalid constraint for operator '" . $type . "'");
683+
}
684+
$result = preg_match($operand,$val) === 1;
685+
}else{
686+
throw new Exception("Invalid constraint for operator '" . $type . "'");
687+
}
688+
break;
689+
}
676690
// Custom operators
677691
case '$instanceOf':
678692
$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)