Passed
Branch master (eb5e46)
by Rick
01:49
created

TaskController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

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