ckuran/period

Complex period comparisons

1.4.4 2019-08-05 07:34 UTC

README

Latest Version on Packagist Build Status Quality Score StyleCI Total Downloads

This package adds support for comparing multiple dates with each other. You can calculate the overlaps and differences between n-amount of periods, as well as some more basic comparisons between two periods.

Periods can be constructed from any type of DateTime implementation, making this package compatible with custom DateTime implementations like Carbon (see cmixin/enhanced-period to convert directly from and to CarbonPeriod).

Periods are always immutable, there's never the worry about your input dates being changed.

This package is still a work in progress.

Installation

You can install the package via composer:

composer require spatie/period

Usage

Quick reference

Creating a period

$period = new Period(
     DateTimeImmutable $start
   , DateTimeImmutable $end
  [, ?int $precisionMask = Precision::DAY]
  [, ?int $boundaryExclusionMask = Boundaries::EXCLUDE_NONE]
)

The static ::make constructor can also take strings and other implementations of DateTimeInterface, as well as an extra format string, in case the textual dates passed aren't of the format Y-m-d or Y-m-d H:i:s.

$period = Period::make(
     string|DateTimeInterface $start
   , string|DateTimeInterface $end
  [, ?int Precision::DAY]
  [, ?int Boundaries::EXCLUDE_NONE]
  [, string $format]
)

Length and boundaries

$period->length(): int
$period->startIncluded(): bool
$period->startExcluded(): bool
$period->endIncluded(): bool
$period->endExcluded(): bool
$period->getStart(): DateTimeImmutable
$period->getStartIncluded(): DateTimeImmutable
$period->getEnd(): DateTimeImmutable
$period->getEndIncluded(): DateTimeImmutable

Comparisons

$period->contains(DateTimeInterface $date): bool
$period->equals(Period $period): bool

$period->overlapsWith(Period $period): bool
$period->touchesWith(Period $period): bool
$period->startsAt(DateTimeInterface $date): bool
$period->startsBefore(DateTimeInterface $date): bool
$period->startsBeforeOrAt(DateTimeInterface $date): bool
$period->startsAfter(DateTimeInterface $date): bool
$period->startsAfterOrAt(DateTimeInterface $date): bool
$period->endsAt(DateTimeInterface $date): bool
$period->endsBefore(DateTimeInterface $date): bool
$period->endsBeforeOrAt(DateTimeInterface $date): bool
$period->endsAfter(DateTimeInterface $date): bool
$period->endsAfterOrAt(DateTimeInterface $date): bool
$period->gap(Period $period): ?Period
$period->overlapSingle(Period $period): ?Period
$period->overlap(Period ...$periods): PeriodCollection
$period->overlapAll(Period ...$periods): Period
$period->diffSingle(Period $period): PeriodCollection
$period->diff(Period ...$periods): PeriodCollection
$periodCollection->overlap(PeriodCollection ...$periodCollections): PeriodCollection
$periodCollection->overlapSingle(PeriodCollection $periodCollection): PeriodCollection
$periodCollection->map(Closure<Period> $closure): PeriodCollection
$periodCollection->reduce(Closure<mixed, Period> $closure): mixed
$periodCollection->boundaries(): ?Period
$periodCollection->gaps(): PeriodCollection

Comparing periods

Overlaps with any other period: this method returns a PeriodCollection multiple Period objects representing the overlaps.

/*
 * A       [========]
 * B                    [==]
 * C                            [=====]
 * CURRENT        [===============]
 *
 * OVERLAP        [=]   [==]    [=]
 */
 
$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-10', '2018-02-20');
$c = Period::make('2018-03-01', '2018-03-31');

$current = Period::make('2018-01-20', '2018-03-10');

$overlaps = $current->overlap($a, $b, $c); 

Overlap with all periods: this method only returns one period where all periods overlap.

/*
 * A              [============]
 * B                   [==]
 * C                  [=======]
 *
 * OVERLAP             [==]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-01-10', '2018-01-15');
$c = Period::make('2018-01-10', '2018-01-31');

$overlap = $a->overlapAll($b, $c);

Diff between multiple periods: this method returns a PeriodCollection multiple Period objects representing the diffs between several periods and one.

/*
 * A                   [====]
 * B                               [========]
 * C         [=====]
 * CURRENT      [========================]
 *
 * DIFF             [=]      [====]
 */

$a = Period::make('2018-01-05', '2018-01-10');
$b = Period::make('2018-01-15', '2018-03-01');
$c = Period::make('2017-01-01', '2018-01-02');

$current = Period::make('2018-01-01', '2018-01-31');

$diff = $current->diff($a, $b, $c);

Overlaps with: this method returns a boolean indicating of two periods overlap or not.

/*
 * A              [============]
 * B                   [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-01-10', '2018-02-15');

$overlap = $a->overlapsWith($b); // true

Touches with: this method determines if two periods touch each other.

/*
 * A              [========]
 * B                        [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-01', '2018-02-15');

$overlap = $a->touchesWith($b); // true

Gap: returns the gap between two periods. If no gap exists, null is returned.

/*
 * A              [========]
 * B                           [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-05', '2018-02-15');

$overlap = $a->gap($b); // Period('2018-02-01', '2018-02-04')

Boundaries of a collection: get one period representing the boundaries of a collection.

/*
 * A                   [====]
 * B                               [========]
 * C           [=====]
 * D                                             [====]
 *
 * BOUNDARIES  [======================================]
 */
 
$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-05'),
    Period::make('2018-01-10', '2018-01-15'),
    Period::make('2018-01-20', '2018-01-25'),
    Period::make('2018-01-30', '2018-01-31')
);

$boundaries = $collection->boundaries();

Gaps of a collection: get all the gaps of a collection.

/*
 * A                   [====]
 * B                               [========]
 * C         [=====]
 * D                                             [====]
 *
 * GAPS             [=]      [====]          [==]
 */

$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-05'),
    Period::make('2018-01-10', '2018-01-15'),
    Period::make('2018-01-20', '2018-01-25'),
    Period::make('2018-01-30', '2018-01-31')
);

$gaps = $collection->gaps();

Overlap multiple collections: returns the overlap between collections. This means an AND operation between collections, and an OR operation within the same collection.

/*
 * A            [=====]      [===========]
 * B            [=================]
 * C                [====================]
 *
 * OVERLAP          [=]      [====]
 */

$a = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-07'),
    Period::make('2018-01-15', '2018-01-25')
);

$b = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-20')
);

$c = new PeriodCollection(
    Period::make('2018-01-06', '2018-01-25')
);

$overlap = $a->overlap($b, $c);

Working with PeriodCollection

Period collections are constructed from several periods:

$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-02'),
    // …
);

They may be looped over directly and its contents will be recognised by your IDE:

$collection = new PeriodCollection(/* … */);

foreach ($collection as $period) {
    $period->…
}

You may destruct them:

[$firstPeriod, $secondPeriod, $thirdPeriod] = $collection;

And finally construct one collection from another:

$newCollection = new PeriodCollection(...$otherCollection);

Precision

Date precision is of utmost importance if you want to reliably compare two periods. The the following example:

Given two periods: [2018-01-01, 2018-01-15] and [2018-01-15, 2018-01-31]; do they overlap?

At first glance the answer is "yes": they overlap on 2018-01-15. But what if the first period ends at 2018-01-15 10:00:00, while the second starts at 2018-01-15 15:00:00? Now they don't anymore!

This is why this package requires you to specify a precision with each period. Only periods with the same precision can be compared.

A more in-depth explanation on why precision is so important can be found here. A period's precision can be specified when constructing that period:

Period::make('2018-01-01', '2018-02-01', Precision::DAY);

The default precision is set on days. These are the available precision options:

Precision::YEAR
Precision::MONTH
Precision::DAY
Precision::HOUR
Precision::MINUTE
Precision::SECOND

Boundaries

By default, period comparisons are done with included boundaries. This means that these two periods overlap:

$a = Period::make('2018-01-01', '2018-02-01');
$b = Period::make('2018-02-01', '2018-02-28');

$a->overlapsWith($b); // true

The length of a period will also include both boundaries:

$a = Period::make('2018-01-01', '2018-01-31');

$a->length(); // 31

It's possible to override the boundary behaviour:

$a = Period::make('2018-01-01', '2018-02-01', null, Boundaries::EXCLUDE_END);
$b = Period::make('2018-02-01', '2018-02-28', null, Boundaries::EXCLUDE_END);

$a->overlapsWith($b); // false

There are four types of boundary exclusion:

Boundaries::EXCLUDE_NONE;
Boundaries::EXCLUDE_START;
Boundaries::EXCLUDE_END;
Boundaries::EXCLUDE_ALL;

Compatibility

You can construct a Period from any type of DateTime object such as Carbon:

Period::make(Carbon::make('2018-01-01'), Carbon::make('2018-01-02'));

Note that as soon as a period is constructed, all further operations on it are immutable. There's never the danger of changing the input dates.

You can iterate a Period like a regular DatePeriod with the precision specified on creation:

$datePeriod = Period::make(Carbon::make('2018-01-01'), Carbon::make('2018-01-31'));

foreach ($datePeriod as $date) {
    /** @var DateTimeImmutable $date */
    // 2018-01-01
    // 2018-01-02
    // ...
    // (31 iterations)
}

$timePeriod = Period::make(Carbon::make('2018-01-01 00:00:00'), Carbon::make('2018-01-01 23:59:59'), Precision::HOUR);

foreach ($timePeriod as $time) {
    /** @var DateTimeImmutable $time */
    // 2018-01-01 00:00:00
    // 2018-01-01 01:00:00
    // ...
    // (24 iterations)
}

Visualizing periods

You can visualize one or more Period objects as well as PeriodCollection objects to see how they related to one another:

$visualizer = new Visualizer(["width" => 27]);

$visualizer->visualize([
    "A" => Period::make('2018-01-01', '2018-01-31'),
    "B" => Period::make('2018-02-10', '2018-02-20'),
    "C" => Period::make('2018-03-01', '2018-03-31'),
    "D" => Period::make('2018-01-20', '2018-03-10'),
    "OVERLAP" => new PeriodCollection(
        Period::make('2018-01-20', '2018-01-31'),
        Period::make('2018-02-10', '2018-02-20'),
        Period::make('2018-03-01', '2018-03-10')
    ),
]);

And visualize will return the following string:

A          [========]
B                      [==]
C                           [========]
D               [==============]
OVERLAP         [===]  [==] [==]

The visualizer has a configurable width provided upon creation which will control the bounds of the displayed periods:

$visualizer = new Visualizer(["width" => 10]);

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

Support us

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License

The MIT License (MIT). Please see License File for more information.