<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2016 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flLogHandlerChrome Class
 *
 * Log handler for Chrome Logger.
 *
 * @package fusionLib
 * @see http://www.chromelogger.com
 */
class flLogHandlerChrome implements flLogHandler {

	/**
	 * The JSON data to send.
	 *
	 * @var array
	 */
	protected $json = array(
		'version' => '4.1.0',
		'columns' => array('log', 'backtrace', 'type'),
		'rows' => array()
	);

	/**
	 * Constructor.
	 */
	function __construct() {
		$this->json['request_uri'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
	}

	/**
	 * Write a record to the log target.
	 *
	 * @param array $record The record to log.
	 */
	public function write($record) {

		if(!headers_sent()) {

			// Format the message
			$message = (empty($record['channel']) ? '' : $record['channel'] . '.') . $record['level_name'] . ' ';
			if(is_array($record['message']) || (is_object($record['message']) && !method_exists($record['message'], '__toString'))) {
				$message .= json_encode($record['message']);
			} else {
				$message .= (string)$record['message'];
			}

			// Add row
			$this->json['rows'][] = array(
				$message,
				'',
				''
			);

			// Send
			header('X-ChromeLogger-Data: ' . base64_encode(utf8_encode(json_encode($this->json))));
		}
	}
}