Child::close()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Tleckie\Async;
4
5
use Throwable;
6
7
/**
8
 * Class Child
9
 *
10
 * @package Tleckie\Async
11
 * @author  Teodoro Leckie Westberg <[email protected]>
12
 */
13
class Child
14
{
15
    /** @var Encoder */
16
    private Encoder $encoder;
17
18
    /** @var mixed */
19
    private mixed $output = null;
20
21
    /** @var mixed */
22
    private mixed $exception = null;
23
24
    /**
25
     * Child constructor.
26
     *
27
     * @param Encoder $encoder
28
     */
29
    public function __construct(Encoder $encoder)
30
    {
31
        $this->encoder = $encoder;
32
    }
33
34
    /**
35
     * @param string|null $encoded
36
     * @return $this
37
     */
38
    public function handle(?string $encoded): self
39
    {
40
        try {
41
            $task = $this->encoder->decode($encoded);
42
            $this->output = $this->encoder->encode($task());
43
        } catch (Throwable $exception) {
44
            $this->exception = $this->encoder->encode(new SerializeException($exception));
45
        }
46
47
        return $this;
48
    }
49
50
    /**
51
     * @return mixed
52
     */
53
    public function exception(): mixed
54
    {
55
        return $this->exception;
56
    }
57
58
    /**
59
     * @return mixed
60
     */
61
    public function output(): mixed
62
    {
63
        return $this->output;
64
    }
65
66
    /**
67
     * @return $this
68
     */
69
    public function write(): self
70
    {
71
        fwrite(($this->hasError()) ? STDERR : STDOUT, ($this->exception) ?? $this->output);
72
73
        return $this;
74
    }
75
76
    /**
77
     * @return bool
78
     */
79
    public function hasError(): bool
80
    {
81
        return isset($this->exception);
82
    }
83
84
    /**
85
     * @codeCoverageIgnore
86
     */
87
    public function close()
88
    {
89
        if ($this->exception) {
90
            exit(1);
91
        }
92
        exit(0);
93
    }
94
}
95