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

TaskController::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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
use React\EventLoop\LoopInterface;
13
14
class TaskController
15
{
16
	/**
17
	 * @var int
18
	 */
19
	protected $loopInterval = 1;
20
21
	/**
22
	 * @var TaskInterface[]
23
	 */
24
	protected $tasks = [];
25
26
	/**
27
	 * TaskController constructor.
28
	 *
29
	 * @param LoopInterface $loop
30
	 */
31 4
	public function __construct(LoopInterface $loop)
32
	{
33 4
		$loop->addPeriodicTimer($this->loopInterval, [$this, 'runTasks']);
34 4
	}
35
36
	/**
37
	 * @param TaskInterface $task
38
	 *
39
	 * @return bool
40
	 */
41 4
	public function add(TaskInterface $task): bool
42
	{
43 4
		if ($this->exists($task))
44 1
			return false;
45
46 4
		$this->tasks[] = $task;
47
48 4
		return true;
49
	}
50
51
	/**
52
	 * @param TaskInterface $task
53
	 *
54
	 * @return bool
55
	 */
56 3
	public function remove(TaskInterface $task): bool
57
	{
58 3
		if (!$this->exists($task))
59 1
			return false;
60
61 3
		unset($this->tasks[array_search($task, $this->tasks)]);
62
63 3
		return true;
64
	}
65
66
	/**
67
	 * @param TaskInterface $task
68
	 *
69
	 * @return bool
70
	 */
71 4
	public function exists(TaskInterface $task): bool
72
	{
73 4
		return in_array($task, $this->tasks);
74
	}
75
76 2
	public function runTasks()
77
	{
78 2
		foreach ($this->tasks as $task)
79
		{
80 2
			if (time() < $task->getExpiryTime())
81 1
				continue;
82
83 2
			$result = $task->run();
84
85
			// It is removed first.
86 2
			$this->remove($task);
87
88 2
			if ($result instanceof TaskInterface)
89
				$this->add($result);
90
		}
91
	}
92
}