Completed
Push — master ( cb7793...7b1e0a )
by Arne
01:36
created

SynchronizationList::getSynchronizationByTime()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
namespace Archivr;
4
5
use Archivr\Exception\Exception;
6
7
class SynchronizationList implements \Countable, \IteratorAggregate
8
{
9
    /**
10
     * Chronologically ordered list of synchronizations (earliest to latest).
11
     *
12
     * @var Synchronization[]
13
     */
14
    protected $synchronizations;
15
16
    /**
17
     * @param Synchronization[] $synchronizations
18
     */
19
    public function __construct(array $synchronizations = [])
20
    {
21
        foreach ($synchronizations as $synchronization)
22
        {
23
            $this->addSynchronization($synchronization);
24
        }
25
    }
26
27
    /**
28
     * @param Synchronization $synchronization
29
     *
30
     * @return SynchronizationList
31
     * @throws Exception
32
     */
33
    public function addSynchronization(Synchronization $synchronization): SynchronizationList
34
    {
35
        if (isset($this->synchronizations[$synchronization->getRevision()]))
36
        {
37
            throw new Exception();
38
        }
39
40
        $this->synchronizations[$synchronization->getRevision()] = $synchronization;
41
42
        return $this;
43
    }
44
45
    /**
46
     * @return Synchronization
47
     */
48
    public function getLastSynchronization()
49
    {
50
        return empty($this->synchronizations) ? null : $this->synchronizations[count($this->synchronizations)];
51
    }
52
53
    /**
54
     * @param int $revision
55
     *
56
     * @return Synchronization
57
     */
58
    public function getSynchronizationByRevision(int $revision)
59
    {
60
        return isset($this->synchronizations[$revision]) ? $this->synchronizations[$revision] : null;
61
    }
62
63
    /**
64
     * Returns the synchronization that was the current one for the given date.
65
     *
66
     * @param \DateTime $time
67
     *
68
     * @return Synchronization
69
     */
70
    public function getSynchronizationByTime(\DateTime $time)
71
    {
72
        $current = null;
73
74
        foreach ($this->synchronizations as $synchronization)
75
        {
76
            if ($synchronization->getTime() > $time)
77
            {
78
                break;
79
            }
80
81
            $current = $synchronization;
82
        }
83
84
        return $current;
85
    }
86
87
    public function count(): int
88
    {
89
        return count($this->synchronizations);
90
    }
91
92
    public function getIterator(): \Traversable
93
    {
94
        return new \ArrayIterator($this->synchronizations);
95
    }
96
}
97