Passed
Push — master ( ba9c7a...091f94 )
by Rick
02:47
created

TaskController::removeAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
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 9
	public function __construct(LoopInterface $loop)
32
	{
33 9
		$loop->addPeriodicTimer($this->loopInterval, [$this, 'runTasks']);
34 9
	}
35
36
	/**
37
	 * @param TaskInterface $task
38
	 *
39
	 * @return bool
40
	 */
41 9
	public function add(TaskInterface $task): bool
42
	{
43 9
		if ($this->exists($task))
44 1
			return false;
45
46 9
		$this->tasks[] = $task;
47
48 9
		return true;
49
	}
50
51
	/**
52
	 * @param TaskInterface $task
53
	 *
54
	 * @return bool
55
	 */
56 8
	public function remove(TaskInterface $task): bool
57
	{
58 8
		if (!$this->exists($task))
59 1
			return false;
60
61 8
		unset($this->tasks[array_search($task, $this->tasks)]);
62
63 8
		return true;
64
	}
65
66 1
    public function removeAll()
67
    {
68 1
        foreach ($this->tasks as $task)
69
        {
70 1
            $task->cancel();
71 1
            $this->remove($task);
72
        }
73 1
	}
74
75
	/**
76
	 * @param TaskInterface $task
77
	 *
78
	 * @return bool
79
	 */
80 9
	public function exists(TaskInterface $task): bool
81
	{
82 9
		return in_array($task, $this->tasks);
83
	}
84
85 6
	public function runTasks()
86
	{
87 6
		foreach ($this->tasks as $task)
88
		{
89 6
			if (time() < $task->getExpiryTime())
90 1
				continue;
91
92 6
			$result = $task->run();
93
94
			// It is removed first.
95 6
			$this->remove($task);
96
97 6
			if ($result instanceof TaskInterface)
98 2
				$this->add($result);
99
		}
100
	}
101
}