Files
controls-web/controls-rework/overviews/data/module-helpers.php
2026-02-17 09:29:34 -06:00

110 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
// phpcs:disable
function module_numeric($value): ?float
{
if ($value === null) {
return null;
}
if (is_numeric($value)) {
return (float) $value;
}
$normalised = str_replace([',', ' '], '', (string) $value);
$normalised = preg_replace('/[^0-9.\-]/', '', $normalised ?? '');
if ($normalised === '' || !is_numeric($normalised)) {
return null;
}
return (float) $normalised;
}
function module_number($value, int $decimals = 0, string $placeholder = '—'): string
{
$numeric = module_numeric($value);
return $numeric === null ? $placeholder : number_format($numeric, $decimals);
}
function module_with_unit($value, string $unit, int $decimals = 0, string $placeholder = '—'): string
{
$formatted = module_number($value, $decimals, $placeholder);
return $formatted === $placeholder ? $formatted : $formatted . ' ' . $unit;
}
function module_percent($value, int $decimals = 0, string $placeholder = '—'): string
{
$numeric = module_numeric($value);
if ($numeric === null) {
return $placeholder;
}
return number_format($numeric, $decimals) . '%';
}
function module_clamp_percent($value): float
{
$numeric = module_numeric($value);
if ($numeric === null) {
return 0.0;
}
return max(0.0, min(100.0, $numeric));
}
function module_status(string $label, string $class): string
{
return '<span class="module-pill ' . htmlspecialchars($class, ENT_QUOTES, 'UTF-8') . '">' .
htmlspecialchars($label, ENT_QUOTES, 'UTF-8') .
'</span>';
}
function module_html(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function module_wrap(string $content, string $class): string
{
return '<div class="' . module_html($class) . '">' . $content . '</div>';
}
function module_if(bool $condition, callable $callback): string
{
return $condition ? (string) $callback() : '';
}
function module_non_empty(?string $value, string $fallback = '—'): string
{
return $value === null || $value === '' ? $fallback : $value;
}
function module_capture(string $path): string
{
ob_start();
include $path;
return trim((string) ob_get_clean());
}
function module_mode(?int $value, int $autoValue = 1, string $fallback = '—'): string
{
if ($value === null) {
return $fallback;
}
$isAuto = (int) $value === $autoValue;
$label = $isAuto ? 'Auto' : 'Manual';
$class = $isAuto ? 'module-pill--success' : 'module-pill--warn';
return module_status($label, $class);
}
// phpcs:enable