Browse Source

Fixing code and adding test for the Between expression

Jose Lorenzo Rodriguez 11 years ago
parent
commit
3cecdc7292

+ 8 - 1
src/Database/Expression/BetweenExpression.php

@@ -46,6 +46,13 @@ class BetweenExpression implements ExpressionInterface {
 	protected $_to;
 
 /**
+ * The data type for the from and to arguments
+ *
+ * @var mixed
+ */
+	protected $_type;
+
+/**
  * Constructor
  *
  * @param mixed $value the value to use as the operand for the expression
@@ -55,7 +62,7 @@ class BetweenExpression implements ExpressionInterface {
 		$this->_field = $field;
 		$this->_from = $from;
 		$this->_to = $to;
-		$this->$type = $type;
+		$this->_type = $type;
 	}
 
 /**

+ 4 - 0
src/Database/Expression/QueryExpression.php

@@ -298,6 +298,10 @@ class QueryExpression implements ExpressionInterface, Countable {
 		return $this->add(new Comparison($field, $values, $type, 'NOT IN'));
 	}
 
+	public function between($field, $from, $to, $type = null) {
+		return $this->add(new BetweenExpression($field, $from, $to, $type));
+	}
+
 // @codingStandardsIgnoreStart
 /**
  * Returns a new QueryExpression object containing all the conditions passed

+ 50 - 0
tests/TestCase/Database/QueryTest.php

@@ -1123,6 +1123,56 @@ class QueryTest extends TestCase {
 	}
 
 /**
+ * Tests that it is possible to use a between expression
+ * in a where condition
+ *
+ * @return void
+ */
+	public function testWhereWithBetween() {
+		$query = new Query($this->connection);
+		$result = $query
+			->select(['id'])
+			->from('comments')
+			->where(function($exp) {
+				return $exp->between('id', 5, 6, 'integer');
+			})
+			->execute();
+
+		$this->assertCount(2, $result);
+		$first = $result->fetch('assoc');
+		$this->assertEquals(5, $first['id']);
+
+		$second = $result->fetch('assoc');
+		$this->assertEquals(6, $second['id']);
+	}
+
+/**
+ * Tests that it is possible to use a between expression
+ * in a where condition with a complex data type
+ *
+ * @return void
+ */
+	public function testWhereWithBetweenComplex() {
+		$query = new Query($this->connection);
+		$result = $query
+			->select(['id'])
+			->from('comments')
+			->where(function($exp) {
+				$from = new \DateTime('2007-03-18 10:51:00');
+				$to = new \DateTime('2007-03-18 10:54:00');
+				return $exp->between('created', $from, $to, 'datetime');
+			})
+			->execute();
+
+		$this->assertCount(2, $result);
+		$first = $result->fetch('assoc');
+		$this->assertEquals(4, $first['id']);
+
+		$second = $result->fetch('assoc');
+		$this->assertEquals(5, $second['id']);
+	}
+
+/**
  * Tests nesting query expressions both using arrays and closures
  *
  * @return void