Browse Source

add inclusive inRange()

euromark 11 years ago
parent
commit
9e00dc6e71
2 changed files with 52 additions and 0 deletions
  1. 25 0
      Model/MyModel.php
  2. 27 0
      Test/Case/Model/MyModelTest.php

+ 25 - 0
Model/MyModel.php

@@ -865,6 +865,31 @@ class MyModel extends Model {
 	}
 
 	/**
+	 * Validate range, but in a more sane way than CORE range().
+	 * This range() validation rule is inclusive regarding the borders.
+	 *
+	 * If $lower and $upper are not set, will return true if
+	 * $check is a legal finite on this platform
+	 *
+	 * @param string $check Value to check
+	 * @param float $lower Lower limit
+	 * @param float $upper Upper limit
+	 * @return boolean Success
+	 */
+	public function validateRange($data, $lower = null, $upper = null) {
+		foreach ($data as $key => $check) {
+			break;
+		}
+		if (!is_numeric($check)) {
+			return false;
+		}
+		if (isset($lower) && isset($upper)) {
+			return ($check >= $lower && $check <= $upper);
+		}
+		return is_finite($check);
+	}
+
+	/**
 	 * Checks a record, if it is unique - depending on other fields in this table (transfered as array)
 	 * example in model: 'rule' => array ('validateUnique', array('belongs_to_table_id','some_id','user_id')),
 	 * if all keys (of the array transferred) match a record, return false, otherwise true

+ 27 - 0
Test/Case/Model/MyModelTest.php

@@ -276,6 +276,33 @@ class MyModelTest extends MyCakeTestCase {
 	}
 
 	/**
+	 * MyModelTest::testValidateRange()
+	 *
+	 * @return void
+	 */
+	public function testValidateRange() {
+		$this->out($this->_header(__FUNCTION__), true);
+		$is = $this->User->validateRange(array('range' => 2), 1, 3);
+		$this->assertTrue($is);
+
+		$this->out($this->_header(__FUNCTION__), true);
+		$is = $this->User->validateRange(array('range' => 2.4), 1.5, 2.3);
+		$this->assertFalse($is);
+
+		$this->out($this->_header(__FUNCTION__), true);
+		$is = $this->User->validateRange(array('range' => -5), -10, 1);
+		$this->assertTrue($is);
+
+		$this->out($this->_header(__FUNCTION__), true);
+		$is = $this->User->validateRange(array('range' => 'word'), 1.5, 2.3);
+		$this->assertFalse($is);
+
+		$this->out($this->_header(__FUNCTION__), true);
+		$is = $this->User->validateRange(array('range' => 5.1));
+		$this->assertTrue($is);
+	}
+
+	/**
 	 * MyModelTest::testValidateIdentical()
 	 *
 	 * @return void