spatie / period

Complex period comparisons
https://spatie.be/open-source
MIT License
1.56k stars 72 forks source link

Get all overlapsed dates from collection #63

Closed ShapesGraphicStudio closed 4 years ago

ShapesGraphicStudio commented 4 years ago

Hello, I need to get a range of overlapping dates from a collection.

Maybe I missed something in the docs but I can not find something like:

$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();

But getting: $overlaps = $collection->overlaps(); instead of gaps

Would that be possible ?

Best regards

ShapesGraphicStudio commented 4 years ago

Hi again,

I do not know if it's the best way to get there, but in case it can help somebody spare some time, here's what I did:

$periods = [];

foreach($items as $item) {
    if($item->model->time_limited) {
        $periods[$item->id] = Period::make($item->available_from,$item->available_to);
    }
}

$collection = new PeriodCollection(...$periods);
$boundaries = $collection->boundaries();

$overlaps = $boundaries->overlapAll(...$periods);

Seems to work fine. Best regards

EDIT Bummer, it worked fine till I got multiple overlaps, I then got: Call to a member function overlapSingle() on null In my case actually it's not a big issue as I do not want to proceed with more than one overlaps range, but it would be great to get overlaps as easily as we can get gaps.

brendt commented 4 years ago

My thought would be as you did, getting the boundaries of the collection and overlapping each individual period to that. Feel free to submit a PR to add eg. overlapAny to the PeriodCollection class.