File tree 4 files changed +59
-2
lines changed
4 files changed +59
-2
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+ declare (strict_types=1 );
3
+
4
+ namespace ThenLabs \TaskLoop ;
5
+
6
+ /**
7
+ * @author Andy Daniel Navarro Taño <andaniel05@gmail.com>
8
+ */
9
+ class CallableTask extends AbstractTask
10
+ {
11
+ /**
12
+ * @var callable
13
+ */
14
+ protected $ callable ;
15
+
16
+ public function __construct (callable $ callable )
17
+ {
18
+ $ this ->callable = $ callable ;
19
+ }
20
+
21
+ public function run (): void
22
+ {
23
+ call_user_func ($ this ->callable , $ this );
24
+ }
25
+ }
Original file line number Diff line number Diff line change 5
5
6
6
use SplObjectStorage ;
7
7
use Symfony \Component \EventDispatcher \EventDispatcher ;
8
+ use TypeError ;
8
9
9
10
/**
10
11
* @author Andy Daniel Navarro Taño <andaniel05@gmail.com>
@@ -42,8 +43,20 @@ public function getTasks(): SplObjectStorage
42
43
return $ this ->tasks ;
43
44
}
44
45
45
- public function addTask (TaskInterface $ task ): void
46
+ /**
47
+ * @param TaskInterface|callable $task
48
+ * @return void
49
+ */
50
+ public function addTask ($ task ): void
46
51
{
52
+ if (! $ task instanceof TaskInterface) {
53
+ if (is_callable ($ task )) {
54
+ $ task = new CallableTask ($ task );
55
+ } else {
56
+ throw new TypeError ('The task argument should be an instance of TaskInterface or a callable. ' );
57
+ }
58
+ }
59
+
47
60
$ event = new Event \AddTaskEvent ($ task );
48
61
$ this ->dispatcher ->dispatch ($ event );
49
62
Original file line number Diff line number Diff line change @@ -21,4 +21,4 @@ public function run(): void
21
21
$ loop ->addTask ($ task );
22
22
23
23
$ task ->end ();
24
- });
24
+ });
Original file line number Diff line number Diff line change 16
16
$ this ->assertCount (0 , $ this ->loop ->getTasks ());
17
17
});
18
18
19
+ test (function () {
20
+ $ this ->expectException (TypeError::class);
21
+
22
+ $ this ->loop ->addTask (uniqid ());
23
+ });
24
+
19
25
test (function () {
20
26
$ task1 = $ this ->getMockBuilder (TaskInterface::class)
21
27
->setMethods (['run ' ])
@@ -90,6 +96,19 @@ public function run(): void
90
96
$ this ->assertCount (3 , $ task2 ->invokations );
91
97
});
92
98
99
+ test (function () {
100
+ $ executed = false ;
101
+
102
+ $ this ->loop ->addTask (function ($ task ) use (&$ executed ) {
103
+ $ executed = true ;
104
+ $ task ->end ();
105
+ });
106
+
107
+ $ this ->loop ->runTasks ();
108
+
109
+ $ this ->assertCount (0 , $ this ->loop ->getTasks ());
110
+ });
111
+
93
112
test (function () {
94
113
$ this ->loop ->getDispatcher ()->addListener (RunTaskEvent::class, function (RunTaskEvent $ event ) {
95
114
$ event ->getTask ()->runned = new DateTime ();
You can’t perform that action at this time.
0 commit comments