Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 /**
6 * This file is part of the Carbon package.
7 *
8 * (c) Brian Nesbitt <[email protected]>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14 namespace Carbon\Traits;
15
16 use Carbon\CarbonInterval;
17 use Carbon\Exceptions\InvalidIntervalException;
18 use DateInterval;
19
20 /**
21 * Trait to call rounding methods to interval or the interval of a period.
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 }