<?php
/**
 * A class for replacing all patterned occurrences in strings with others.
 */
class filter_pattern implements filter
{
    /**
     * @var string/array The search pattern.
     */
    protected $search;
    
    /**
     * @var string/array The replacement.
     */
    protected $replace;
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.

    /**
     * @param string/array $search The search pattern.
     * @param string/array (optional) $replace The replacement.
     */
    public function __construct($search, $replace = '')
    {
        $this->search = $search;
        $this->replace = $replace;
    }

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

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

    /**
     * Filters a value.
     * 
     * @param string $value The value.
     * @param string/array (optional) $search The search pattern.
     * @param string/array (optional) $replace The replacement.
     * @throws logicexception If the $search parameter is not a valid pattern.
     * @return string The filtered value.
     */
    public function filter($value, $search = null, $replace = null)
    {
        if ($search === null)
        {
            $search = $this->search;
        }
        
        if ($replace === null)
        {
            $replace = $this->replace;
        }
        
        $value = preg_replace($search, $replace, $value);
        
        if ($value === false)
        {
            throw new logicexception('Regex pattern ' . ((is_array($search)) ? print_r($search, true) : var_export($search, true)) . ' is not valid.');
        }
        
        return $value;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
