<?php
/**
 * A class for validating strings against regex patterns.
 */
class validator_pattern extends validator_reverse
{
    /**
     * @var string The regex pattern.
     */
    protected $pattern;

    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.

    /**
     * @param string $pattern The regex pattern.
     * @param string (optional) $error The error message.
     * @param boolean (optional) $reverse Whether the validator is in reverse
     * mode or not.
     */
    public function __construct($pattern, $error = null, $reverse = false)
    {
        parent::__construct($error, $reverse);
        $this->pattern = $pattern;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.

    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    /**
     * Checks if a value is valid.
     * 
     * @param mixed $value The value.
     * @param string (optional) $pattern The regex pattern.
     * @throws logicexception If the $pattern parameter is not a valid pattern.
     * @return boolean True if valid, else false.
     */
    protected function _is_valid($value, $pattern = null)
    {
        if ($pattern === null)
        {
            $pattern = $this->pattern;
        }
        
        $valid = preg_match($pattern, $value);
        
        if ($valid === false)
        {
            throw new logicexception('Regex pattern ' . var_export($pattern, true) . ' is not valid.');
        }
        
        return (boolean) $valid;
    }
}
