69 lines
2.2 KiB
PHP
69 lines
2.2 KiB
PHP
<?php
|
|
namespace Workbloom\Helpers;
|
|
|
|
use DateTime;
|
|
|
|
class DataSanitizer {
|
|
public static function string(mixed $value): string|null {
|
|
if($value === null) {
|
|
return null;
|
|
}
|
|
return trim(string: strip_tags(string: $value));
|
|
}
|
|
|
|
public static function int(mixed $value): int {
|
|
return filter_var(value: $value, filter: FILTER_VALIDATE_INT) ?? 0;
|
|
}
|
|
|
|
public static function float(mixed $value): float {
|
|
return filter_var(value: $value, filter: FILTER_VALIDATE_FLOAT) ?? 0.0;
|
|
}
|
|
|
|
public static function email(string $value): string {
|
|
$value = trim(string: strtolower(string: $value));
|
|
return filter_var(value: $value, filter: FILTER_VALIDATE_EMAIL) ?: '';
|
|
}
|
|
|
|
public static function phone(string $value): string {
|
|
// remove tudo que não for número
|
|
return preg_replace(pattern: '/\D+/', replacement: '', subject: $value) ?? '';
|
|
}
|
|
|
|
public static function document(string $value): string {
|
|
// CPF, CNPJ, RG etc. só números
|
|
return preg_replace(pattern: '/\D+/', replacement: '', subject: $value) ?? '';
|
|
}
|
|
|
|
public static function date(string $value, string $format = 'Y-m-d'): string {
|
|
$value = trim(string: $value);
|
|
|
|
if ($value === '') {
|
|
return '';
|
|
}
|
|
|
|
$date = DateTime::createFromFormat(format: "!{$format}", datetime: $value);
|
|
|
|
if (!$date) {
|
|
// tenta converter qualquer formato válido
|
|
$date = date_create(datetime: $value);
|
|
}
|
|
|
|
return $date ? $date->format(format: $format) : '';
|
|
}
|
|
|
|
public static function datetime(string $value, string $format = 'Y-m-d H:i:s'): string {
|
|
$value = trim(string: $value);
|
|
|
|
if ($value === '') {
|
|
return '';
|
|
}
|
|
|
|
$date = DateTime::createFromFormat(format: "!{$format}", datetime: $value);
|
|
|
|
if (!$date) {
|
|
$date = date_create(datetime: $value);
|
|
}
|
|
|
|
return $date ? $date->format(format: $format) : '';
|
|
}
|
|
} |