<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Utility;

use duncan3dc\Forker\Fork;
use duncan3dc\Forker\SingleThreadAdapter;

class WorkPool
{
    /** @var bool */
    protected $runInParallel = false;

    public function inParallel(bool $inParallel): self
    {
        $clone = clone $this;
        $clone->runInParallel = $inParallel;
        return $clone;
    }

    /** @param callable[] $thingsToRun */
    public function run(array $thingsToRun): void
    {
        // `null` is default adapter (`PcntlAdapter`, if available)
        $adapter = $this->runInParallel ? null : new SingleThreadAdapter();
        $fork = new Fork($adapter);
        foreach ($thingsToRun as $thingToRun) {
            $fork->call($thingToRun);
        }
        $fork->wait();
    }
}
