php-censor/src/PHPCensor/Logging/LoggerConfig.php

89 lines
2.2 KiB
PHP
Raw Normal View History

<?php
2016-07-19 20:28:11 +02:00
namespace PHPCensor\Logging;
use Monolog\Logger;
/**
* Class LoggerConfig
*/
2014-02-27 15:23:51 +01:00
class LoggerConfig
{
const KEY_ALWAYS_LOADED = "_";
private $config;
2016-04-20 17:39:48 +02:00
private $cache = [];
/**
* The filepath is expected to return an array which will be
* passed to the normal constructor.
*
* @param string $filePath
* @return LoggerConfig
*/
public static function newFromFile($filePath)
{
if (file_exists($filePath)) {
$configArray = require($filePath);
2014-02-27 15:23:51 +01:00
} else {
2016-04-20 17:39:48 +02:00
$configArray = [];
}
return new self($configArray);
}
/**
* Each key of the array is the name of a logger. The value of
* each key should be an array or a function that returns an
* array of LogHandlers.
* @param array $configArray
*/
2016-04-20 17:39:48 +02:00
public function __construct(array $configArray = [])
2014-02-27 15:23:51 +01:00
{
$this->config = $configArray;
}
/**
* Returns an instance of Monolog with all configured handlers
* added. The Monolog instance will be given $name.
* @param $name
* @return Logger
*/
2014-02-27 15:23:51 +01:00
public function getFor($name)
{
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
2014-02-27 15:23:51 +01:00
$handlers = $this->getHandlers(self::KEY_ALWAYS_LOADED);
if ($name !== self::KEY_ALWAYS_LOADED) {
$handlers = array_merge($handlers, $this->getHandlers($name));
}
$logger = new Logger($name, $handlers);
2017-01-11 16:15:54 +01:00
Handler::register($logger);
$this->cache[$name] = $logger;
return $logger;
}
/**
* Return an array of enabled log handlers.
* @param $key
* @return array|mixed
*/
2014-02-27 15:23:51 +01:00
protected function getHandlers($key)
{
2016-04-20 17:39:48 +02:00
$handlers = [];
// They key is expected to either be an array or
// a callable function that returns an array
if (isset($this->config[$key])) {
if (is_callable($this->config[$key])) {
$handlers = call_user_func($this->config[$key]);
2014-02-27 15:23:51 +01:00
} elseif (is_array($this->config[$key])) {
$handlers = $this->config[$key];
}
}
return $handlers;
}
2014-02-27 15:23:51 +01:00
}