| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
namespace Carbon\Traits; |
| 15 |
|
| 16 |
use Carbon\CarbonInterval; |
| 17 |
use Carbon\Exceptions\InvalidIntervalException; |
| 18 |
use DateInterval; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
trait IntervalRounding |
| 24 |
{ |
| 25 |
protected function callRoundMethod(string $method, array $parameters): ?static |
| 26 |
{ |
| 27 |
$action = substr($method, 0, 4); |
| 28 |
|
| 29 |
if ($action !== 'ceil') { |
| 30 |
$action = substr($method, 0, 5); |
| 31 |
} |
| 32 |
|
| 33 |
if (\in_array($action, ['round', 'floor', 'ceil'])) { |
| 34 |
return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters); |
| 35 |
} |
| 36 |
|
| 37 |
return null; |
| 38 |
} |
| 39 |
|
| 40 |
protected function roundWith(DateInterval|string|float|int $precision, callable|string $function): ?static |
| 41 |
{ |
| 42 |
$unit = 'second'; |
| 43 |
|
| 44 |
if ($precision instanceof DateInterval) { |
| 45 |
$precision = CarbonInterval::instance($precision)->forHumans(['locale' => 'en']); |
| 46 |
} |
| 47 |
|
| 48 |
if (\is_string($precision) && preg_match('/^\s*(?<precision>\d+)?\s*(?<unit>\w+)(?<other>\W.*)?$/', $precision, $match)) { |
| 49 |
if (trim($match['other'] ?? '') !== '') { |
| 50 |
throw new InvalidIntervalException('Rounding is only possible with single unit intervals.'); |
| 51 |
} |
| 52 |
|
| 53 |
$precision = (int) ($match['precision'] ?: 1); |
| 54 |
$unit = $match['unit']; |
| 55 |
} |
| 56 |
|
| 57 |
return $this->roundUnit($unit, $precision, $function); |
| 58 |
} |
| 59 |
} |