Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Polyfills are provided for:
- the `ReflectionConstant` class introduced in PHP 8.4
- the `CURL_HTTP_VERSION_3` and `CURL_HTTP_VERSION_3ONLY` constants introduced in PHP 8.4;
- the `grapheme_str_split` function introduced in PHP 8.4;
- the `bcdivmod` function introduced in PHP 8.4;
- the `bcceil`, `bcdivmod`, `bcfloor` and `bcround` functions introduced in PHP 8.4;
- the `get_error_handler` and `get_exception_handler` functions introduced in PHP 8.5;
- the `NoDiscard` attribute introduced in PHP 8.5;
- the `array_first` and `array_last` functions introduced in PHP 8.5;
Expand Down
204 changes: 204 additions & 0 deletions src/Php84/Php84.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ public static function grapheme_str_split(string $string, int $length)
return $chunks;
}

public static function bcceil(string $num): string
{
if (!is_numeric($num)) {
throw new \ValueError('bcceil(): Argument #1 ($num) is not well-formed');
}
return self::bcround($num, 0, \RoundingMode::PositiveInfinity);
}

public static function bcdivmod(string $num1, string $num2, ?int $scale = null): ?array
{
if (null === $quot = \bcdiv($num1, $num2, 0)) {
Expand All @@ -214,4 +222,200 @@ public static function bcdivmod(string $num1, string $num2, ?int $scale = null):

return [$quot, \bcmod($num1, $num2, $scale)];
}

public static function bcfloor(string $num): string
{
if (!is_numeric($num)) {
throw new \ValueError('bcfloor(): Argument #1 ($num) is not well-formed');
}
return self::bcround($num, 0, \RoundingMode::NegativeInfinity);
}

/**
* @param \RoundingMode|\RoundingMode::* $mode
*/
public static function bcround(string $num, int $precision = 0, $mode = \RoundingMode::HalfAwayFromZero): string
{
if (!is_numeric($num)) {
throw new \ValueError('bcround(): Argument #1 ($num) is not well-formed');
}

$sign = 1;
if ('' !== $num && ('-' === $num[0] || '+' === $num[0])) {
if ('-' === $num[0]) {
$sign = -1;
}

$num = substr($num, 1);
}

if (false !== strpos($num, '.')) {
[$intPart, $fracPart] = array_pad(explode('.', $num, 2), 2, '');
} else {
$intPart = $num;
$fracPart = '';
}

if ('' === $intPart) {
$intPart = '0';
}

$intPart = self::trimLeadingZeros($intPart);
$fracPart = (string) $fracPart;

if ($precision >= 0) {
$fracLength = \strlen($fracPart);

if ($precision <= $fracLength) {
$scaledInt = $intPart.(string) substr($fracPart, 0, $precision);
$scaledFrac = (string) substr($fracPart, $precision);
} else {
$scaledInt = $intPart.$fracPart.str_repeat('0', $precision - $fracLength);
$scaledFrac = '';
}
} else {
$shift = -$precision;
$intLength = \strlen($intPart);

if ($shift <= $intLength) {
$splitPos = $intLength - $shift;
$scaledInt = substr($intPart, 0, $splitPos);
$scaledInt = '' === $scaledInt ? '0' : $scaledInt;
$scaledFrac = substr($intPart, $splitPos).$fracPart;
} else {
$scaledInt = '0';
$scaledFrac = str_repeat('0', $shift - $intLength).$intPart.$fracPart;
}
}

$roundedInt = self::roundIntegerPart($scaledInt, $scaledFrac, $sign, $mode);
$isZero = '' === trim($roundedInt, '0');
$absResult = self::formatRoundedDigits($roundedInt, $precision);

if (-1 === $sign && !$isZero) {
$absResult = '-'.$absResult;
}

return $absResult;
}

private static function roundIntegerPart(string $intPart, string $fracPart, int $sign, $mode): string
{
$intPart = self::trimLeadingZeros($intPart);

if ('' === $fracPart || '' === trim($fracPart, '0')) {
return $intPart;
}

$firstDigit = $fracPart[0];
$tail = (string) substr($fracPart, 1);
$tailNonZero = '' !== trim($tail, '0');
$isGreaterThanHalf = $firstDigit > '5' || ('5' === $firstDigit && $tailNonZero);
$isExactlyHalf = '5' === $firstDigit && !$tailNonZero;
$shouldIncrease = false;

switch ($mode) {
case \RoundingMode::TowardsZero:
break;

case \RoundingMode::AwayFromZero:
$shouldIncrease = true;
break;

case \RoundingMode::PositiveInfinity:
$shouldIncrease = $sign > 0;
break;

case \RoundingMode::NegativeInfinity:
$shouldIncrease = $sign < 0;
break;

case \RoundingMode::HalfAwayFromZero:
$shouldIncrease = $isGreaterThanHalf || $isExactlyHalf;
break;

case \RoundingMode::HalfTowardsZero:
$shouldIncrease = $isGreaterThanHalf;
break;

case \RoundingMode::HalfEven:
if ($isGreaterThanHalf) {
$shouldIncrease = true;
} elseif ($isExactlyHalf && self::lastDigit($intPart) % 2 === 1) {
$shouldIncrease = true;
}
break;

case \RoundingMode::HalfOdd:
if ($isGreaterThanHalf) {
$shouldIncrease = true;
} elseif ($isExactlyHalf && self::lastDigit($intPart) % 2 === 0) {
$shouldIncrease = true;
}
break;
}

if ($shouldIncrease) {
$intPart = self::incrementDigits($intPart);
}

return self::trimLeadingZeros($intPart);
}

private static function formatRoundedDigits(string $roundedInt, int $precision): string
{
if ($precision > 0) {
if (\strlen($roundedInt) <= $precision) {
$roundedInt = str_pad($roundedInt, $precision + 1, '0', STR_PAD_LEFT);
}

$intDigits = substr($roundedInt, 0, -$precision);
$fracDigits = substr($roundedInt, -$precision);

$intDigits = self::trimLeadingZeros('' === $intDigits ? '0' : $intDigits);
$fracDigits = str_pad($fracDigits, $precision, '0', STR_PAD_LEFT);

return $intDigits.'.'.$fracDigits;
}

if (0 === $precision) {
return self::trimLeadingZeros($roundedInt);
}

$shift = -$precision;
$digits = $roundedInt.str_repeat('0', $shift);

return self::trimLeadingZeros($digits);
}

private static function incrementDigits(string $digits): string
{
$digits = '' === $digits ? '0' : $digits;
$index = \strlen($digits) - 1;
$result = $digits;
$carry = 1;

while ($index >= 0 && $carry) {
$value = ord($result[$index]) - 48 + $carry;
$carry = $value >= 10 ? 1 : 0;
$result[$index] = chr(48 + ($value % 10));
--$index;
}

return $carry ? '1'.$result : $result;
}

private static function trimLeadingZeros(string $digits): string
{
$digits = ltrim($digits, '0');

return '' === $digits ? '0' : $digits;
}

private static function lastDigit(string $digits): int
{
$length = \strlen($digits);

return $length ? ord($digits[$length - 1]) - 48 : 0;
}
}
55 changes: 55 additions & 0 deletions src/Php84/Resources/stubs/RoundingMode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

/*
if (\PHP_VERSION_ID >= 80100 && \PHP_VERSION_ID < 80400) {
enum RoundingMode {
case HalfAwayFromZero; // Round to the nearest integer. If the decimal part is 5, round to the integer with the larger absolute value.
case HalfTowardsZero; // Round to the nearest integer. If the decimal part is 5, round to the integer with the smaller absolute value.
case HalfEven; // Round to the nearest integer. If the decimal part is 5, round to the even integer.
case HalfOdd; // Round to the nearest integer. If the decimal part is 5, round to the odd integer.
case TowardsZero; // Round to the nearest integer with a smaller or equal absolute value.
case AwayFromZero; // Round to the nearest integer with a greater or equal absolute value.
case NegativeInfinity; // Round to the largest integer that is smaller or equal.
case PositiveInfinity; // Round to the smallest integer that is greater or equal.
}
}
if (\PHP_VERSION_ID < 80100) {
*/
if (\PHP_VERSION_ID < 80400) {
// @author Thomas Durand <[email protected]>
final class RoundingMode {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when PHP >= 8.1 is used, we should use a real enum

Copy link
Author

@Dean151 Dean151 Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nicolas-grekas When I try to introduce an enum, even behind an if PHP_VERSION_ID, older PHP version are complaining pretty badly on the syntax.
See this CI run
An idea?

const HalfAwayFromZero = 0; // Round to the nearest integer. If the decimal part is 5, round to the integer with the larger absolute value.
const HalfTowardsZero = 1; // Round to the nearest integer. If the decimal part is 5, round to the integer with the smaller absolute value.
const HalfEven = 2; // Round to the nearest integer. If the decimal part is 5, round to the even integer.
const HalfOdd = 3; // Round to the nearest integer. If the decimal part is 5, round to the odd integer.
const TowardsZero = 4; // Round to the nearest integer with a smaller or equal absolute value.
const AwayFromZero = 5; // Round to the nearest integer with a greater or equal absolute value.
const NegativeInfinity = 6; // Round to the largest integer that is smaller or equal.
const PositiveInfinity = 7; // Round to the smallest integer that is greater or equal.

private function __construct() {}

public static function cases(): array
{
return [
self::HalfAwayFromZero,
self::HalfTowardsZero,
self::HalfEven,
self::HalfOdd,
self::TowardsZero,
self::AwayFromZero,
self::NegativeInfinity,
self::PositiveInfinity,
];
}
}
}
12 changes: 12 additions & 0 deletions src/Php84/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,21 @@ function mb_rtrim(string $string, ?string $characters = null, ?string $encoding
}

if (extension_loaded('bcmath')) {
if (!function_exists('bcceil')) {
function bcceil(string $num): string { return p\Php84::bcceil($num); }
}
if (!function_exists('bcdivmod')) {
function bcdivmod(string $num1, string $num2, ?int $scale = null): ?array { return p\Php84::bcdivmod($num1, $num2, $scale); }
}
if (!function_exists('bcfloor')) {
function bcfloor(string $num): string { return p\Php84::bcfloor($num); }
}
if (!function_exists('bcround')) {
/**
* @param \RoundingMode|\RoundingMode::* $mode
*/
function bcround(string $num, int $precision = 0, $mode = RoundingMode::HalfAwayFromZero): string { return p\Php84::bcround($num, $precision, $mode); }
}
}

if (\PHP_VERSION_ID >= 80200) {
Expand Down
Loading
Loading