<?php
/**
 * An abstract class for log writers.
 *
 * This class provides a filtering mechanism.
 */
abstract class log_filter implements log_writer
{
    /**
     * @var integer The priority filter.
     */
    protected $filter;

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

    /**
     * @param integer (optional) $filter The priority filter.
     * @throws outofrangeexception If the priority does not exist.
     */
    public function __construct($filter = log::DEBUG)
    {
        if (!in_array($filter, range(0, 8), true))
        {
            throw new outofrangeexception('Filter priority ' . $filter . ' does not exist.');
        }
        
        $this->filter = $filter;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    /**
     * Writes a log message to storage.
     *
     * @param string $message The message.
     * @param integer (optional) $priority The priority filter.
     * @param string (optional) $timestamp The date.
     * @throws outofrangeexception If the priority does not exist.
     * @return log_filter A fluent interface.
     */
    public function write($message, $priority = log::EMERGENCY, $timestamp = null)
    {
        if (!in_array($priority, range(0, 8), true))
        {
            throw new outofrangeexception('Priority ' . $priority . ' does not exist.');
        }
        
        if ($this->filter < $priority)
        {
            return $this;
        }
        
        if ($timestamp === null)
        {
            $timestamp = date('c');
        }
        
        return $this->_write($message, $priority, $timestamp);
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    /**
     * Writes a log message to storage.
     *
     * @param string $message The message.
     * @param integer $priority The priority.
     * @param string $timestamp The date.
     * @return log_filter A fluent interface.
     */
    protected abstract function _write($message, $priority, $timestamp);
}
