2016-12-30 02:16:04 +01:00
|
|
|
<?php
|
2015-08-22 05:41:38 +02:00
|
|
|
|
2016-08-23 23:47:40 +02:00
|
|
|
namespace Amp\Parallel\Worker;
|
2016-08-18 18:04:48 +02:00
|
|
|
|
2017-11-29 22:01:32 +01:00
|
|
|
use Amp\Parallel\Context\Thread;
|
2017-12-10 23:43:19 +01:00
|
|
|
use Amp\Parallel\Sync\Channel;
|
2017-05-18 09:51:31 +02:00
|
|
|
use Amp\Promise;
|
2015-08-22 05:41:38 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A worker thread that executes task objects.
|
|
|
|
*/
|
2018-10-27 01:29:45 +02:00
|
|
|
final class WorkerThread extends TaskWorker
|
2018-10-07 16:50:45 +02:00
|
|
|
{
|
2017-07-26 08:02:34 +02:00
|
|
|
/**
|
|
|
|
* @param string $envClassName Name of class implementing \Amp\Parallel\Worker\Environment to instigate.
|
|
|
|
* Defaults to \Amp\Parallel\Worker\BasicEnvironment.
|
2019-02-22 22:43:42 +01:00
|
|
|
* @param string|null $bootstrapPath Path to custom autoloader.
|
2017-07-26 08:02:34 +02:00
|
|
|
*/
|
2019-02-22 22:43:42 +01:00
|
|
|
public function __construct(string $envClassName = BasicEnvironment::class, string $bootstrapPath = null)
|
2018-10-07 16:50:45 +02:00
|
|
|
{
|
2019-02-22 22:43:42 +01:00
|
|
|
parent::__construct(new Thread(static function (Channel $channel, string $className, string $bootstrapPath = null): Promise {
|
|
|
|
if ($bootstrapPath !== null) {
|
|
|
|
if (!\is_file($bootstrapPath)) {
|
|
|
|
throw new \Error(\sprintf("No file found at bootstrap file path given '%s'", $bootstrapPath));
|
2019-02-21 00:39:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Include file within unbound closure to protect scope.
|
2019-02-22 22:43:42 +01:00
|
|
|
(static function () use ($bootstrapPath): void {
|
|
|
|
require $bootstrapPath;
|
2019-02-21 00:39:39 +01:00
|
|
|
})->bindTo(null, null)();
|
|
|
|
}
|
|
|
|
|
2017-12-01 06:58:41 +01:00
|
|
|
if (!\class_exists($className)) {
|
|
|
|
throw new \Error(\sprintf("Invalid environment class name '%s'", $className));
|
2017-07-26 08:02:34 +02:00
|
|
|
}
|
|
|
|
|
2017-12-01 06:58:41 +01:00
|
|
|
if (!\is_subclass_of($className, Environment::class)) {
|
2017-07-26 08:02:34 +02:00
|
|
|
throw new \Error(\sprintf("The class '%s' does not implement '%s'", $className, Environment::class));
|
|
|
|
}
|
|
|
|
|
2017-12-01 06:58:41 +01:00
|
|
|
$environment = new $className;
|
2017-07-26 08:02:34 +02:00
|
|
|
|
|
|
|
if (!\defined("AMP_WORKER")) {
|
2019-02-18 06:50:41 +01:00
|
|
|
\define("AMP_WORKER", \AMP_CONTEXT);
|
2017-07-26 08:02:34 +02:00
|
|
|
}
|
|
|
|
|
2017-12-10 23:43:19 +01:00
|
|
|
$runner = new TaskRunner($channel, $environment);
|
2016-08-18 18:04:48 +02:00
|
|
|
return $runner->run();
|
2019-02-22 22:43:42 +01:00
|
|
|
}, $envClassName, $bootstrapPath));
|
2015-08-22 05:41:38 +02:00
|
|
|
}
|
|
|
|
}
|