Passed
Push — master ( 6f883b...72b5f0 )
by Rick
01:50
created

RepeatableTask::run()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 0
crap 3
1
<?php
2
3
/**
4
 * Copyright 2017 NanoSector
5
 *
6
 * You should have received a copy of the MIT license with the project.
7
 * See the LICENSE file for more information.
8
 */
9
10
namespace Yoshi2889\Tasks;
11
12
13
class RepeatableTask implements TaskInterface
14
{
15
	/**
16
	 * @var int
17
	 */
18
	protected $repeatInterval = 0;
19
20
	/**
21
	 * @var int
22
	 */
23
	protected $expiryTime = 0;
24
25
	/**
26
	 * @var TaskInterface
27
	 */
28
	protected $childTask;
29
30
	/**
31
	 * RepeatableTask constructor.
32
	 *
33
	 * @param TaskInterface $childTask
34
	 * @param int $repeatInterval
35
	 */
36 4
	public function __construct(TaskInterface $childTask, int $repeatInterval)
37
	{
38 4
		$this->expiryTime = time() + $repeatInterval;
39 4
		$this->repeatInterval = $repeatInterval;
40 4
		$this->childTask = $childTask;
41 4
	}
42
43
	/**
44
	 * @return null|TaskInterface
45
	 */
46 2
	public function run(): ?TaskInterface
47
	{
48 2
		if (time() >= $this->childTask->getExpiryTime())
49
		{
50 2
			$result = $this->childTask->run();
51
52 2
			if ($result instanceof TaskInterface)
53 1
				$this->childTask = $result;
54
		}
55
56 2
		$this->expiryTime = $this->getExpiryTime() + $this->getRepeatInterval();
57 2
		return $this;
58
	}
59
60 1
	public function cancel(): void
61
	{
62 1
		$this->childTask->cancel();
63 1
		$this->repeatInterval = 0;
64 1
		$this->expiryTime = 0;
65 1
	}
66
67
	/**
68
	 * @return int
69
	 */
70 4
	public function getRepeatInterval(): int
71
	{
72 4
		return $this->repeatInterval;
73
	}
74
75
	/**
76
	 * @param int $repeatInterval
77
	 */
78 1
	public function setRepeatInterval(int $repeatInterval)
79
	{
80 1
		$this->repeatInterval = $repeatInterval;
81 1
	}
82
83
	/**
84
	 * @return int
85
	 */
86 3
	public function getExpiryTime(): int
87
	{
88 3
		return $this->expiryTime;
89
	}
90
}