<?php
/**
* a baisc constraint for integers. This class can be used in setter methods
* to validate input data and constrain it to a valid range.
*
* @see Constraint
* @author Cory
* @package constraints
*/
require_once ROGUE_DIR . '/constraints/Constraint.php';
/**
* a baisc constraint for integers. This class can be used in setter methods
* to validate input data and constrain it to a valid range.
* <code>
* <pre>
* private static $_myConstraint = false;
*
* public function __construct()
* {
* // create the constraint as a static, we only need one for all call references
* if (self::$_myConstraint == false)
* self::$_myConstraint = new IntegerConstraint('a constraint', integer, false, minValue, maxValue);
* }
* public function setSomeThing($data)
* {
* self::$_myConstraint->validate($data); // throws BSException.php if $data is not type integer and not null
* $this->_someInt = $data
* }
* </pre>
* </code>
*
* @author Cory
* @package constraints
* @property integer $_minValue the minimum value to accept
* @property integer $_maxValue the maximum value to accept
*/
class IntegerConstraint extends Constraint
{
protected $_minValue;
protected $_maxValue;
/**
* build a new Contraint for Integers
*
* @param String $name the name of the constraint
* @param String $type the PHP name for the type as returned by instanceof
* @param Boolean $nullAble true if the paramater may be null
* @param Integer $minValue the minimum value for the constraint
* @param Integer $maxValue the maximum value for the constraint
*/
public function __construct($name = false, $type = false, $nullAble = false, $minValue = false, $maxValue = false)
{
// setup the base constraint
parent::__construct($name, $type, $nullAble);
// verify the min value
if (!is_int($minValue))
throw new BSException('Can not create an Integer constraint without a min value');
// verify the max value
if (!is_int($maxValue))
throw new BSException('Can not create an Integer constraint without a max value');
// assign the min and max values
$this->_minValue = $minValue;
$this->_maxValue = $maxValue;
}
/**
* validate that the passed paramater matches the constraint. Tests Constraint tests
* as well as min ans max values for the paramater.
*
* @param mixed $param the paramater to test
* @return Boolean true if validation succeeds
*/
public function validate($param, $message= false)
{
// validate the type and nullability
parent::validate($param);
// if it's an allowed null value, then return success
if ($this->_isNull)
return true;
$res = '';
if ($param < $this->_minValue)
$res = $this->_name . ' may not be less than ' . $this->_minValue . ' / ' . $param;
// validate the max
if ($param > $this->_maxValue)
$res = $this->_name . ' may not be greater than ' . $this->_maxValue . ' / ' . $param;
if ($res)
throw new ConstraintException($res);
// life is good
return true;
}
}