Completed
Pull Request — master (#79)
by
unknown
12:40
created

Sequence::insert()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 3
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 3
rs 10
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 7
                $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 7
                $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
     * Returns the sum of all instances durations as expressed in seconds.
226
     */
227 3
    public function getTotaTimestampInterval(): float
228
    {
229 3
        $func = function (int $carry, Period $interval): float {
230 3
            return $carry + $interval->getTimestampInterval();
231 3
        };
232
233
        return $this->reduce($func, 0);
234
    }
235 3
236
    /**
237
     * Tells whether some intervals in the current instance satisfies the predicate.
238
     */
239
    public function some(callable $predicate): bool
240
    {
241 3
        foreach ($this->intervals as $offset => $interval) {
242
            if (true === $predicate($interval, $offset)) {
243 3
                return true;
244 3
            }
245 3
        }
246
247
        return false;
248
    }
249 3
250
    /**
251
     * Tells whether all intervals in the current instance satisfies the predicate.
252
     */
253
    public function every(callable $predicate): bool
254
    {
255
        foreach ($this->intervals as $offset => $interval) {
256
            if (true !== $predicate($interval, $offset)) {
257 6
                return false;
258
            }
259 6
        }
260
261
        return [] !== $this->intervals;
262
    }
263
264
    /**
265 3
     * Returns the array representation of the sequence.
266
     *
267 3
     * @return Period[]
268
     */
269
    public function toArray(): array
270
    {
271
        return $this->intervals;
272
    }
273 18
274
    /**
275 18
     * {@inheritdoc}
276 18
     */
277
    public function jsonSerialize(): array
278 18
    {
279
        return $this->intervals;
280
    }
281
282
    /**
283 30
     * {@inheritdoc}
284
     */
285 30
    public function getIterator(): Iterator
286
    {
287
        foreach ($this->intervals as $offset => $interval) {
288
            yield $offset => $interval;
289
        }
290
    }
291
292
    /**
293 3
     * {@inheritdoc}
294
     */
295 3
    public function count(): int
296
    {
297
        return count($this->intervals);
298
    }
299
300
    /**
301
     * @inheritdoc
302
     *
303 3
     * @param int $offset
304
     */
305 3
    public function offsetExists($offset): bool
306
    {
307
        return isset($this->intervals[$offset]);
308
    }
309
310
    /**
311
     * @inheritdoc
312
     *
313 6
     * @param int $offset
314
     */
315 6
    public function offsetGet($offset): Period
316 3
    {
317
        return $this->get($offset);
318
    }
319
320
    /**
321
     * @inheritdoc
322
     *
323
     * @param int $offset
324 9
     */
325
    public function offsetUnset($offset): void
326 9
    {
327 9
        $this->remove($offset);
328 3
    }
329
330
    /**
331 3
     * @inheritdoc
332 3
     *
333
     * @param mixed|int $offset
334
     * @param Period    $interval
335
     */
336
    public function offsetSet($offset, $interval): void
337 15
    {
338
        if (null !== $offset) {
339 15
            $this->set($offset, $interval);
340
            return;
341
        }
342
343
        $this->push($interval);
344
    }
345
346
    /**
347 6
     * Tells whether the sequence is empty.
348
     */
349 6
    public function isEmpty(): bool
350 6
    {
351 6
        return [] === $this->intervals;
352 4
    }
353
354
    /**
355
     * Tells whether the given interval is present in the sequence.
356 6
     *
357
     * @param Period ...$intervals
358
     */
359
    public function contains(Period $interval, Period ...$intervals): bool
360
    {
361
        $intervals[] = $interval;
362
        foreach ($intervals as $period) {
363
            if (false === $this->indexOf($period)) {
364
                return false;
365
            }
366 6
        }
367
368 6
        return true;
369 6
    }
370 6
371
    /**
372
     * Attempts to find the first offset attached to the submitted interval.
373
     *
374 6
     * If no offset is found the method returns boolean false.
375
     *
376
     * @return int|bool
377
     */
378
    public function indexOf(Period $interval)
379
    {
380
        foreach ($this->intervals as $offset => $period) {
381
            if ($period->equals($interval)) {
382 39
                return $offset;
383
            }
384 39
        }
385 39
386 30
        return false;
387
    }
388
389 15
    /**
390
     * Returns the interval specified at a given offset.
391
     *
392
     * @throws InvalidIndex If the offset is illegal for the current sequence
393
     */
394
    public function get(int $offset): Period
395
    {
396
        $period = $this->intervals[$offset] ?? null;
397
        if (null !== $period) {
398 6
            return $period;
399
        }
400 6
401
        throw new InvalidIndex(sprintf('%s is an invalid offset in the current sequence', $offset));
402
    }
403
404
    /**
405
     * Sort the current instance according to the given comparison callable
406
     * and maintain index association.
407
     *
408
     * Returns true on success or false on failure
409
     */
410 3
    public function sort(callable $compare): bool
411
    {
412 3
        return uasort($this->intervals, $compare);
413 3
    }
414
415
    /**
416
     * Adds new intervals at the front of the sequence.
417
     *
418
     * The sequence is re-indexed after addition
419
     *
420 24
     * @param Period ...$intervals
421
     */
422 24
    public function unshift(Period $interval, Period ...$intervals): void
423 24
    {
424
        $this->intervals = array_merge([$interval], $intervals, $this->intervals);
425
    }
426
427
    /**
428
     * Adds new intervals at the end of the sequence.
429
     *
430
     * @param Period ...$intervals
431
     */
432
    public function push(Period $interval, Period ...$intervals): void
433
    {
434 3
        $this->intervals = array_merge($this->intervals, [$interval], $intervals);
435
    }
436 3
437 3
    /**
438
     * Inserts new intervals at the specified offset of the sequence.
439
     *
440 3
     * The sequence is re-indexed after addition
441 3
     *
442 3
     * @param Period ...$intervals
443
     *
444
     * @throws InvalidIndex If the offset is illegal for the current sequence.
445
     */
446
    public function insert(int $offset, Period $interval, Period ...$intervals): void
447
    {
448
        if ($offset < 0 || $offset > count($this->intervals)) {
449 12
            throw new InvalidIndex(sprintf('%s is an invalid offset in the current sequence', $offset));
450
        }
451 12
452 9
        array_unshift($intervals, $interval);
453 9
        array_splice($this->intervals, $offset, 0, $intervals);
454
    }
455
456
    /**
457
     * Updates the interval at the specify offset.
458
     *
459
     * @throws InvalidIndex If the offset is illegal for the current sequence.
460
     */
461
    public function set(int $offset, Period $interval): void
462 9
    {
463
        $this->get($offset);
464 9
        $this->intervals[$offset] = $interval;
465 6
    }
466
467 6
    /**
468
     * Removes an interval from the sequence at the given offset and returns it.
469 6
     *
470
     * The sequence is re-indexed after removal
471
     *
472
     * @throws InvalidIndex If the offset is illegal for the current sequence.
473
     */
474
    public function remove(int $offset): Period
475
    {
476
        $interval = $this->get($offset);
477
        unset($this->intervals[$offset]);
478 6
479
        $this->intervals = array_values($this->intervals);
480 6
481 6
        return $interval;
482 3
    }
483
484
    /**
485 3
     * Filters the sequence according to the given predicate.
486
     *
487
     * This method MUST retain the state of the current instance, and return
488
     * an instance that contains the interval which validate the predicate.
489
     */
490
    public function filter(callable $predicate): self
491 3
    {
492
        $intervals = array_filter($this->intervals, $predicate, ARRAY_FILTER_USE_BOTH);
493 3
        if ($intervals === $this->intervals) {
494 3
            return $this;
495
        }
496
497
        return new self(...$intervals);
498
    }
499
500
    /**
501
     * Removes all intervals from the sequence.
502
     */
503 24
    public function clear(): void
504
    {
505 24
        $this->intervals = [];
506 24
    }
507 24
508 12
    /**
509
     * Returns an instance sorted according to the given comparison callable
510
     * but does not maintain index association.
511 15
     *
512
     * This method MUST retain the state of the current instance, and return
513
     * an instance that contains the sorted intervals. The key are re-indexed
514
     */
515
    public function sorted(callable $compare): self
516
    {
517
        $intervals = $this->intervals;
518
        usort($intervals, $compare);
519
        if ($intervals === $this->intervals) {
520
            return $this;
521
        }
522 9
523
        return new self(...$intervals);
524 9
    }
525 9
526 9
    /**
527
     * Returns an instance where the given function is applied to each element in
528
     * the collection. The callable MUST return a Period object and takes a Period
529 9
     * and its associated key as argument.
530 3
     *
531
     * This method MUST retain the state of the current instance, and return
532
     * an instance that contains the returned intervals.
533 6
     */
534 6
    public function map(callable $func): self
535
    {
536 6
        $intervals = [];
537
        foreach ($this->intervals as $offset => $interval) {
538
            $intervals[$offset] = $func($interval, $offset);
539
        }
540
541
        if ($intervals === $this->intervals) {
542
            return $this;
543
        }
544
545
        $mapped = new self();
546
        $mapped->intervals = $intervals;
547
548
        return $mapped;
549
    }
550 6
551
    /**
552 6
     * Iteratively reduces the sequence to a single value using a callback.
553 6
     *
554
     * @param callable $func Accepts the carry, the current value and the current offset, and
555
     *                       returns an updated carry value.
556 6
     *
557
     * @param mixed|null $carry Optional initial carry value.
558
     *
559
     * @return mixed The carry value of the final iteration, or the initial
560
     *               value if the sequence was empty.
561
     */
562
    public function reduce(callable $func, $carry = null)
563
    {
564
        foreach ($this->intervals as $offset => $interval) {
565
            $carry = $func($carry, $interval, $offset);
566
        }
567
568
        return $carry;
569
    }
570
}
571