Valor con pruebas

This commit is contained in:
Juan Pablo Vial
2025-04-28 20:20:43 -04:00
parent 4845801b27
commit 5d939f970b
3 changed files with 139 additions and 8 deletions

View File

@ -4,6 +4,7 @@ namespace Incoviba\Service;
use DateTimeInterface;
use DateTimeImmutable;
use DateMalformedStringException;
use function PHPUnit\Framework\countOf;
class Valor
{
@ -11,15 +12,22 @@ class Valor
public function clean(string|float|int $value): float
{
if ((float) $value == $value) {
if (!is_string($value)) {
return (float) $value;
}
return (float) str_replace(['.', ','], ['', '.'], $value);
if ((int) $value == $value) {
return (float) $value;
}
if ($this->isUS($value)) {
return $this->formatUS($value);
}
return $this->formatCL($value);
}
public function toPesos(string $value, null|string|DateTimeInterface $date = null, bool $force = false): int
{
$date = $this->getDateTime($date);
if (abs((float) $value - (int) $value) > 0 or $force) {
if ($this->isFloat($value) or $force) {
return round($value * $this->ufService->get($date));
}
return (int) $value;
@ -27,7 +35,7 @@ class Valor
public function toUF(string $value, null|string|DateTimeInterface $date = null, bool $force = false): float
{
$date = $this->getDateTime($date);
if (abs((float) $value - (int) $value) > 0 and !$force) {
if ($this->isFloat($value) and !$force) {
return (float) $value;
}
return $value / $this->ufService->get($date);
@ -47,4 +55,58 @@ class Valor
}
return $date;
}
protected function isUS(string $value): bool
{
/*
* Chile
* 1.000.000,00
* 10000,000
* 10,53
* 1.000,00
* 1.000 imposible! se asume US si # antes de . < 10
*
* 1,000,000.00
* 10000.00
* 1,000.000
* 10.53
* 1,000 imposible! se asume CL
*/
if (str_contains($value, '.')) {
$parts = explode('.', $value);
if (count($parts) > 2) { // 1.000.000 || 1.000.000,00
return false;
}
if (strlen($parts[0]) > 3) { // 1000.000 || 1,000.000
return true;
}
if (str_contains($value, ',')) {
if (strpos($value, ',') > strpos($value, '.')) { // 1.000,000
return false;
}
return true; // 1,000.000
}
if ((int) $parts[0] < 10) {
return true;
}
return false;
}
return true;
}
protected function formatCL(string $value): float
{
return (float) str_replace(',', '.', (str_replace('.', '', $value)));
}
protected function formatUS(string $value): float
{
return (float) str_replace(',', '', $value);
}
protected function isFloat(string|int|float $value): bool
{
if (!is_string($value)) {
return is_float($value);
}
$cleaned = $this->clean($value);
return round($cleaned) !== $cleaned;
}
}