Completed
Push — master ( a2f7a7...4d2430 )
by ignace nyamagana
22s queued 10s
created

Sequence::calculateUnion()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 2
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 4
rs 9.9332
c 0
b 0
f 0
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 ArrayAccess;
17
use Countable;
18
use Iterator;
19
use IteratorAggregate;
20
use JsonSerializable;
21
use function array_filter;
22
use function array_merge;
23
use function array_splice;
24
use function array_unshift;
25
use function array_values;
26
use function count;
27
use function reset;
28
use function sort;
29
use function sprintf;
30
use function uasort;
31
use function usort;
32
use const ARRAY_FILTER_USE_BOTH;
33
34
/**
35
 * A class to manipulate interval collection.
36
 *
37
 * @package League.period
38
 * @author  Ignace Nyamagana Butera <[email protected]>
39
 * @since   4.1.0
40
 */
41
final class Sequence implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
42
{
43
    /**
44
     * @var Period[]
45
     */
46
    private $intervals = [];
47
48
    /**
49
     * new instance.
50
     *
51
     * @param Period ...$intervals
52
     */
53 87
    public function __construct(Period ...$intervals)
54
    {
55 87
        $this->intervals = $intervals;
56 87
    }
57
58
    /**
59
     * Returns the sequence boundaries as a Period instance.
60
     *
61
     * If the sequence contains no interval null is returned.
62
     *
63
     * @return ?Period
64
     */
65 12
    public function boundaries(): ?Period
66
    {
67 12
        $period = reset($this->intervals);
68 12
        if (false === $period) {
69 6
            return null;
70
        }
71
72 12
        return $period->merge(...$this->intervals);
73
    }
74
75
    /**
76
     * Returns the gaps inside the instance.
77
     */
78 9
    public function gaps(): self
79
    {
80 9
        $sequence = new self();
81 9
        $interval = null;
82 9
        foreach ($this->sorted([$this, 'sortByStartDate']) as $period) {
83 9
            if (null === $interval) {
84 9
                $interval = $period;
85 9
                continue;
86
            }
87
88 9
            if (!$interval->overlaps($period) && !$interval->abuts($period)) {
89 6
                $sequence->push($interval->gap($period));
90
            }
91
92 9
            if (!$interval->contains($period)) {
93 8
                $interval = $period;
94
            }
95
        }
96
97 9
        return $sequence;
98
    }
99
100
    /**
101
     * Sorts two Interval instance using their start datepoint.
102
     */
103 15
    private function sortByStartDate(Period $interval1, Period $interval2): int
104
    {
105 15
        return $interval1->getStartDate() <=> $interval2->getStartDate();
106
    }
107
108
    /**
109
     * Returns the intersections inside the instance.
110
     */
111 9
    public function intersections(): self
112
    {
113 9
        $sequence = new self();
114 9
        $current = null;
115 9
        $isPreviouslyContained = false;
116 9
        foreach ($this->sorted([$this, 'sortByStartDate']) as $period) {
117 9
            if (null === $current) {
118 9
                $current = $period;
119 9
                continue;
120
            }
121
122 9
            $isContained = $current->contains($period);
123 9
            if ($isContained && $isPreviouslyContained) {
124 3
                continue;
125
            }
126
127 9
            if ($current->overlaps($period)) {
128 6
                $sequence->push($current->intersect($period));
129
            }
130
131 9
            $isPreviouslyContained = $isContained;
132 9
            if (!$isContained) {
133 8
                $current = $period;
134
            }
135
        }
136
137 9
        return $sequence;
138
    }
139
140
    /**
141
     * Returns the unions inside the instance.
142
     */
143 6
    public function unions(): self
144
    {
145
        $sequence = $this
146 6
            ->sorted([$this, 'sortByStartDate'])
147 6
            ->reduce([$this, 'calculateUnion'], new self())
148
        ;
149
150 6
        if ($sequence->intervals === $this->intervals) {
151 3
            return $this;
152
        }
153
154 3
        return $sequence;
155
    }
156
157
    /**
158
     * Iteratively calculate the union sequence.
159
     */
160 6
    private function calculateUnion(Sequence $sequence, Period $period): Sequence
161
    {
162 6
        if ($sequence->isEmpty()) {
163 6
            $sequence->push($period);
164
165 6
            return $sequence;
166
        }
167
168 3
        $index = $sequence->count() - 1;
169 3
        $interval = $sequence->get($index);
170 3
        if ($interval->overlaps($period) || $interval->abuts($period)) {
171 3
            $sequence->set($index, $interval->merge($period));
172
173 3
            return $sequence;
174
        }
175
176 3
        $sequence->push($period);
177
178 3
        return $sequence;
179
    }
180
181
    /**
182
     * Returns the sequence boundaries as a Period instance.
183
     *
184
     * DEPRECATION WARNING! This method will be removed in the next major point release
185
     *
186
     * @deprecated deprecated since version 4.4.0
187
     * @see        ::boundaries
188
     *
189
     * If the sequence contains no interval null is returned.
190
     *
191
     * @return ?Period
192
     */
193 12
    public function getBoundaries(): ?Period
194
    {
195 12
        return $this->boundaries();
196
    }
197
198
    /**
199
     * Returns the intersections inside the instance.
200
     *
201
     * DEPRECATION WARNING! This method will be removed in the next major point release
202
     *
203
     * @deprecated deprecated since version 4.4.0
204
     * @see        ::intersections
205
     */
206 9
    public function getIntersections(): self
207
    {
208 9
        return $this->intersections();
209
    }
210
211
    /**
212
     * Returns the gaps inside the instance.
213
     *
214
     * DEPRECATION WARNING! This method will be removed in the next major point release
215
     *
216
     * @deprecated deprecated since version 4.4.0
217
     * @see        ::gaps
218
     */
219 9
    public function getGaps(): self
220
    {
221 9
        return $this->gaps();
222
    }
223
224
    /**
225
     * Tells whether some intervals in the current instance satisfies the predicate.
226
     */
227 3
    public function some(callable $predicate): bool
228
    {
229 3
        foreach ($this->intervals as $offset => $interval) {
230 3
            if (true === $predicate($interval, $offset)) {
231 3
                return true;
232
            }
233
        }
234
235 3
        return false;
236
    }
237
238
    /**
239
     * Tells whether all intervals in the current instance satisfies the predicate.
240
     */
241 3
    public function every(callable $predicate): bool
242
    {
243 3
        foreach ($this->intervals as $offset => $interval) {
244 3
            if (true !== $predicate($interval, $offset)) {
245 2
                return false;
246
            }
247
        }
248
249 3
        return [] !== $this->intervals;
250
    }
251
252
    /**
253
     * Returns the array representation of the sequence.
254
     *
255
     * @return Period[]
256
     */
257 6
    public function toArray(): array
258
    {
259 6
        return $this->intervals;
260
    }
261
262
    /**
263
     * {@inheritdoc}
264
     */
265 3
    public function jsonSerialize(): array
266
    {
267 3
        return $this->intervals;
268
    }
269
270
    /**
271
     * {@inheritdoc}
272
     */
273 18
    public function getIterator(): Iterator
274
    {
275 18
        foreach ($this->intervals as $offset => $interval) {
276 18
            yield $offset => $interval;
277
        }
278 18
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283 30
    public function count(): int
284
    {
285 30
        return count($this->intervals);
286
    }
287
288
    /**
289
     * @inheritdoc
290
     *
291
     * @param int $offset
292
     */
293 3
    public function offsetExists($offset): bool
294
    {
295 3
        return isset($this->intervals[$offset]);
296
    }
297
298
    /**
299
     * @inheritdoc
300
     *
301
     * @param int $offset
302
     */
303 3
    public function offsetGet($offset): Period
304
    {
305 3
        return $this->get($offset);
306
    }
307
308
    /**
309
     * @inheritdoc
310
     *
311
     * @param int $offset
312
     */
313 6
    public function offsetUnset($offset): void
314
    {
315 6
        $this->remove($offset);
316 3
    }
317
318
    /**
319
     * @inheritdoc
320
     *
321
     * @param mixed|int $offset
322
     * @param Period    $interval
323
     */
324 9
    public function offsetSet($offset, $interval): void
325
    {
326 9
        if (null !== $offset) {
327 9
            $this->set($offset, $interval);
328 3
            return;
329
        }
330
331 3
        $this->push($interval);
332 3
    }
333
334
    /**
335
     * Tells whether the sequence is empty.
336
     */
337 15
    public function isEmpty(): bool
338
    {
339 15
        return [] === $this->intervals;
340
    }
341
342
    /**
343
     * Tells whether the given interval is present in the sequence.
344
     *
345
     * @param Period ...$intervals
346
     */
347 6
    public function contains(Period $interval, Period ...$intervals): bool
348
    {
349 6
        $intervals[] = $interval;
350 6
        foreach ($intervals as $period) {
351 6
            if (false === $this->indexOf($period)) {
352 5
                return false;
353
            }
354
        }
355
356 6
        return true;
357
    }
358
359
    /**
360
     * Attempts to find the first offset attached to the submitted interval.
361
     *
362
     * If no offset is found the method returns boolean false.
363
     *
364
     * @return int|bool
365
     */
366 6
    public function indexOf(Period $interval)
367
    {
368 6
        foreach ($this->intervals as $offset => $period) {
369 6
            if ($period->equals($interval)) {
370 6
                return $offset;
371
            }
372
        }
373
374 6
        return false;
375
    }
376
377
    /**
378
     * Returns the interval specified at a given offset.
379
     *
380
     * @throws InvalidIndex If the offset is illegal for the current sequence
381
     */
382 39
    public function get(int $offset): Period
383
    {
384 39
        $period = $this->intervals[$offset] ?? null;
385 39
        if (null !== $period) {
386 30
            return $period;
387
        }
388
389 15
        throw new InvalidIndex(sprintf('%s is an invalid offset in the current sequence', $offset));
390
    }
391
392
    /**
393
     * Sort the current instance according to the given comparison callable
394
     * and maintain index association.
395
     *
396
     * Returns true on success or false on failure
397
     */
398 6
    public function sort(callable $compare): bool
399
    {
400 6
        return uasort($this->intervals, $compare);
401
    }
402
403
    /**
404
     * Adds new intervals at the front of the sequence.
405
     *
406
     * The sequence is re-indexed after addition
407
     *
408
     * @param Period ...$intervals
409
     */
410 3
    public function unshift(Period $interval, Period ...$intervals): void
411
    {
412 3
        $this->intervals = array_merge([$interval], $intervals, $this->intervals);
413 3
    }
414
415
    /**
416
     * Adds new intervals at the end of the sequence.
417
     *
418
     * @param Period ...$intervals
419
     */
420 24
    public function push(Period $interval, Period ...$intervals): void
421
    {
422 24
        $this->intervals = array_merge($this->intervals, [$interval], $intervals);
423 24
    }
424
425
    /**
426
     * Inserts new intervals at the specified offset of the sequence.
427
     *
428
     * The sequence is re-indexed after addition
429
     *
430
     * @param Period ...$intervals
431
     *
432
     * @throws InvalidIndex If the offset is illegal for the current sequence.
433
     */
434 3
    public function insert(int $offset, Period $interval, Period ...$intervals): void
435
    {
436 3
        if ($offset < 0 || $offset > count($this->intervals)) {
437 3
            throw new InvalidIndex(sprintf('%s is an invalid offset in the current sequence', $offset));
438
        }
439
440 3
        array_unshift($intervals, $interval);
441 3
        array_splice($this->intervals, $offset, 0, $intervals);
442 3
    }
443
444
    /**
445
     * Updates the interval at the specify offset.
446
     *
447
     * @throws InvalidIndex If the offset is illegal for the current sequence.
448
     */
449 12
    public function set(int $offset, Period $interval): void
450
    {
451 12
        $this->get($offset);
452 9
        $this->intervals[$offset] = $interval;
453 9
    }
454
455
    /**
456
     * Removes an interval from the sequence at the given offset and returns it.
457
     *
458
     * The sequence is re-indexed after removal
459
     *
460
     * @throws InvalidIndex If the offset is illegal for the current sequence.
461
     */
462 9
    public function remove(int $offset): Period
463
    {
464 9
        $interval = $this->get($offset);
465 6
        unset($this->intervals[$offset]);
466
467 6
        $this->intervals = array_values($this->intervals);
468
469 6
        return $interval;
470
    }
471
472
    /**
473
     * Filters the sequence according to the given predicate.
474
     *
475
     * This method MUST retain the state of the current instance, and return
476
     * an instance that contains the interval which validate the predicate.
477
     */
478 6
    public function filter(callable $predicate): self
479
    {
480 6
        $intervals = array_filter($this->intervals, $predicate, ARRAY_FILTER_USE_BOTH);
481 6
        if ($intervals === $this->intervals) {
482 3
            return $this;
483
        }
484
485 3
        return new self(...$intervals);
486
    }
487
488
    /**
489
     * Removes all intervals from the sequence.
490
     */
491 3
    public function clear(): void
492
    {
493 3
        $this->intervals = [];
494 3
    }
495
496
    /**
497
     * Returns an instance sorted according to the given comparison callable
498
     * but does not maintain index association.
499
     *
500
     * This method MUST retain the state of the current instance, and return
501
     * an instance that contains the sorted intervals. The key are re-indexed
502
     */
503 24
    public function sorted(callable $compare): self
504
    {
505 24
        $intervals = $this->intervals;
506 24
        usort($intervals, $compare);
507 24
        if ($intervals === $this->intervals) {
508 12
            return $this;
509
        }
510
511 15
        return new self(...$intervals);
512
    }
513
514
    /**
515
     * Returns an instance where the given function is applied to each element in
516
     * the collection. The callable MUST return a Period object and takes a Period
517
     * and its associated key as argument.
518
     *
519
     * This method MUST retain the state of the current instance, and return
520
     * an instance that contains the returned intervals.
521
     */
522 9
    public function map(callable $func): self
523
    {
524 9
        $intervals = [];
525 9
        foreach ($this->intervals as $offset => $interval) {
526 9
            $intervals[$offset] = $func($interval, $offset);
527
        }
528
529 9
        if ($intervals === $this->intervals) {
530 3
            return $this;
531
        }
532
533 6
        $mapped = new self();
534 6
        $mapped->intervals = $intervals;
535
536 6
        return $mapped;
537
    }
538
539
    /**
540
     * Iteratively reduces the sequence to a single value using a callback.
541
     *
542
     * @param callable $func Accepts the carry, the current value and the current offset, and
543
     *                       returns an updated carry value.
544
     *
545
     * @param mixed|null $carry Optional initial carry value.
546
     *
547
     * @return mixed The carry value of the final iteration, or the initial
548
     *               value if the sequence was empty.
549
     */
550 6
    public function reduce(callable $func, $carry = null)
551
    {
552 6
        foreach ($this->intervals as $offset => $interval) {
553 6
            $carry = $func($carry, $interval, $offset);
554
        }
555
556 6
        return $carry;
557
    }
558
}
559