Decimal.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use function is_numeric;
  9. use function is_string;
  10. use function number_format;
  11. use function preg_replace;
  12. use function var_export;
  13. /**
  14. * Validates the decimal
  15. *
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class Decimal extends AbstractRule
  19. {
  20. /**
  21. * @var int
  22. */
  23. private $decimals;
  24. public function __construct(int $decimals)
  25. {
  26. $this->decimals = $decimals;
  27. }
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function validate($input): bool
  32. {
  33. if (!is_numeric($input)) {
  34. return false;
  35. }
  36. return $this->toFormattedString($input) === $this->toRawString($input);
  37. }
  38. /**
  39. * @param mixed $input
  40. */
  41. private function toRawString($input): string
  42. {
  43. if (is_string($input)) {
  44. return $input;
  45. }
  46. return var_export($input, true);
  47. }
  48. /**
  49. * @param mixed $input
  50. */
  51. private function toFormattedString($input): string
  52. {
  53. $formatted = number_format((float) $input, $this->decimals, '.', '');
  54. if (is_string($input)) {
  55. return $formatted;
  56. }
  57. return preg_replace('/^(\d+\.\d)0*$/', '$1', $formatted) ?: '';
  58. }
  59. }