nur-sery/src/output/msg.php

78 lines
2.2 KiB
PHP

<?php
namespace nur\sery\output;
use nur\sery\output\std\ProxyMessenger;
use nur\sery\php\func;
use nur\sery\ValueException;
/**
* Class msg: inscrire un message dans les logs ET l'afficher sur la console
*
* Cette classe DOIT être initialisée avec {@link set_messenger()} ou
* {@link set_messenger_class()} avant d'être utilisée.
*/
class msg extends _messenger {
private static ?IMessenger $msg = null;
private static bool $setup = false;
static function is_setup(): bool {
return self::$setup;
}
static function set_messenger(IMessenger $msg) {
self::$msg = $msg;
self::$setup = true;
}
static function get(): IMessenger {
return self::$msg ??= new ProxyMessenger();
}
/**
* initialiser les instances say, console, log.
*/
static function init(array $msgs) {
$say = $msgs["say"] ?? null;
$console = $msgs["console"] ?? null;
$log = $msgs["log"] ?? null;
$msgs = [];
if ($log !== null && $log !== false) {
if ($log instanceof IMessenger) log::set_messenger($log);
elseif (is_string($log)) log::set_messenger_class($log);
elseif (is_array($log)) {
func::ensure_class($log, $args);
$log = func::cons($log, $args);
}
log::set_messenger($log);
$msgs[] = $log;
}
if ($console !== null && $console !== false) {
if ($console instanceof IMessenger) console::set_messenger($console);
elseif (is_string($console)) console::set_messenger_class($console);
elseif (is_array($console)) {
func::ensure_class($console, $args);
$console = func::cons($console, $args);
}
console::set_messenger($console);
$msgs[] = $console;
}
if ($say !== null && $say !== false) {
if ($say instanceof IMessenger) say::set_messenger($say);
elseif (is_string($say)) say::set_messenger_class($say);
elseif (is_array($say)) {
func::ensure_class($say, $args);
$say = func::cons($say, $args);
}
say::set_messenger($say);
$msgs[] = $say;
}
if ($say === null && $console !== null) {
say::set_messenger($console);
} elseif ($console === null && $say !== null) {
console::set_messenger($say);
}
self::set_messenger(new ProxyMessenger(...$msgs));
}
}