Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/IntervalStep.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\Callback;
17 use Carbon\Carbon;
18 use Carbon\CarbonImmutable;
19 use Carbon\CarbonInterface;
20 use Closure;
21 use DateTimeImmutable;
22 use DateTimeInterface;
23
24 trait IntervalStep
25 {
26 /**
27 * Step to apply instead of a fixed interval to get the new date.
28 *
29 * @var Closure|null
30 */
31 protected $step;
32
33 /**
34 * Get the dynamic step in use.
35 *
36 * @return Closure
37 */
38 public function getStep(): ?Closure
39 {
40 return $this->step;
41 }
42
43 /**
44 * Set a step to apply instead of a fixed interval to get the new date.
45 *
46 * Or pass null to switch to fixed interval.
47 *
48 * @param Closure|null $step
49 */
50 public function setStep(?Closure $step): void
51 {
52 $this->step = $step;
53 }
54
55 /**
56 * Take a date and apply either the step if set, or the current interval else.
57 *
58 * The interval/step is applied negatively (typically subtraction instead of addition) if $negated is true.
59 *
60 * @param DateTimeInterface $dateTime
61 * @param bool $negated
62 *
63 * @return CarbonInterface
64 */
65 public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface
66 {
67 /** @var CarbonInterface $carbonDate */
68 $carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime);
69
70 if ($this->step) {
71 $carbonDate = Callback::parameter($this->step, $carbonDate->avoidMutation());
72
73 return $carbonDate->modify(($this->step)($carbonDate, $negated)->format('Y-m-d H:i:s.u e O'));
74 }
75
76 if ($negated) {
77 return $carbonDate->rawSub($this);
78 }
79
80 return $carbonDate->rawAdd($this);
81 }
82
83 /**
84 * Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance.
85 */
86 private function resolveCarbon(DateTimeInterface $dateTime): Carbon|CarbonImmutable
87 {
88 if ($dateTime instanceof DateTimeImmutable) {
89 return CarbonImmutable::instance($dateTime);
90 }
91
92 return Carbon::instance($dateTime);
93 }
94 }