ProcessManager::run()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4286
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * File ProcessManager.php
4
 *
5
 * @author Edward Pfremmer <[email protected]>
6
 */
7
namespace Epfremme\ProcessQueue\Process;
8
9
use GuzzleHttp\Promise\Promise;
10
use GuzzleHttp\Promise\PromiseInterface;
11
use Symfony\Component\Process\Process;
12
13
/**
14
 * Class ProcessManager
15
 *
16
 * @package Epfremme\ProcessQueue\Process
17
 */
18
class ProcessManager
19
{
20
    /**
21
     * @var ProcessQueue
22
     */
23
    private $queue;
24
25
    /**
26
     * @var ProcessFactory
27
     */
28
    private $factory;
29
30
    /**
31
     * ProcessFactory constructor
32
     *
33
     * @param ProcessFactory $factory
34
     * @param null $limit
35
     */
36 8
    public function __construct(ProcessFactory $factory, $limit = null)
37
    {
38 8
        $this->queue = new ProcessQueue($limit);
39
40 8
        $this->factory = $factory;
41 8
    }
42
43
    /**
44
     * @param \SplFileInfo|string $cwd
45
     * @return PromiseInterface
46
     */
47 6
    public function enqueue($cwd = null)
48
    {
49 6
        $process = $this->factory->make($cwd);
50
51
        /** @var Promise $promise */
52 6
        $promise = new Promise(function() use ($process, &$promise) {
53 4
            if ($process->isStarted()) {
54 4
                $process->wait();
55 4
            }
56
57 4
            $process->isSuccessful()
58 4
                ? $promise->resolve($process)
59 4
                : $promise->reject($process);
60 6
        });
61
62 6
        $this->queue->add($process);
63
64 6
        $process->setOptions([ProcessQueue::PROMISE_KEY => $promise]);
65
66 6
        return $promise;
67
    }
68
69 4
    public function run(\Closure $tick = null)
70
    {
71 4
        $queue = $this->queue;
72
73
        /** @var Process $next */
74 4
        foreach ($queue() as $next) {
75 4
            $next->start();
76 4
            $tick && $tick();
77 4
        }
78 4
    }
79
}
80