Commit 0819ef53 authored by Jens Segers's avatar Jens Segers

Tweak regexp operations, fixes #282

parent 5f755fea
...@@ -832,13 +832,30 @@ class Builder extends QueryBuilder { ...@@ -832,13 +832,30 @@ class Builder extends QueryBuilder {
$operator = '='; $operator = '=';
$regex = str_replace('%', '', $value); $regex = str_replace('%', '', $value);
// Prepare regex // Convert like to regular expression.
if (substr($value, 0, 1) != '%') $regex = '^' . $regex; if (starts_with($value, '%')) $regex = '^' . $regex;
if (substr($value, -1) != '%') $regex = $regex . '$'; if (ends_with($value, '%')) $regex = $regex . '$';
$value = new MongoRegex("/$regex/i"); $value = new MongoRegex("/$regex/i");
} }
// Manipulate regexp operations.
elseif (in_array($operator, array('regexp', 'not regexp', 'regex', 'not regex')))
{
// Automatically convert regular expression strings to MongoRegex objects.
if ( ! $value instanceof MongoRegex)
{
$value = new MongoRegex($value);
}
// For inverse regexp operations, we can just use the $not operator
// and pass it a MongoRegex instence.
if (starts_with($operator, 'not'))
{
$operator = 'not';
}
}
if ( ! isset($operator) or $operator == '=') if ( ! isset($operator) or $operator == '=')
{ {
$query = array($column => $value); $query = array($column => $value);
......
...@@ -540,6 +540,12 @@ class QueryBuilderTest extends TestCase { ...@@ -540,6 +540,12 @@ class QueryBuilderTest extends TestCase {
$results = DB::collection('users')->where('name', 'REGEX', $regex)->get(); $results = DB::collection('users')->where('name', 'REGEX', $regex)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('users')->where('name', 'regexp', '/.*doe/i')->get();
$this->assertEquals(2, count($results));
$results = DB::collection('users')->where('name', 'not regexp', '/.*doe/i')->get();
$this->assertEquals(1, count($results));
DB::collection('users')->insert(array( DB::collection('users')->insert(array(
array( array(
'name' => 'John Doe', 'name' => 'John Doe',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment