Skip to content

Commit 9ef23ce

Browse files
committed
Created the CallableTask class. The loop supports callables as tasks
1 parent 9cb15d7 commit 9ef23ce

File tree

4 files changed

+59
-2
lines changed

4 files changed

+59
-2
lines changed

src/CallableTask.php

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

src/TaskLoop.php

+14-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
use SplObjectStorage;
77
use Symfony\Component\EventDispatcher\EventDispatcher;
8+
use TypeError;
89

910
/**
1011
* @author Andy Daniel Navarro Taño <andaniel05@gmail.com>
@@ -42,8 +43,20 @@ public function getTasks(): SplObjectStorage
4243
return $this->tasks;
4344
}
4445

45-
public function addTask(TaskInterface $task): void
46+
/**
47+
* @param TaskInterface|callable $task
48+
* @return void
49+
*/
50+
public function addTask($task): void
4651
{
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+
4760
$event = new Event\AddTaskEvent($task);
4861
$this->dispatcher->dispatch($event);
4962

tests/test-AbstractTask.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@ public function run(): void
2121
$loop->addTask($task);
2222

2323
$task->end();
24-
});
24+
});

tests/test-TaskLoop.php

+19
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@
1616
$this->assertCount(0, $this->loop->getTasks());
1717
});
1818

19+
test(function () {
20+
$this->expectException(TypeError::class);
21+
22+
$this->loop->addTask(uniqid());
23+
});
24+
1925
test(function () {
2026
$task1 = $this->getMockBuilder(TaskInterface::class)
2127
->setMethods(['run'])
@@ -90,6 +96,19 @@ public function run(): void
9096
$this->assertCount(3, $task2->invokations);
9197
});
9298

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+
93112
test(function () {
94113
$this->loop->getDispatcher()->addListener(RunTaskEvent::class, function (RunTaskEvent $event) {
95114
$event->getTask()->runned = new DateTime();

0 commit comments

Comments
 (0)