diff --git a/lib/Context/ContextFactory.php b/lib/Context/ContextFactory.php new file mode 100644 index 0000000..1cef4df --- /dev/null +++ b/lib/Context/ContextFactory.php @@ -0,0 +1,28 @@ + + */ + public function run($script): Promise; +} diff --git a/lib/Context/DefaultContextFactory.php b/lib/Context/DefaultContextFactory.php new file mode 100644 index 0000000..fcaa2d6 --- /dev/null +++ b/lib/Context/DefaultContextFactory.php @@ -0,0 +1,36 @@ +create($script); } /** - * @param string|string[] $script + * Creates and starts a process based on installed extensions (a thread if ext-parallel is installed, otherwise a child + * process). + * + * @param string|string[] $script Path to PHP script or array with first element as path and following elements options + * to the PHP script (e.g.: ['bin/worker', 'Option1Value', 'Option2Value']. * * @return Promise */ function run($script): Promise { - if (Parallel::isSupported()) { - return Parallel::run($script); - } - - return Process::run($script); + return factory()->run($script); +} + +/** + * Gets or sets the global context factory. + * + * @param ContextFactory|null $factory + * + * @return ContextFactory + */ +function factory(?ContextFactory $factory = null): ContextFactory +{ + if ($factory === null) { + $factory = Loop::getState(LOOP_FACTORY_IDENTIFIER); + if ($factory) { + return $factory; + } + + $factory = new DefaultContextFactory; + } + Loop::setState(LOOP_FACTORY_IDENTIFIER, $factory); + return $factory; } diff --git a/test/Context/DefaultContextFactoryTest.php b/test/Context/DefaultContextFactoryTest.php new file mode 100644 index 0000000..b234b6d --- /dev/null +++ b/test/Context/DefaultContextFactoryTest.php @@ -0,0 +1,28 @@ +create(__DIR__ . '/Fixtures/test-process.php'); + $this->assertInstanceOf(Context::class, $context); + } + + public function testRun(): \Generator + { + $this->expectException(ContextPanicError::class); + $this->expectExceptionMessage('No string provided'); + + $factory = new DefaultContextFactory; + $context = yield $factory->run(__DIR__ . '/Fixtures/test-process.php'); + yield $context->join(); + } +}