Completed
Pull Request — master (#93)
by ignace nyamagana
11:38 queued 09:44
created

Period::getStartDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
/**
4
 * League.Period (https://period.thephpleague.com)
5
 *
6
 * (c) Ignace Nyamagana Butera <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace League\Period;
15
16
use DateInterval;
17
use DatePeriod;
18
use DateTimeImmutable;
19
use DateTimeInterface;
20
use DateTimeZone;
21
use JsonSerializable;
22
use function array_filter;
23
use function array_keys;
24
use function implode;
25
use function preg_match;
26
use function sprintf;
27
use function strlen;
28
use function substr;
29
30
/**
31
 * A immutable value object class to manipulate Time interval.
32
 *
33
 * @package League.period
34
 * @author  Ignace Nyamagana Butera <[email protected]>
35
 * @since   1.0.0
36
 */
37
final class Period implements JsonSerializable
38
{
39
    private const ISO8601_FORMAT = 'Y-m-d\TH:i:s.u\Z';
40
41
    private const ISO8601_REGEXP = '/^
42
        (?<date>
43
            (?<year>\d+)
44
            (-(?<month>1[0-2]|0[1-9]))?
45
            (-(?<day>3[01]|0[1-9]|[12][0-9]))?
46
        )
47
        (T(?<time>
48
            (?<hour>2[0-3]|[01][0-9])
49
            (:(?<minute>[0-5][0-9]))?
50
            (:(?<second>[0-5][0-9])(\.(?<micro>\d+))?)?
51
        ))?
52
        (?<utc>Z)?
53
     $/x';
54
55
    private const BOUNDARY_TYPE = [
56
        self::INCLUDE_START_EXCLUDE_END => 1,
57
        self::INCLUDE_ALL => 1,
58
        self::EXCLUDE_START_INCLUDE_END => 1,
59
        self::EXCLUDE_ALL => 1,
60
    ];
61
62
    public const INCLUDE_START_EXCLUDE_END = '[)';
63
64
    public const EXCLUDE_START_INCLUDE_END = '(]';
65
66
    public const EXCLUDE_ALL = '()';
67
68
    public const INCLUDE_ALL = '[]';
69
70
    /**
71
     * The starting datepoint.
72
     *
73
     * @var DateTimeImmutable
74
     */
75
    private $startDate;
76
77
    /**
78
     * The ending datepoint.
79
     *
80
     * @var DateTimeImmutable
81
     */
82
    private $endDate;
83
84
    /**
85
     * The boundary type.
86
     *
87
     * @var string
88
     */
89
    private $boundaryType;
90
91
    /**
92
     * Creates a new instance.
93
     *
94
     * @param mixed $startDate the starting datepoint
95
     * @param mixed $endDate   the ending datepoint
96
     *
97
     * @throws Exception If $startDate is greater than $endDate
98
     */
99 897
    public function __construct($startDate, $endDate, string $boundaryType = self::INCLUDE_START_EXCLUDE_END)
100
    {
101 897
        $startDate = self::getDatepoint($startDate);
102 897
        $endDate = self::getDatepoint($endDate);
103 885
        if ($startDate > $endDate) {
104 66
            throw new Exception('The ending datepoint must be greater or equal to the starting datepoint');
105
        }
106
107 861
        if (!isset(self::BOUNDARY_TYPE[$boundaryType])) {
108 6
            throw new Exception(sprintf(
109 6
                'The boundary type `%s` is invalid. The only valid values are %s',
110 6
                $boundaryType,
111 6
                '`'.implode('`, `', array_keys(self::BOUNDARY_TYPE)).'`'
112
            ));
113
        }
114
115 858
        $this->startDate = $startDate;
116 858
        $this->endDate = $endDate;
117 858
        $this->boundaryType = $boundaryType;
118 858
    }
119
120
    /**
121
     * Returns a DateTimeImmutable instance.
122
     *
123
     * @param mixed $datepoint a Datepoint
124
     */
125 1062
    private static function getDatepoint($datepoint): DateTimeImmutable
126
    {
127 1062
        if ($datepoint instanceof DateTimeImmutable) {
128 840
            return $datepoint;
129
        }
130
131 720
        return Datepoint::create($datepoint);
132
    }
133
134
    /**
135
     * Returns a DateInterval instance.
136
     *
137
     * @param mixed $duration a Duration
138
     */
139 357
    private static function getDuration($duration): DateInterval
140
    {
141 357
        if ($duration instanceof DateInterval) {
142 150
            return $duration;
143
        }
144
145 207
        return Duration::create($duration);
146
    }
147
148
    /**************************************************
149
     * Named constructors
150
     **************************************************/
151
152
    /**
153
     * @inheritDoc
154
     */
155 6
    public static function __set_state(array $interval)
156
    {
157 6
        return new self($interval['startDate'], $interval['endDate'], $interval['boundaryType'] ?? self::INCLUDE_START_EXCLUDE_END);
158
    }
159
160
    /**
161
     * Creates new instance from a starting datepoint and a duration.
162
     *
163
     * @param mixed $startDate the starting datepoint
164
     * @param mixed $duration  a Duration
165
     */
166 132
    public static function after($startDate, $duration, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
167
    {
168 132
        $startDate = self::getDatepoint($startDate);
169
170 132
        return new self($startDate, $startDate->add(self::getDuration($duration)), $boundaryType);
171
    }
172
173
    /**
174
     * Creates new instance from a ending datepoint and a duration.
175
     *
176
     * @param mixed $endDate  the ending datepoint
177
     * @param mixed $duration a Duration
178
     */
179 27
    public static function before($endDate, $duration, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
180
    {
181 27
        $endDate = self::getDatepoint($endDate);
182
183 27
        return new self($endDate->sub(self::getDuration($duration)), $endDate, $boundaryType);
184
    }
185
186
    /**
187
     * Creates new instance where the given duration is simultaneously
188
     * subtracted from and added to the datepoint.
189
     *
190
     * @param mixed $datepoint a Datepoint
191
     * @param mixed $duration  a Duration
192
     */
193 21
    public static function around($datepoint, $duration, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
194
    {
195 21
        $datepoint = self::getDatepoint($datepoint);
196 21
        $duration = self::getDuration($duration);
197
198 21
        return new self($datepoint->sub($duration), $datepoint->add($duration), $boundaryType);
199
    }
200
201
    /**
202
     * Creates new instance from a DatePeriod.
203
     */
204 12
    public static function fromDatePeriod(DatePeriod $datePeriod, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
205
    {
206 12
        return new self($datePeriod->getStartDate(), $datePeriod->getEndDate(), $boundaryType);
207
    }
208
209
    /**
210
     * Creates new instance for a specific year.
211
     */
212 12
    public static function fromYear(int $year, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
213
    {
214 12
        $startDate = (new DateTimeImmutable())->setDate($year, 1, 1)->setTime(0, 0);
215
216 12
        return new self($startDate, $startDate->add(new DateInterval('P1Y')), $boundaryType);
217
    }
218
219
    /**
220
     * Creates new instance for a specific ISO year.
221
     */
222 6
    public static function fromIsoYear(int $year, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
223
    {
224 6
        return new self(
225 6
            (new DateTimeImmutable())->setISODate($year, 1)->setTime(0, 0),
226 6
            (new DateTimeImmutable())->setISODate(++$year, 1)->setTime(0, 0),
227 2
            $boundaryType
228
        );
229
    }
230
231
    /**
232
     * Creates new instance for a specific year and semester.
233
     */
234 18
    public static function fromSemester(int $year, int $semester = 1, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
235
    {
236 18
        $month = (($semester - 1) * 6) + 1;
237 18
        $startDate = (new DateTimeImmutable())->setDate($year, $month, 1)->setTime(0, 0);
238
239 18
        return new self($startDate, $startDate->add(new DateInterval('P6M')), $boundaryType);
240
    }
241
242
    /**
243
     * Creates new instance for a specific year and quarter.
244
     */
245 18
    public static function fromQuarter(int $year, int $quarter = 1, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
246
    {
247 18
        $month = (($quarter - 1) * 3) + 1;
248 18
        $startDate = (new DateTimeImmutable())->setDate($year, $month, 1)->setTime(0, 0);
249
250 18
        return new self($startDate, $startDate->add(new DateInterval('P3M')), $boundaryType);
251
    }
252
253
    /**
254
     * Creates new instance for a specific year and month.
255
     */
256 75
    public static function fromMonth(int $year, int $month = 1, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
257
    {
258 75
        $startDate = (new DateTimeImmutable())->setDate($year, $month, 1)->setTime(0, 0);
259
260 75
        return new self($startDate, $startDate->add(new DateInterval('P1M')), $boundaryType);
261
    }
262
263
    /**
264
     * Creates new instance for a specific ISO8601 week.
265
     */
266 21
    public static function fromIsoWeek(int $year, int $week = 1, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
267
    {
268 21
        $startDate = (new DateTimeImmutable())->setISODate($year, $week, 1)->setTime(0, 0);
269
270 21
        return new self($startDate, $startDate->add(new DateInterval('P7D')), $boundaryType);
271
    }
272
273
    /**
274
     * Creates new instance for a specific year, month and day.
275
     */
276 51
    public static function fromDay(int $year, int $month = 1, int $day = 1, string $boundaryType = self::INCLUDE_START_EXCLUDE_END): self
277
    {
278 51
        $startDate = (new DateTimeImmutable())->setDate($year, $month, $day)->setTime(0, 0);
279
280 51
        return new self($startDate, $startDate->add(new DateInterval('P1D')), $boundaryType);
281
    }
282
283
    /**
284
     * Creates new instance from an ISO 8601 time interval.
285
     * This named constructor only support full datepoint and interval.
286
     *
287
     * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
288
     *
289
     * @throws \Exception
290
     * @throws Exception
291
     */
292 36
    public static function fromISO8601(
293
        string $isoFormat,
294
        string $separator = '/',
295
        string $boundaryType = self::INCLUDE_START_EXCLUDE_END
296
    ): self {
297 36
        if (false === strpos($isoFormat, $separator)) {
298 3
            throw new Exception(sprintf('The submitted separator `%s` is not present in interval string `%s`.', $separator, $isoFormat));
299
        }
300
301
        /** @var string[] $parts */
302 33
        $parts = explode($separator, $isoFormat);
303 33
        if (2 !== count($parts)) {
304 3
            throw new Exception(sprintf('The submitted interval string `%s` is not a valid ISO8601 interval format.', $isoFormat));
305
        }
306
307 30
        [$start, $end] = $parts;
308 30
        if ('P' === $start[0]) {
309 3
            return self::before(
310 3
                self::extractDateTimeString($end),
311 3
                new DateInterval($start),
312 3
                $boundaryType
313
            );
314
        }
315
316 27
        if ('P' === $end[0]) {
317 3
            return self::after(
318 3
                self::extractDateTimeString($start),
319 3
                new DateInterval($end),
320 3
                $boundaryType
321
            );
322
        }
323
324 24
        [$startDate, $endDate] = self::normalizeISO8601($parts);
325
326 18
        return new self($startDate, $endDate, $boundaryType);
327
    }
328
329 27
    private static function extractDateTimeString(string $isoFormat): string
330
    {
331 27
        if (1 !== preg_match(self::ISO8601_REGEXP, $isoFormat, $matches)) {
332 3
            throw new Exception(sprintf('The submitted interval string `%s` is not a valid ISO8601 interval date string.', $isoFormat));
333
        }
334
335 24
        foreach (['month', 'day'] as $part) {
336 24
            if (!isset($matches[$part]) || '' === $matches[$part]) {
337 6
                $matches[$part] = '01';
338
            }
339
        }
340
341 24
        if (!isset($matches['time']) || '' === $matches['time']) {
342 12
            $matches['time'] = '00:00:00';
343
        }
344 24
        $matches['utc'] = $matches['utc'] ?? '';
345
346 24
        return $matches['year'].'-'.$matches['month'].'-'.$matches['day'].' '.$matches['time'].$matches['utc'];
347
    }
348
349
    /**
350
     * @param string[] $iso8601String
351
     *
352
     * @throws Exception
353
     *
354
     * @return string[]
355
     */
356 24
    private static function normalizeISO8601(array $iso8601String): array
357
    {
358 24
        [$startDate, $endDate] = $iso8601String;
359 24
        $startLength = strlen($startDate);
360 24
        $endLength = strlen($endDate);
361 24
        $diff = $startLength <=> $endLength;
362 24
        if (-1 === $diff) {
363 3
            throw new Exception('The string format is not valid. Please review your submitted ISO8601 Interval format.');
364
        }
365
366 21
        if (1 === $diff) {
367 12
            $iso8601String = [$startDate, substr($startDate, 0, - $endLength).$endDate];
368
        }
369
370 21
        return array_map([self::class, 'extractDateTimeString'], $iso8601String);
371
    }
372
373
    /**************************************************
374
     * Basic getters
375
     **************************************************/
376
377
    /**
378
     * Returns the starting datepoint.
379
     */
380 243
    public function getStartDate(): DateTimeImmutable
381
    {
382 243
        return $this->startDate;
383
    }
384
385
    /**
386
     * Returns the ending datepoint.
387
     */
388 219
    public function getEndDate(): DateTimeImmutable
389
    {
390 219
        return $this->endDate;
391
    }
392
393
    /**
394
     * Returns the instance boundary type.
395
     */
396 159
    public function getBoundaryType(): string
397
    {
398 159
        return $this->boundaryType;
399
    }
400
401
    /**
402
     * Returns the instance duration as expressed in seconds.
403
     */
404 36
    public function getTimestampInterval(): float
405
    {
406 36
        return $this->endDate->getTimestamp() - $this->startDate->getTimestamp();
407
    }
408
409
    /**
410
     * Returns the instance duration as a DateInterval object.
411
     */
412 129
    public function getDateInterval(): DateInterval
413
    {
414 129
        return $this->startDate->diff($this->endDate);
415
    }
416
417
    /**************************************************
418
     * String representation
419
     **************************************************/
420
421
    /**
422
     * Returns the string representation as a ISO8601 interval format.
423
     *
424
     * @see Period::toISO8601()
425
     */
426 6
    public function __toString()
427
    {
428 6
        return $this->toISO8601();
429
    }
430
431
    /**
432
     * Returns the string representation as a ISO8601 interval format.
433
     *
434
     * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
435
     *
436
     */
437 6
    public function toISO8601(): string
438
    {
439 6
        $interval = $this->jsonSerialize();
440
441 6
        return $interval['startDate'].'/'.$interval['endDate'];
442
    }
443
444
    /**
445
     * Returns the JSON representation of an instance.
446
     *
447
     * Based on the JSON representation of dates as
448
     * returned by Javascript Date.toJSON() method.
449
     *
450
     * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
451
     * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
452
     *
453
     * @return array<string>
454
     */
455 15
    public function jsonSerialize()
456
    {
457 15
        $utc = new DateTimeZone('UTC');
458
459
        return [
460 15
            'startDate' => $this->startDate->setTimezone($utc)->format(self::ISO8601_FORMAT),
461 15
            'endDate' => $this->endDate->setTimezone($utc)->format(self::ISO8601_FORMAT),
462
        ];
463
    }
464
465
    /**
466
     * Returns the mathematical representation of an instance as a left close, right open interval.
467
     *
468
     * @see https://en.wikipedia.org/wiki/Interval_(mathematics)#Notations_for_intervals
469
     * @see https://php.net/manual/en/function.date.php
470
     * @see https://www.postgresql.org/docs/9.3/static/rangetypes.html
471
     *
472
     * @param string $format the format of the outputted date string
473
     */
474 24
    public function format(string $format): string
475
    {
476 24
        return $this->boundaryType[0]
477 24
            .$this->startDate->format($format)
478 24
            .', '
479 24
            .$this->endDate->format($format)
480 24
            .$this->boundaryType[1];
481
    }
482
483
    /**************************************************
484
     * Boundary related methods
485
     **************************************************/
486
487
    /**
488
     * Tells whether the start datepoint is included in the boundary.
489
     */
490 12
    public function isStartIncluded(): bool
491
    {
492 12
        return '[' === $this->boundaryType[0];
493
    }
494
495
    /**
496
     * Tells whether the start datepoint is excluded from the boundary.
497
     */
498 81
    public function isStartExcluded(): bool
499
    {
500 81
        return '(' === $this->boundaryType[0];
501
    }
502
503
    /**
504
     * Tells whether the end datepoint is included in the boundary.
505
     */
506 12
    public function isEndIncluded(): bool
507
    {
508 12
        return ']' === $this->boundaryType[1];
509
    }
510
511
    /**
512
     * Tells whether the end datepoint is excluded from the boundary.
513
     */
514 81
    public function isEndExcluded(): bool
515
    {
516 81
        return ')' === $this->boundaryType[1];
517
    }
518
519
    /**************************************************
520
     * Duration comparison methods
521
     **************************************************/
522
523
    /**
524
     * Compares two instances according to their duration.
525
     *
526
     * Returns:
527
     * <ul>
528
     * <li> -1 if the current Interval is lesser than the submitted Interval object</li>
529
     * <li>  1 if the current Interval is greater than the submitted Interval object</li>
530
     * <li>  0 if both Interval objects have the same duration</li>
531
     * </ul>
532
     */
533 60
    public function durationCompare(self $interval): int
534
    {
535 60
        return $this->startDate->add($this->getDateInterval())
536 60
            <=> $this->startDate->add($interval->getDateInterval());
537
    }
538
539
    /**
540
     * Tells whether the current instance duration is equal to the submitted one.
541
     */
542 6
    public function durationEquals(self $interval): bool
543
    {
544 6
        return 0 === $this->durationCompare($interval);
545
    }
546
547
    /**
548
     * Tells whether the current instance duration is greater than the submitted one.
549
     */
550 18
    public function durationGreaterThan(self $interval): bool
551
    {
552 18
        return 1 === $this->durationCompare($interval);
553
    }
554
555
    /**
556
     * Tells whether the current instance duration is less than the submitted one.
557
     */
558 12
    public function durationLessThan(self $interval): bool
559
    {
560 12
        return -1 === $this->durationCompare($interval);
561
    }
562
563
    /**************************************************
564
     * Relation methods
565
     **************************************************/
566
567
    /**
568
     * Tells whether an instance is entirely before the specified index.
569
     *
570
     * The index can be a DateTimeInterface object or another Period object.
571
     *
572
     * [--------------------)
573
     *                          [--------------------)
574
     *
575
     * @param mixed $index a datepoint or a Period object
576
     */
577 90
    public function isBefore($index): bool
578
    {
579 90
        if ($index instanceof self) {
580 48
            return $this->endDate < $index->startDate
581 48
                || ($this->endDate == $index->startDate && $this->boundaryType[1] !== $index->boundaryType[0]);
582
        }
583
584 42
        $datepoint = self::getDatepoint($index);
585 42
        return $this->endDate < $datepoint
586 42
            || ($this->endDate == $datepoint && ')' === $this->boundaryType[1]);
587
    }
588
589
    /**
590
     * Tells whether the current instance end date meets the interval start date.
591
     *
592
     * [--------------------)
593
     *                      [--------------------)
594
     */
595 309
    public function bordersOnStart(self $interval): bool
596
    {
597 309
        return $this->endDate == $interval->startDate
598 309
            && '][' !== $this->boundaryType[1].$interval->boundaryType[0];
599
    }
600
601
    /**
602
     * Tells whether two intervals share the same start datepoint
603
     * and the same starting boundary type.
604
     *
605
     *    [----------)
606
     *    [--------------------)
607
     *
608
     * or
609
     *
610
     *    [--------------------)
611
     *    [---------)
612
     *
613
     * @param mixed $index a datepoint or a Period object
614
     */
615 27
    public function isStartedBy($index): bool
616
    {
617 27
        if ($index instanceof self) {
618 15
            return $this->startDate == $index->startDate
619 15
                && $this->boundaryType[0] === $index->boundaryType[0];
620
        }
621
622 12
        $index = self::getDatepoint($index);
623
624 12
        return $index == $this->startDate && '[' === $this->boundaryType[0];
625
    }
626
627
    /**
628
     * Tells whether an instance is fully contained in the specified interval.
629
     *
630
     *     [----------)
631
     * [--------------------)
632
     */
633 39
    public function isDuring(self $interval): bool
634
    {
635 39
        return $interval->containsInterval($this);
636
    }
637
638
    /**
639
     * Tells whether an instance fully contains the specified index.
640
     *
641
     * The index can be a DateTimeInterface object or another Period object.
642
     *
643
     * @param mixed $index a datepoint or a Period object
644
     */
645 144
    public function contains($index): bool
646
    {
647 144
        if ($index instanceof self) {
648 66
            return $this->containsInterval($index);
649
        }
650
651 78
        return $this->containsDatepoint(self::getDatepoint($index), $this->boundaryType);
652
    }
653
654
    /**
655
     * Tells whether an instance fully contains another instance.
656
     *
657
     * [--------------------)
658
     *     [----------)
659
     */
660 66
    private function containsInterval(self $interval): bool
661
    {
662 66
        if ($this->startDate < $interval->startDate && $this->endDate > $interval->endDate) {
663 18
            return true;
664
        }
665
666 63
        if ($this->startDate == $interval->startDate && $this->endDate == $interval->endDate) {
667 21
            return $this->boundaryType === $interval->boundaryType || '[]' === $this->boundaryType;
668
        }
669
670 42
        if ($this->startDate == $interval->startDate) {
671 12
            return ($this->boundaryType[0] === $interval->boundaryType[0] || '[' === $this->boundaryType[0])
672 12
                && $this->containsDatepoint($this->startDate->add($interval->getDateInterval()), $this->boundaryType);
673
        }
674
675 30
        if ($this->endDate == $interval->endDate) {
676 18
            return ($this->boundaryType[1] === $interval->boundaryType[1] || ']' === $this->boundaryType[1])
677 18
                && $this->containsDatepoint($this->endDate->sub($interval->getDateInterval()), $this->boundaryType);
0 ignored issues
show
Bug introduced by
It seems like $this->endDate->sub($interval->getDateInterval()) can also be of type false; however, parameter $datepoint of League\Period\Period::containsDatepoint() does only seem to accept DateTimeInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

677
                && $this->containsDatepoint(/** @scrutinizer ignore-type */ $this->endDate->sub($interval->getDateInterval()), $this->boundaryType);
Loading history...
678
        }
679
680 12
        return false;
681
    }
682
683
    /**
684
     * Tells whether an instance contains a datepoint.
685
     *
686
     * [------|------------)
687
     */
688 108
    private function containsDatepoint(DateTimeInterface $datepoint, string $boundaryType): bool
689
    {
690
        switch ($boundaryType) {
691 108
            case self::EXCLUDE_ALL:
692 9
                return $datepoint > $this->startDate && $datepoint < $this->endDate;
693 99
            case self::INCLUDE_ALL:
694 3
                return $datepoint >= $this->startDate && $datepoint <= $this->endDate;
695 96
            case self::EXCLUDE_START_INCLUDE_END:
696 9
                return $datepoint > $this->startDate && $datepoint <= $this->endDate;
697 87
            case self::INCLUDE_START_EXCLUDE_END:
698
            default:
699 87
                return $datepoint >= $this->startDate && $datepoint < $this->endDate;
700
        }
701
    }
702
703
    /**
704
     * Tells whether two intervals share the same datepoints.
705
     *
706
     * [--------------------)
707
     * [--------------------)
708
     */
709 285
    public function equals(self $interval): bool
710
    {
711 285
        return $this->startDate == $interval->startDate
712 285
            && $this->endDate == $interval->endDate
713 285
            && $this->boundaryType === $interval->boundaryType;
714
    }
715
716
    /**
717
     * Tells whether two intervals share the same end datepoint
718
     * and the same ending boundary type.
719
     *
720
     *              [----------)
721
     *    [--------------------)
722
     *
723
     * or
724
     *
725
     *    [--------------------)
726
     *               [---------)
727
     *
728
     * @param mixed $index a datepoint or a Period object
729
     */
730 24
    public function isEndedBy($index): bool
731
    {
732 24
        if ($index instanceof self) {
733 12
            return $this->endDate == $index->endDate
734 12
                && $this->boundaryType[1] === $index->boundaryType[1];
735
        }
736
737 12
        $index = self::getDatepoint($index);
738
739 12
        return $index == $this->endDate && ']' === $this->boundaryType[1];
740
    }
741
742
    /**
743
     * Tells whether the current instance start date meets the interval end date.
744
     *
745
     *                      [--------------------)
746
     * [--------------------)
747
     */
748 291
    public function bordersOnEnd(self $interval): bool
749
    {
750 291
        return $interval->bordersOnStart($this);
751
    }
752
753
    /**
754
     * Tells whether an interval is entirely after the specified index.
755
     * The index can be a DateTimeInterface object or another Period object.
756
     *
757
     *                          [--------------------)
758
     * [--------------------)
759
     *
760
     * @param mixed $index a datepoint or a Period object
761
     */
762 54
    public function isAfter($index): bool
763
    {
764 54
        if ($index instanceof self) {
765 24
            return $index->isBefore($this);
766
        }
767
768 30
        $datepoint = self::getDatepoint($index);
769 30
        return $this->startDate > $datepoint
770 30
            || ($this->startDate == $datepoint && '(' === $this->boundaryType[0]);
771
    }
772
773
    /**
774
     * Tells whether two intervals abuts.
775
     *
776
     * [--------------------)
777
     *                      [--------------------)
778
     * or
779
     *                      [--------------------)
780
     * [--------------------)
781
     */
782 309
    public function abuts(self $interval): bool
783
    {
784 309
        return $this->bordersOnStart($interval) || $this->bordersOnEnd($interval);
785
    }
786
787
    /**
788
     * Tells whether two intervals overlaps.
789
     *
790
     * [--------------------)
791
     *          [--------------------)
792
     */
793 291
    public function overlaps(self $interval): bool
794
    {
795 291
        return !$this->abuts($interval)
796 291
            && $this->startDate < $interval->endDate
797 291
            && $this->endDate > $interval->startDate;
798
    }
799
800
    /**************************************************
801
     * Manipulating instance duration
802
     **************************************************/
803
804
    /**
805
     * Returns the difference between two instances expressed in seconds.
806
     */
807 6
    public function timestampIntervalDiff(self $interval): float
808
    {
809 6
        return $this->getTimestampInterval() - $interval->getTimestampInterval();
810
    }
811
812
    /**
813
     * Returns the difference between two instances expressed with a DateInterval object.
814
     */
815 12
    public function dateIntervalDiff(self $interval): DateInterval
816
    {
817 12
        return $this->endDate->diff($this->startDate->add($interval->getDateInterval()));
818
    }
819
820
    /**
821
     * Allows iteration over a set of dates and times,
822
     * recurring at regular intervals, over the instance.
823
     *
824
     * @see http://php.net/manual/en/dateperiod.construct.php
825
     *
826
     * @param mixed $duration a Duration
827
     */
828 54
    public function getDatePeriod($duration, int $option = 0): DatePeriod
829
    {
830 54
        return new DatePeriod($this->startDate, self::getDuration($duration), $this->endDate, $option);
831
    }
832
833
    /**
834
     * Allows iteration over a set of dates and times,
835
     * recurring at regular intervals, over the instance backwards starting from
836
     * the instance ending datepoint.
837
     *
838
     * @param mixed $duration a Duration
839
     */
840 24
    public function getDatePeriodBackwards($duration, int $option = 0): iterable
841
    {
842 24
        $duration = self::getDuration($duration);
843 24
        $date = $this->endDate;
844 24
        if ((bool) ($option & DatePeriod::EXCLUDE_START_DATE)) {
845 12
            $date = $this->endDate->sub($duration);
846
        }
847
848 24
        while ($date > $this->startDate) {
849 24
            yield $date;
850 24
            $date = $date->sub($duration);
851
        }
852 24
    }
853
854
    /**
855
     * Allows splitting an instance in smaller Period objects according to a given interval.
856
     *
857
     * The returned iterable Interval set is ordered so that:
858
     * <ul>
859
     * <li>The first returned object MUST share the starting datepoint of the parent object.</li>
860
     * <li>The last returned object MUST share the ending datepoint of the parent object.</li>
861
     * <li>The last returned object MUST have a duration equal or lesser than the submitted interval.</li>
862
     * <li>All returned objects except for the first one MUST start immediately after the previously returned object</li>
863
     * </ul>
864
     *
865
     * @param mixed $duration a Duration
866
     *
867
     * @return iterable<Period>
868
     */
869 30
    public function split($duration): iterable
870
    {
871 30
        $duration = self::getDuration($duration);
872 30
        foreach ($this->getDatePeriod($duration) as $startDate) {
873 30
            $endDate = $startDate->add($duration);
874 30
            if ($endDate > $this->endDate) {
875 12
                $endDate = $this->endDate;
876
            }
877
878 30
            yield new self($startDate, $endDate, $this->boundaryType);
879
        }
880 30
    }
881
882
    /**
883
     * Allows splitting an instance in smaller Period objects according to a given interval.
884
     *
885
     * The returned iterable Period set is ordered so that:
886
     * <ul>
887
     * <li>The first returned object MUST share the ending datepoint of the parent object.</li>
888
     * <li>The last returned object MUST share the starting datepoint of the parent object.</li>
889
     * <li>The last returned object MUST have a duration equal or lesser than the submitted interval.</li>
890
     * <li>All returned objects except for the first one MUST end immediately before the previously returned object</li>
891
     * </ul>
892
     *
893
     * @param mixed $duration a Duration
894
     *
895
     * @return iterable<Period>
896
     */
897 18
    public function splitBackwards($duration): iterable
898
    {
899 18
        $endDate = $this->endDate;
900 18
        $duration = self::getDuration($duration);
901
        do {
902 18
            $startDate = $endDate->sub($duration);
903 18
            if ($startDate < $this->startDate) {
904 6
                $startDate = $this->startDate;
905
            }
906 18
            yield new self($startDate, $endDate, $this->boundaryType);
907
908 18
            $endDate = $startDate;
909 18
        } while ($endDate > $this->startDate);
910 18
    }
911
912
    /**************************************************
913
     * Manipulation instance endpoints and boundaries
914
     **************************************************/
915
916
    /**
917
     * Returns the computed intersection between two instances as a new instance.
918
     *
919
     * [--------------------)
920
     *          ∩
921
     *                 [----------)
922
     *          =
923
     *                 [----)
924
     *
925
     * @throws Exception If both objects do not overlaps
926
     */
927 153
    public function intersect(self $interval): self
928
    {
929 153
        if (!$this->overlaps($interval)) {
930 12
            throw new Exception('Both '.self::class.' objects should overlaps');
931
        }
932
933 141
        $startDate = $this->startDate;
934 141
        $endDate = $this->endDate;
935 141
        $boundaryType = $this->boundaryType;
936 141
        if ($interval->startDate > $this->startDate) {
937 132
            $boundaryType[0] = $interval->boundaryType[0];
938 132
            $startDate = $interval->startDate;
939
        }
940
941 141
        if ($interval->endDate < $this->endDate) {
942 33
            $boundaryType[1] = $interval->boundaryType[1];
943 33
            $endDate = $interval->endDate;
944
        }
945
946 141
        $intersect = new self($startDate, $endDate, $boundaryType);
947 141
        if ($intersect->equals($this)) {
948 21
            return $this;
949
        }
950
951 138
        return $intersect;
952
    }
953
954
    /**
955
     * Returns the computed difference between two overlapping instances as
956
     * an array containing Period objects or the null value.
957
     *
958
     * The array will always contains 2 elements:
959
     *
960
     * <ul>
961
     * <li>an NULL filled array if both objects have the same datepoints</li>
962
     * <li>one Period object and NULL if both objects share one datepoint</li>
963
     * <li>two Period objects if both objects share no datepoint</li>
964
     * </ul>
965
     *
966
     * [--------------------)
967
     *          \
968
     *                [-----------)
969
     *          =
970
     * [--------------)  +  [-----)
971
     *
972
     * @return array<null|Period>
973
     */
974 99
    public function diff(self $interval): array
975
    {
976 99
        if ($interval->equals($this)) {
977 12
            return [null, null];
978
        }
979
980 87
        $intersect = $this->intersect($interval);
981 81
        $merge = $this->merge($interval);
982 81
        if ($merge->startDate == $intersect->startDate) {
983 9
            $first = ')' === $intersect->boundaryType[1] ? '[' : '(';
984 9
            $boundary = $first.$merge->boundaryType[1];
985
986 9
            return [$merge->startingOn($intersect->endDate)->withBoundaryType($boundary), null];
987
        }
988
989 75
        if ($merge->endDate == $intersect->endDate) {
990 6
            $last = '(' === $intersect->boundaryType[0] ? ']' : ')';
991 6
            $boundary = $merge->boundaryType[0].$last;
992
993 6
            return [$merge->endingOn($intersect->startDate)->withBoundaryType($boundary), null];
994
        }
995
996 69
        $last = '(' === $intersect->boundaryType[0] ? ']' : ')';
997 69
        $lastBoundary = $merge->boundaryType[0].$last;
998
999 69
        $first = ')' === $intersect->boundaryType[1] ? '[' : '(';
1000 69
        $firstBoundary = $first.$merge->boundaryType[1];
1001
1002
        return [
1003 69
            $merge->endingOn($intersect->startDate)->withBoundaryType($lastBoundary),
1004 69
            $merge->startingOn($intersect->endDate)->withBoundaryType($firstBoundary),
1005
        ];
1006
    }
1007
1008
    /**
1009
     * DEPRECATION WARNING! This method will be removed in the next major point release.
1010
     *
1011
     * @deprecated since version 4.9.0
1012
     * @see ::subtract
1013
     */
1014 3
    public function substract(self $interval): Sequence
1015
    {
1016 3
        return $this->subtract($interval);
1017
    }
1018
1019
    /**
1020
     * Returns the difference set operation between two intervals as a Sequence.
1021
     * The Sequence can contain from 0 to 2 Periods depending on the result of
1022
     * the operation.
1023
     *
1024
     * [--------------------)
1025
     *          -
1026
     *                [-----------)
1027
     *          =
1028
     * [--------------)
1029
     */
1030 24
    public function subtract(self $interval): Sequence
1031
    {
1032 24
        if (!$this->overlaps($interval)) {
1033 9
            return new Sequence($this);
1034
        }
1035
1036
        $filter = function ($item): bool {
1037 18
            return null !== $item && $this->overlaps($item);
1038 18
        };
1039
1040 18
        return new Sequence(...array_filter($this->diff($interval), $filter));
1041
    }
1042
1043
    /**
1044
     * Returns the computed gap between two instances as a new instance.
1045
     *
1046
     * [--------------------)
1047
     *          +
1048
     *                          [----------)
1049
     *          =
1050
     *                      [---)
1051
     *
1052
     * @throws Exception If both instance overlaps
1053
     */
1054 84
    public function gap(self $interval): self
1055
    {
1056 84
        if ($this->overlaps($interval)) {
1057 18
            throw new Exception('Both '.self::class.' objects must not overlaps');
1058
        }
1059
1060 66
        $boundaryType = $this->isEndExcluded() ? '[' : '(';
1061 66
        $boundaryType .= $interval->isStartExcluded() ? ']' : ')';
1062 66
        if ($interval->startDate > $this->startDate) {
1063 66
            return new self($this->endDate, $interval->startDate, $boundaryType);
1064
        }
1065
1066 6
        return new self($interval->endDate, $this->startDate, $this->boundaryType);
1067
    }
1068
1069
    /**
1070
     * Merges one or more instances to return a new instance.
1071
     * The resulting instance represents the largest duration possible.
1072
     *
1073
     * This method MUST retain the state of the current instance, and return
1074
     * an instance that contains the specified new datepoints.
1075
     *
1076
     * [--------------------)
1077
     *          +
1078
     *                 [----------)
1079
     *          =
1080
     * [--------------------------)
1081
     *
1082
     *
1083
     * @param Period ...$intervals
1084
     */
1085 105
    public function merge(self ...$intervals): self
1086
    {
1087 105
        $carry = $this;
1088 105
        foreach ($intervals as $period) {
1089 99
            if ($carry->startDate > $period->startDate) {
1090 33
                $carry = new self(
1091 33
                    $period->startDate,
1092 33
                    $carry->endDate,
1093 33
                    $period->boundaryType[0].$carry->boundaryType[1]
1094
                );
1095
            }
1096
1097 99
            if ($carry->endDate < $period->endDate) {
1098 87
                $carry = new self(
1099 87
                    $carry->startDate,
1100 87
                    $period->endDate,
1101 87
                    $carry->boundaryType[0].$period->boundaryType[1]
1102
                );
1103
            }
1104
        }
1105
1106 105
        return $carry;
1107
    }
1108
1109
1110
    /**************************************************
1111
     * Mutation methods
1112
     **************************************************/
1113
1114
    /**
1115
     * Returns an instance with the specified starting datepoint.
1116
     *
1117
     * This method MUST retain the state of the current instance, and return
1118
     * an instance that contains the specified starting datepoint.
1119
     *
1120
     * @param mixed $startDate the new starting datepoint
1121
     */
1122 120
    public function startingOn($startDate): self
1123
    {
1124 120
        $startDate = self::getDatepoint($startDate);
1125 120
        if ($startDate == $this->startDate) {
1126 6
            return $this;
1127
        }
1128
1129 120
        return new self($startDate, $this->endDate, $this->boundaryType);
1130
    }
1131
1132
    /**
1133
     * Returns an instance with the specified ending datepoint.
1134
     *
1135
     * This method MUST retain the state of the current instance, and return
1136
     * an instance that contains the specified ending datepoint.
1137
     *
1138
     * @param mixed $endDate the new ending datepoint
1139
     */
1140 120
    public function endingOn($endDate): self
1141
    {
1142 120
        $endDate = self::getDatepoint($endDate);
1143 120
        if ($endDate == $this->endDate) {
1144 6
            return $this;
1145
        }
1146
1147 120
        return new self($this->startDate, $endDate, $this->boundaryType);
1148
    }
1149
1150
    /**
1151
     * Returns an instance with the specified boundary type.
1152
     *
1153
     * This method MUST retain the state of the current instance, and return
1154
     * an instance with the specified range type.
1155
     */
1156 87
    public function withBoundaryType(string $boundaryType): self
1157
    {
1158 87
        if ($boundaryType === $this->boundaryType) {
1159 72
            return $this;
1160
        }
1161
1162 45
        return new self($this->startDate, $this->endDate, $boundaryType);
1163
    }
1164
1165
    /**
1166
     * Returns a new instance with a new ending datepoint.
1167
     *
1168
     * This method MUST retain the state of the current instance, and return
1169
     * an instance that contains the specified ending datepoint.
1170
     *
1171
     * @param mixed $duration a Duration
1172
     */
1173 12
    public function withDurationAfterStart($duration): self
1174
    {
1175 12
        return $this->endingOn($this->startDate->add(self::getDuration($duration)));
1176
    }
1177
1178
    /**
1179
     * Returns a new instance with a new starting datepoint.
1180
     *
1181
     * This method MUST retain the state of the current instance, and return
1182
     * an instance that contains the specified starting datepoint.
1183
     *
1184
     * @param mixed $duration a Duration
1185
     */
1186 12
    public function withDurationBeforeEnd($duration): self
1187
    {
1188 12
        return $this->startingOn($this->endDate->sub(self::getDuration($duration)));
1189
    }
1190
1191
    /**
1192
     * Returns a new instance with a new starting datepoint
1193
     * moved forward or backward by the given interval.
1194
     *
1195
     * This method MUST retain the state of the current instance, and return
1196
     * an instance that contains the specified starting datepoint.
1197
     *
1198
     * @param mixed $duration a Duration
1199
     */
1200 18
    public function moveStartDate($duration): self
1201
    {
1202 18
        return $this->startingOn($this->startDate->add(self::getDuration($duration)));
1203
    }
1204
1205
    /**
1206
     * Returns a new instance with a new ending datepoint
1207
     * moved forward or backward by the given interval.
1208
     *
1209
     * This method MUST retain the state of the current instance, and return
1210
     * an instance that contains the specified ending datepoint.
1211
     *
1212
     * @param mixed $duration a Duration
1213
     */
1214 15
    public function moveEndDate($duration): self
1215
    {
1216 15
        return $this->endingOn($this->endDate->add(self::getDuration($duration)));
1217
    }
1218
1219
    /**
1220
     * Returns a new instance where the datepoints
1221
     * are moved forwards or backward simultaneously by the given DateInterval.
1222
     *
1223
     * This method MUST retain the state of the current instance, and return
1224
     * an instance that contains the specified new datepoints.
1225
     *
1226
     * @param mixed $duration a Duration
1227
     */
1228 24
    public function move($duration): self
1229
    {
1230 24
        $duration = self::getDuration($duration);
1231 24
        $interval = new self($this->startDate->add($duration), $this->endDate->add($duration), $this->boundaryType);
1232 24
        if ($this->equals($interval)) {
1233 6
            return $this;
1234
        }
1235
1236 24
        return $interval;
1237
    }
1238
1239
    /**
1240
     * Returns an instance where the given DateInterval is simultaneously
1241
     * subtracted from the starting datepoint and added to the ending datepoint.
1242
     *
1243
     * Depending on the duration value, the resulting instance duration will be expanded or shrinked.
1244
     *
1245
     * This method MUST retain the state of the current instance, and return
1246
     * an instance that contains the specified new datepoints.
1247
     *
1248
     * @param mixed $duration a Duration
1249
     */
1250 24
    public function expand($duration): self
1251
    {
1252 24
        $duration = self::getDuration($duration);
1253 24
        $interval = new self($this->startDate->sub($duration), $this->endDate->add($duration), $this->boundaryType);
1254 18
        if ($this->equals($interval)) {
1255 6
            return $this;
1256
        }
1257
1258 12
        return $interval;
1259
    }
1260
}
1261