1: <?php declare(strict_types = 1);
2:
3: namespace ApiGen\Scheduler;
4:
5: use ApiGen\Scheduler;
6: use ApiGen\Task\Task;
7: use ApiGen\Task\TaskHandler;
8: use ApiGen\Task\TaskHandlerFactory;
9: use Nette\DI\Container;
10:
11: use function extension_loaded;
12: use function function_exists;
13:
14: use const PHP_SAPI;
15:
16:
17: class SchedulerFactory
18: {
19: public function __construct(
20: protected Container $container,
21: protected int $workerCount,
22: ) {
23: }
24:
25:
26: /**
27: * @template TTask of Task
28: * @template TResult
29: * @template TContext
30: *
31: * @param class-string<TaskHandlerFactory<TContext, TaskHandler<TTask, TResult>>> $handlerFactoryType
32: * @param TContext $context
33: * @return Scheduler<TTask, TResult>
34: */
35: public function create(string $handlerFactoryType, mixed $context): Scheduler
36: {
37: if ($this->workerCount > 1 && PHP_SAPI === 'cli') {
38: if (extension_loaded('pcntl')) {
39: $handler = $this->createHandler($handlerFactoryType, $context);
40: return new ForkScheduler($handler, $this->workerCount);
41:
42: } elseif (function_exists('proc_open')) {
43: return new ExecScheduler($this->container::class, $this->container->getParameters(), $handlerFactoryType, $context, $this->workerCount);
44: }
45: }
46:
47: $handler = $this->createHandler($handlerFactoryType, $context);
48: return new SimpleScheduler($handler);
49: }
50:
51:
52: /**
53: * @template TTask of Task
54: * @template TResult
55: * @template TContext
56: *
57: * @param class-string<TaskHandlerFactory<TContext, TaskHandler<TTask, TResult>>> $handlerFactoryType
58: * @param TContext $context
59: * @return TaskHandler<TTask, TResult>
60: */
61: private function createHandler(string $handlerFactoryType, mixed $context): TaskHandler
62: {
63: $factory = $this->container->getByType($handlerFactoryType);
64: return $factory->create($context);
65: }
66: }
67: