2024-07-03 15:13:13 -04:00
|
|
|
<?php
|
|
|
|
namespace Incoviba\Service;
|
|
|
|
|
2025-04-11 17:34:40 +00:00
|
|
|
use DateTimeInterface;
|
|
|
|
use DateTimeImmutable;
|
|
|
|
use DateMalformedStringException;
|
|
|
|
|
2024-07-03 15:13:13 -04:00
|
|
|
class Valor
|
|
|
|
{
|
2025-04-11 17:34:40 +00:00
|
|
|
public function __construct(protected UF $ufService) {}
|
|
|
|
|
2024-07-03 15:13:13 -04:00
|
|
|
public function clean(string|float|int $value): float
|
|
|
|
{
|
|
|
|
if ((float) $value == $value) {
|
|
|
|
return (float) $value;
|
|
|
|
}
|
|
|
|
return (float) str_replace(['.', ','], ['', '.'], $value);
|
|
|
|
}
|
2025-04-11 17:34:40 +00:00
|
|
|
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) {
|
|
|
|
return round($value * $this->ufService->get($date));
|
|
|
|
}
|
|
|
|
return (int) $value;
|
|
|
|
}
|
|
|
|
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) {
|
|
|
|
return (float) $value;
|
|
|
|
}
|
|
|
|
return $value / $this->ufService->get($date);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface
|
|
|
|
{
|
|
|
|
if ($date === null) {
|
|
|
|
return new DateTimeImmutable();
|
|
|
|
}
|
|
|
|
if (is_string($date)) {
|
|
|
|
try {
|
|
|
|
return new DateTimeImmutable($date);
|
|
|
|
} catch (DateMalformedStringException) {
|
|
|
|
return new DateTimeImmutable();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return $date;
|
|
|
|
}
|
2024-07-03 15:13:13 -04:00
|
|
|
}
|