Completed
Pull Request — master (#94)
by Alessandro
08:53
created

Pipeline::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Paraunit\Runner;
4
5
use Paraunit\Configuration\EnvVariables;
6
use Paraunit\Lifecycle\ProcessEvent;
7
use Paraunit\Process\AbstractParaunitProcess;
8
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
9
10
/**
11
 * Class Pipeline
12
 * @package Paraunit\Runner
13
 */
14
class Pipeline
15
{
16
    /** @var EventDispatcherInterface */
17
    private $dispatcher;
18
19
    /** @var AbstractParaunitProcess */
20
    private $process;
21
22
    /** @var int */
23
    private $number;
24
25
    /**
26
     * Pipeline constructor.
27
     * @param EventDispatcherInterface $dispatcher
28
     * @param int $number
29
     */
30
    public function __construct(EventDispatcherInterface $dispatcher, int $number)
31
    {
32
        $this->dispatcher = $dispatcher;
33
        $this->number = $number;
34
    }
35
36
    public function execute(AbstractParaunitProcess $process)
37
    {
38
        if (! $this->isFree()) {
39
            throw new \RuntimeException('This pipeline is not free');
40
        }
41
42
        $this->process = $process;
43
        $this->process->start([
44
            EnvVariables::PIPELINE_NUMBER => $this->number,
45
        ]);
46
    }
47
48
    public function isFree(): bool
49
    {
50
        return $this->process === null;
51
    }
52
53
    public function isTerminated(): bool
54
    {
55
        if ($this->isFree()) {
56
            return true;
57
        }
58
59
        return $this->process->isTerminated();
60
    }
61
62
    public function triggerTermination(): bool
63
    {
64
        if ($this->isFree()) {
65
            return false;
66
        }
67
68
        if ($this->process->isTerminated()) {
69
            $this->handleProcessTermination();
70
71
            return true;
72
        }
73
74
        return false;
75
    }
76
77
    public function getNumber(): int
78
    {
79
        return $this->number;
80
    }
81
82
    private function handleProcessTermination()
83
    {
84
        $this->dispatcher->dispatch(ProcessEvent::PROCESS_TERMINATED, new ProcessEvent($this->process));
85
        $this->process = null;
86
    }
87
}
88