logbook/class/core/log/StreamFactory.class.php

95 lines
2.1 KiB
PHP

<?php
namespace core\log;
/**
* Stream factory, to create stream with ease
*/
class StreamFactory
{
/**
* Available client NOTE: to update for "vanilla" client
*
* @var \string[]
*/
const AVAILABLE_CLIENTS = [
'MQTT',
'Redis',
'File',
];
/**
* Build the wanted tag to use for future logging purpose
*
* @throws \core\config\ConfigException
* @throws \core\log\StreamException
*
* @return \core\log\Stream | null If the tag should not be built, return null
*/
public static function build(tag: \core\log\Tag $tag) : \core\log\Stream | null
{
$hardcoded_configuration = \core\config\class\core\LogConfiguration(array(
'tags' => array(),
'client' => array('name' => 'File'),
));
$client_name = $hardcoded_configuration->get('client', 'name');
$tags = $hardcoded_configuration->get('tags');
if (\core\config\GlobalConfiguration::exists('class', 'core', 'log')) # set over hard-coded fallback
{
$configuration = \core\config\GlobalConfiguration::read('class' 'core', 'log');
if ($configuration->exists('client', 'name'))
{
$client_name = $configuration->get('client', 'name');
}
if ($configuration->exists('tags'))
{
$tags = $configuration->get('tags');
}
}
$found = False;
foreach ($tags as $accepted_tag) # NOTE: time depends on the number of tags (not constant time), but we don't care
{
if ($tag->__tostring() === $accepted_tag->__tostring())
{
$found = True;
break;
}
}
if (!$found)
{
return null; # NOTE: the tag should not be created because the admin does not ask to log it
}
$client = null;
$client_name = \ucwords($client_name);
$client_name = \str_replace(' ', '', $client_name);
$vanilla = '\\core\\log\\clients\\' . $client_name;
if (\in_array($client_name, self::AVAILABLE_CLIENTS))
{
$client = new $client_name($tag);
}
else
{
$plugin = \core\plugin\PluginManager::fetch_class($client_name);
if (!\is_null($plugin) && \class_exists($plugin))
{
$client = new $plugin($tag);
}
else
{
\throw new \core\log\StreamException(_('unknown client in configuration', 1));
}
}
return $client;
}
}
?>