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