BCMathCalculator.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * League.Uri (https://uri.thephpleague.com)
  4. *
  5. * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace League\Uri\IPv4;
  12. use function bcadd;
  13. use function bccomp;
  14. use function bcdiv;
  15. use function bcmod;
  16. use function bcmul;
  17. use function bcpow;
  18. use function bcsub;
  19. use function str_split;
  20. final class BCMathCalculator implements Calculator
  21. {
  22. private const SCALE = 0;
  23. private const CONVERSION_TABLE = [
  24. '0' => '0', '1' => '1', '2' => '2', '3' => '3',
  25. '4' => '4', '5' => '5', '6' => '6', '7' => '7',
  26. '8' => '8', '9' => '9', 'a' => '10', 'b' => '11',
  27. 'c' => '12', 'd' => '13', 'e' => '14', 'f' => '15',
  28. ];
  29. public function baseConvert(mixed $value, int $base): string
  30. {
  31. $value = (string) $value;
  32. if (10 === $base) {
  33. return $value;
  34. }
  35. $base = (string) $base;
  36. $decimal = '0';
  37. foreach (str_split($value) as $char) {
  38. $decimal = bcadd($this->multiply($decimal, $base), self::CONVERSION_TABLE[$char], self::SCALE);
  39. }
  40. return $decimal;
  41. }
  42. public function pow(mixed $value, int $exponent): string
  43. {
  44. return bcpow((string) $value, (string) $exponent, self::SCALE);
  45. }
  46. public function compare(mixed $value1, $value2): int
  47. {
  48. return bccomp((string) $value1, (string) $value2, self::SCALE);
  49. }
  50. public function multiply(mixed $value1, $value2): string
  51. {
  52. return bcmul((string) $value1, (string) $value2, self::SCALE);
  53. }
  54. public function div(mixed $value, mixed $base): string
  55. {
  56. return bcdiv((string) $value, (string) $base, self::SCALE);
  57. }
  58. public function mod(mixed $value, mixed $base): string
  59. {
  60. return bcmod((string) $value, (string) $base, self::SCALE);
  61. }
  62. public function add(mixed $value1, mixed $value2): string
  63. {
  64. return bcadd((string) $value1, (string) $value2, self::SCALE);
  65. }
  66. public function sub(mixed $value1, mixed $value2): string
  67. {
  68. return bcsub((string) $value1, (string) $value2, self::SCALE);
  69. }
  70. }