events-venues/app/helpers/logging.php

116 lines
2.5 KiB
PHP

<?php
/**
* @package: events-venues-task
* @author: Yevhen Odynets
* @date: 2024-07-28
* @time: 16:12
*/
//phpcs:ignore
declare(strict_types = 1);
use App\{ConsoleStyleInterfaceType as Style, LoggingSeverityLevelsType as LogType};
use Illuminate\Support\Facades\{App, Log};
use Symfony\Component\Console\{Input\ArgvInput, Output\ConsoleOutput, Style\SymfonyStyle};
/**
* @param mixed $e
* @param LogType|null $severity
* @param int|null $code
* @param int|null $traceLine
*
* @return void
*/
function appLog(Exception|string $e, ?LogType $severity = null, ?int $code = null, ?int $traceLine = null): void
{
$severity ??= LogType::notice;
if (is_string($e)) {
$e = new RuntimeException($e);
if (is_null($traceLine)) {
$traceLine = 2;
}
$trace = $e->getTrace()[$traceLine];
$context = [$code ?? $e->getCode(), $trace['file'], $trace['line'], $e->getTrace()[++$traceLine]['function']];
} else {
$context = [$code ?? $e->getCode(), $e->getFile(), $e->getLine(), $e->getTrace()[0]['function']];
}
Log::channel('app')->{$severity->name}($e->getMessage(), $context);
}
/**
* @param Exception|string $e
* @param Style $cmd
*
* @return void
* @throws ReflectionException
*/
function appConsole(Exception|string $e, Style $cmd): void
{
if (! is_string($e)) {
$e = $e->getMessage();
}
// $reflection = new ReflectionClass($e);
// if (! $reflection->isSubclassOf(Exception::class)) {
// $e = $e->getMessage();
// }
if (App::runningInConsole()) {
$io = new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
$io->{$cmd->name}($e);
}
}
/**
* @param Exception|string $e
*
* @return void
* @throws ReflectionException
*/
function appWarning(Exception|string $e): void
{
appLog($e, LogType::warning);
appConsole($e, Style::warning);
}
/**
* @param mixed $e
*
* @return void
* @throws ReflectionException
*/
function appSuccess(Exception|string $e): void
{
appLog($e, LogType::info);
appConsole($e, Style::success);
}
/**
* @param mixed $e
*
* @return void
* @throws ReflectionException
*/
function appInfo(Exception|string $e): void
{
appLog($e, LogType::info);
appConsole($e, Style::note);
}
/**
* @param mixed $e
*
* @return void
* @throws ReflectionException
*/
function appNotice(Exception|string $e): void
{
appLog($e, LogType::notice);
appConsole($e, Style::note);
}