<?php
/**
 * Cpanel_Listner_Observer_GenericLogger
 * 
 * Copyright (c) 2011, cPanel, Inc.
 * All rights reserved.
 * http://cpanel.net
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    * Neither the name of cPanel, Inc. nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * @category   Cpanel
 * @package    Cpanel_Listner
 * @subpackage Observer
 * @author     David Neimeyer <david.neimeyer@cpanel.net>
 * @copyright  (c) 2011 cPanel, Inc., All rights Reserved. (http://cpanel.net) 
 * @license    http://sdk.cpanel.net/license/bsd.html BSD License 
 * @version    0.1.0
 * @link       http://sdk.cpanel.net
 * @since      0.1.0
 */
/**
 * An observer class for logging data
 *
 * @class      Cpanel_Listner_Observer_GenericLogger
 * @category   Cpanel
 * @package    Cpanel_Listner
 * @subpackage Observer
 * @author     David Neimeyer <david.neimeyer@cpanel.net>
 * @copyright  (c) 2011 cPanel, Inc., All rights Reserved. (http://cpanel.net) 
 * @license    http://sdk.cpanel.net/license/bsd.html BSD License 
 * @version    0.1.0
 * @link       http://sdk.cpanel.net
 * @since      0.1.0
 */
class Cpanel_Listner_Observer_GenericLogger extends Cpanel_Core_Object implements SplObserver
{
    /**
     * Verbosity level map
     */
    private $_levelkey;
    /**
     * Constructor
     * 
     * Passing 'level'=>$value in configuration data array will set the logger's
     * verbosity level.  Verbosity levels response to specific types of logged
     * messages generated by the log listner. Valid verbosity levels are:
     *   'loud'    - will response to any logged message
     *   'verbose' - will response to 'info', 'warn' and 'die' messages 
     *   'std'     - will only response to 'warn' and 'die' messages
     *   'quiet'   - will only response to 'die' messages
     *   'silent'  - will never log any messages
     * 
     * @param array $optArray Optional configuration data
     * 
     * @return Cpanel_Listner_Observer_GenericLogger
     */
    public function __construct($optArray = array())
    {
        //TODO: break this out into methods
        $this->_levelkey = array(
            'loud' => array(
                'debug',
                'info',
                'warn',
                'die'
            ),
            'verbose' => array(
                'info',
                'warn',
                'die'
            ),
            'std' => array(
                'warn',
                'die'
            ),
            'quiet' => array(
                'die'
            ),
            'silent' => array(),
        );
        if (!array_key_exists('level', $optArray)) {
            $optArray['level'] = 'std';
        }
        $tz = (ini_get('date.timezone')) ? ini_get('date.timezone') : 'UTC';
        date_default_timezone_set($tz);
        parent::__construct($optArray);
        return $this;
    }
    /**
     * Log data to error_log
     * 
     * @param SplSubject $sub Calling subject listner
     * 
     * @see    SplObserver::update()
     * @return Cpanel_Listner_Observer_GenericLogger
     */
    public function update(SplSubject $sub)
    {
        if ($sub->getDebugLevel() !== $this->level) {
            $this->level = $sub->getDebugLevel();
        }
        $log = $sub->getLog();
        if (!empty($log)) {
            foreach ($log as $key => $value) {
                $key = strtolower($key);
                if (in_array($key, $this->_levelkey[$this->level])) {
                    error_log("[" . date('Y-m-d H:i:s O') . "] $key: $value");
                }
            }
        } elseif (property_exists($sub, 'response') && $sub->response) {
            //example of obj munging possible my PHP object passing by ref by default
            echo get_class($this) . ": pre: " . $sub->response->data->item . "\n";
            $sub->response->data->item = 'new data!';
            echo get_class($this) . ": post: " . $sub->response->data->item . "\n";
        }
        return $this;
    }
    /**
     * Simple log creator.
     * 
     * The method allow a subject/observer logger to be easily generated anyway
     * in the code base and attached to any object. 
     *
     * @param object &$obj       Object to inject subject logger into
     * @param int    $priority   Order within subject queue
     * @param array  $cfg        Any configuration data to pass to the observer,
     *  like log level
     * @param object $listner    Previous instance of
     *  Cpanel_Listeners_CpanelLogger to attach the observer to
     * @param string $debugLevel Debug level to pass to this subject
     * 
     * @return object          The object passed in as the first parameter with
     *                         logger stored at "listner" property
     * @throws Exception If first argument is not an object
     * @throws Exception If $listner was passed and not an instance of
     *                         Cpanel_Listner_Subject_Abstract
     */
    public static function initLogger(&$obj, $priority = 1, $cfg = array(), $listner = null, $debugLevel = 'std')
    {
        if (!is_object($obj)) {
            throw new Exception('First argument must be an object');
        } elseif (empty($listner)) {
            // look into $obj
            if ($obj instanceof Cpanel_Core_Object) {
                $listner = $obj->listner;
            } elseif (property_exists($obj, 'listner')) {
                $listner = $obj->listner;
            }
        }
        if (empty($listner)) {
            $listner = new Cpanel_Listner_Subject_Logger($debugLevel);
        } elseif (!$listner instanceof Cpanel_Listner_Subject_Abstract) {
            throw new Exception(
                'Passed listner object is not an instance of CpanelListner'
            );
        }
        if (!is_int($priority)) {
            $priority = 1;
        }
        $listner->attach(new self($cfg), $priority);
        $obj->listner = $listner;
        return $obj;
    }
}
?>