2015-08-27 16:10:08 +02:00
|
|
|
<?php
|
|
|
|
namespace Icicle\Concurrent\Worker\Internal;
|
|
|
|
|
2015-10-18 08:54:09 +02:00
|
|
|
use Icicle\Concurrent\Sync\ChannelInterface;
|
2015-09-10 06:29:41 +02:00
|
|
|
use Icicle\Concurrent\Worker\Environment;
|
2015-08-27 16:10:08 +02:00
|
|
|
use Icicle\Concurrent\Worker\TaskInterface;
|
|
|
|
|
|
|
|
class TaskRunner
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var bool
|
|
|
|
*/
|
|
|
|
private $idle = true;
|
|
|
|
|
|
|
|
/**
|
2015-10-18 08:54:09 +02:00
|
|
|
* @var \Icicle\Concurrent\Sync\ChannelInterface
|
2015-08-27 16:10:08 +02:00
|
|
|
*/
|
|
|
|
private $channel;
|
|
|
|
|
2015-09-10 06:29:41 +02:00
|
|
|
/**
|
|
|
|
* @var \Icicle\Concurrent\Worker\Environment
|
|
|
|
*/
|
|
|
|
private $environment;
|
|
|
|
|
|
|
|
public function __construct(ChannelInterface $channel, Environment $environment)
|
2015-08-27 16:10:08 +02:00
|
|
|
{
|
|
|
|
$this->channel = $channel;
|
2015-09-10 06:29:41 +02:00
|
|
|
$this->environment = $environment;
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @coroutine
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
|
|
|
public function run()
|
|
|
|
{
|
2015-09-01 23:20:57 +02:00
|
|
|
$task = (yield $this->channel->receive());
|
2015-08-27 16:10:08 +02:00
|
|
|
|
|
|
|
while ($task instanceof TaskInterface) {
|
|
|
|
$this->idle = false;
|
|
|
|
|
|
|
|
try {
|
2015-09-10 06:29:41 +02:00
|
|
|
$result = (yield $task->run($this->environment));
|
2015-08-27 16:10:08 +02:00
|
|
|
} catch (\Exception $exception) {
|
|
|
|
$result = new TaskFailure($exception);
|
|
|
|
}
|
|
|
|
|
|
|
|
yield $this->channel->send($result);
|
|
|
|
|
|
|
|
$this->idle = true;
|
|
|
|
|
2015-09-01 23:20:57 +02:00
|
|
|
$task = (yield $this->channel->receive());
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
yield $task;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function isIdle()
|
|
|
|
{
|
|
|
|
return $this->idle;
|
|
|
|
}
|
|
|
|
}
|