blob: 6f6c9d1d20407b4627e9753b72439fce17248926 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/**
4 * This file is part of the Carbon package.
5 *
6 * (c) Brian Nesbitt <brian@nesbot.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11namespace Carbon\Traits;
12
13use Carbon\CarbonInterval;
14use Carbon\Exceptions\InvalidIntervalException;
15use DateInterval;
16
17/**
18 * Trait to call rounding methods to interval or the interval of a period.
19 */
20trait IntervalRounding
21{
22 protected function callRoundMethod(string $method, array $parameters)
23 {
24 $action = substr($method, 0, 4);
25
26 if ($action !== 'ceil') {
27 $action = substr($method, 0, 5);
28 }
29
30 if (\in_array($action, ['round', 'floor', 'ceil'])) {
31 return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters);
32 }
33
34 return null;
35 }
36
37 protected function roundWith($precision, $function)
38 {
39 $unit = 'second';
40
41 if ($precision instanceof DateInterval) {
42 $precision = (string) CarbonInterval::instance($precision);
43 }
44
45 if (\is_string($precision) && preg_match('/^\s*(?<precision>\d+)?\s*(?<unit>\w+)(?<other>\W.*)?$/', $precision, $match)) {
46 if (trim($match['other'] ?? '') !== '') {
47 throw new InvalidIntervalException('Rounding is only possible with single unit intervals.');
48 }
49
50 $precision = (int) ($match['precision'] ?: 1);
51 $unit = $match['unit'];
52 }
53
54 return $this->roundUnit($unit, $precision, $function);
55 }
56}