diff --git a/lib/Worker/Internal/Job.php b/lib/Worker/Internal/Job.php index 6dcdc3a..75d3f3f 100644 --- a/lib/Worker/Internal/Job.php +++ b/lib/Worker/Internal/Job.php @@ -2,6 +2,7 @@ namespace Amp\Parallel\Worker\Internal; +use Amp\Parallel\Worker\Environment; use Amp\Parallel\Worker\Task; /** @internal */ @@ -23,10 +24,14 @@ class Job { public function getTask(): Task { // Classes that cannot be autoloaded will be unserialized as an instance of __PHP_Incomplete_Class. - \assert( - $this->task instanceof Task, - \sprintf("Classes implementing %s must be autoloadable by the Composer autoloader", Task::class) - ); + if ($this->task instanceof \__PHP_Incomplete_Class) { + return new class implements Task { + public function run(Environment $environment) { + throw new \Error(\sprintf("Classes implementing %s must be autoloadable by the Composer autoloader", Task::class)); + } + }; + } + return $this->task; } } diff --git a/test/Worker/AbstractWorkerTest.php b/test/Worker/AbstractWorkerTest.php index 524f6cb..b22f8c7 100644 --- a/test/Worker/AbstractWorkerTest.php +++ b/test/Worker/AbstractWorkerTest.php @@ -3,8 +3,17 @@ namespace Amp\Parallel\Test\Worker; use Amp\Loop; +use Amp\Parallel\Worker\Environment; +use Amp\Parallel\Worker\Task; +use Amp\Parallel\Worker\TaskError; use Amp\PHPUnit\TestCase; +class NonAutoloadableTask implements Task { + public function run(Environment $environment) { + return 1; + } +} + abstract class AbstractWorkerTest extends TestCase { /** * @return \Amp\Parallel\Worker\Worker @@ -93,4 +102,21 @@ abstract class AbstractWorkerTest extends TestCase { $this->assertRunTimeLessThan([$worker, 'kill'], 250); $this->assertFalse($worker->isRunning()); } + + public function testUnserializableTask() { + Loop::run(function () { + $worker = $this->createWorker(); + $worker->start(); + + try { + yield $worker->enqueue(new NonAutoloadableTask); + $this->fail("Tasks that cannot be autoloaded should throw an exception"); + } catch (TaskError $exception) { + $this->assertSame("Error", $exception->getName()); + $this->assertGreaterThan(0, \strpos($exception->getMessage(), \sprintf("Classes implementing %s", Task::class))); + } + + yield $worker->shutdown(); + }); + } }