Files
workbloomerp-backend/app/Shared/Utils/SanitizeUtil.php
T
Claudecio Martins a951944997 first commit
2026-06-16 10:04:10 -03:00

93 lines
2.7 KiB
PHP

<?php
namespace WorkbloomERP\Utils;
class SanitizeUtil {
public static function string(mixed $value): ?string {
if ($value === null) {
return null;
}
$value = trim(string: $value);
$value = strip_tags(string: $value);
return $value;
}
public static function email(mixed $value): ?string {
if ($value === null) {
return null;
}
$value = filter_var(value: $value, filter: FILTER_SANITIZE_EMAIL);
return $value ?: '';
}
public static function int(mixed $value): ?int {
if ($value === null) {
return null;
}
return (int) filter_var(value: $value, filter: FILTER_SANITIZE_NUMBER_INT);
}
public static function float(mixed $value): ?float {
if($value === null) {
return null;
}
return (float) filter_var(
value: $value,
filter: FILTER_SANITIZE_NUMBER_FLOAT,
options: FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND
);
}
public static function document(mixed $value): ?string {
if ($value === null) {
return null;
}
// remove espaços
$value = trim($value);
// converte caracteres especiais (Ç -> C, Á -> A, etc.)
$value = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
// mantém apenas letras e números
$value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
return $value;
}
public static function boolean(mixed $value): ?bool {
if ($value === null) {
return null;
}
if (is_bool($value)) {
return $value;
}
if (is_string($value)) {
$value = strtolower($value);
if (in_array($value, ['true', '1', 'yes'], true)) {
return true;
}
if (in_array($value, ['false', '0', 'no'], true)) {
return false;
}
}
if (is_int($value)) {
return $value === 1;
}
// Se não for possível converter, retorna null
return null;
}
public static function phone(mixed $value, bool $withCountryCode = false): ?string {
if ($value === null) {
return null;
}
// remove tudo que não for número
$value = preg_replace('/\D/', '', $value);
if (!$value) {
return '';
}
// adiciona DDI do Brasil se não tiver
if ($withCountryCode) {
if (strlen($value) === 10 || strlen($value) === 11) {
$value = "55{$value}";
}
}
return $value;
}
}