AsyncProcess   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 47
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hasCallbackSet() 0 3 1
A startJob() 0 23 5
A hasOnErrorSet() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Async;
5
6
use RuntimeException;
7
use Symfony\Component\Process\Process;
8
9
class AsyncProcess extends Process
10
{
11
    /**
12
     * @var bool
13
     */
14
    private $hasCallbackSet;
15
    /**
16
     * @var bool
17
     */
18
    private $hasOnErrorSet;
19
20
    public function startJob(
21
        callable $callback = null,
22
        callable $onError = null
23
    ): void {
24
        $this->hasCallbackSet = null !== $callback;
25
        $this->hasOnErrorSet = null !== $callback;
26
27
        $this->start(
28
            static function (string $type, string $buffer) use ($callback, $onError) {
29
                // if we can't decode probably child failed to execute
30
                if ($decoded = base64_decode($buffer, true)) {
31
                    /** @var AsyncChildResponse $asyncChildResponse */
32
                    $asyncChildResponse = unserialize($decoded, [false]);
33
                } else {
34
                    throw new RuntimeException('Child process returned: ' . $buffer);
35
                }
36
37
                if (null !== $onError && $asyncChildResponse->getError()) {
38
                    $onError($asyncChildResponse->getError());
39
                }
40
41
                if (null !== $callback) {
42
                    $callback($asyncChildResponse->getJobResult(), $asyncChildResponse->getStdOut());
43
                }
44
            }
45
        );
46
    }
47
48
    public function hasCallbackSet(): bool
49
    {
50
        return $this->hasCallbackSet;
51
    }
52
53
    public function hasOnErrorSet(): bool
54
    {
55
        return $this->hasOnErrorSet;
56
    }
57
}