first commit
This commit is contained in:
69
app/Common/Helpers/Sanitizer.php
Executable file
69
app/Common/Helpers/Sanitizer.php
Executable file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
namespace Zampet\Helpers;
|
||||
|
||||
use DateTime;
|
||||
|
||||
class Sanitizer {
|
||||
public static function string(mixed $value): string|null {
|
||||
if(is_null($value)) {
|
||||
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($value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$date = DateTime::createFromFormat('!'.$format, $value);
|
||||
|
||||
if (!$date) {
|
||||
// tenta converter qualquer formato válido
|
||||
$date = date_create($value);
|
||||
}
|
||||
|
||||
return $date ? $date->format($format) : '';
|
||||
}
|
||||
|
||||
public static function datetime(string $value, string $format = 'Y-m-d H:i:s'): string {
|
||||
$value = trim($value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$date = DateTime::createFromFormat('!'.$format, $value);
|
||||
|
||||
if (!$date) {
|
||||
$date = date_create($value);
|
||||
}
|
||||
|
||||
return $date ? $date->format($format) : '';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user