<?php
/**
* a baisc constraint for string. This class can be used in setter methods
* to validate input data and constrain it to a valid string regex.
*
* @see Constraint
* @author Cory
* @package constraints
*/
require_once ROGUE_DIR . '/constraints/Constraint.php';
class RegExConstraint extends Constraint
{
private $_regex;
/**
* build a new Contraint for strings with regexes
*
* @param string $name the name of the constraint
* @param string $regex the pcre (perl) regular expression to validate data against default alpha numeric
* @param boolean $nullAble true if the paramater may be null
*/
public function __construct($name = false, $regex = '/[a-zA-Z0-9/', $nullAble = false)
{
// setup the base constraint
parent::__construct($name, 'string', $nullAble);
// assign the min and max values
$this->_regex = $regex;
}
/**
* validate that the passed paramater matches the constraint. Tests Constraint tests
* Constraint base class validation, as well as the regular expression.
*
* @param string $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 (!preg_match($this->_regex, $param))
$res = ($message) ? $message : 'constraint: ' . $this->_name . ' may does not match ' . $this->_regex . ' / ' . $param;
if ($res)
throw new ConstraintException ($res);
// life is good
return true;
}
}