Passed
Push — master ( 72b5f0...bba1ad )
by Rick
01:53
created

TaskController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 79
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add() 0 9 2
A remove() 0 9 2
A exists() 0 4 1
A runTasks() 0 16 4
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 5
	public function __construct(LoopInterface $loop)
32
	{
33 5
		$loop->addPeriodicTimer($this->loopInterval, [$this, 'runTasks']);
34 5
	}
35
36
	/**
37
	 * @param TaskInterface $task
38
	 *
39
	 * @return bool
40
	 */
41 5
	public function add(TaskInterface $task): bool
42
	{
43 5
		if ($this->exists($task))
44 1
			return false;
45
46 5
		$this->tasks[] = $task;
47
48 5
		return true;
49
	}
50
51
	/**
52
	 * @param TaskInterface $task
53
	 *
54
	 * @return bool
55
	 */
56 4
	public function remove(TaskInterface $task): bool
57
	{
58 4
		if (!$this->exists($task))
59 1
			return false;
60
61 4
		unset($this->tasks[array_search($task, $this->tasks)]);
62
63 4
		return true;
64
	}
65
66
	/**
67
	 * @param TaskInterface $task
68
	 *
69
	 * @return bool
70
	 */
71 5
	public function exists(TaskInterface $task): bool
72
	{
73 5
		return in_array($task, $this->tasks);
74
	}
75
76 3
	public function runTasks()
77
	{
78 3
		foreach ($this->tasks as $task)
79
		{
80 3
			if (time() < $task->getExpiryTime())
81 1
				continue;
82
83 3
			$result = $task->run();
84
85
			// It is removed first.
86 3
			$this->remove($task);
87
88 3
			if ($result instanceof TaskInterface)
89 1
				$this->add($result);
90
		}
91
	}
92
}