Completed
Push — master ( 1fa11a...2abe5b )
by Akihito
02:24
created

Worker::error()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 9
nc 2
nop 0
1
<?php
2
namespace Ackintosh\Snidel;
3
4
use Ackintosh\Snidel\Pcntl;
5
use Ackintosh\Snidel\Result\Result;
6
7
class Worker
8
{
9
    /** @var \Ackintosh\Snidel\Task\Task */
10
    private $task;
11
12
    /** @var \Ackintosh\Snidel\Fork\Fork */
13
    private $fork;
14
15
    /** @var \Ackintosh\Snidel\Result\Queue */
16
    private $resultQueue;
17
18
    /** @var \Ackintosh\Snidel\Pcntl */
19
    private $pcntl;
20
21
    /**
22
     * @param   \Ackintosh\Snidel\Fork\Fork $fork
23
     * @param   \Ackintosh\Snidel\Task\Task
24
     */
25
    public function __construct($fork, $task)
26
    {
27
        $this->pcntl    = new Pcntl();
28
        $this->fork     = $fork;
29
        $this->task     = $task;
30
    }
31
32
    /**
33
     * @param   \Ackintosh\Snidel\Result\Queue
34
     * @return  void
35
     */
36
    public function setResultQueue($queue)
37
    {
38
        $this->resultQueue = $queue;
39
    }
40
41
    /**
42
     * @return  int
43
     */
44
    public function getPid()
45
    {
46
        return $this->fork->getPid();
47
    }
48
49
    /**
50
     * @return  void
51
     * @throws  \RuntimeException
52
     */
53
    public function run()
54
    {
55
        try {
56
            $result = $this->task->execute();
57
        } catch (\RuntimeException $e) {
58
            throw $e;
59
        }
60
61
        $result->setFork($this->fork);
62
63
        try {
64
            $this->resultQueue->enqueue($result);
65
        } catch (\RuntimeException $e) {
66
            throw $e;
67
        }
68
    }
69
70
    /**
71
     * @return  void
72
     * @throws  \RuntimeException
73
     */
74
    public function error()
75
    {
76
        $result = new Result();
77
        $result->setError(error_get_last());
78
        $result->setTask($this->task);
79
        $result->setFork($this->fork);
80
81
        try {
82
            $this->resultQueue->enqueue($result);
83
        } catch (\RuntimeException $e) {
84
            throw $e;
85
        }
86
    }
87
88
    /**
89
     * @param   int     $sig
90
     * @return  void
91
     */
92
    public function terminate($sig)
93
    {
94
        posix_kill($this->fork->getPid(), $sig);
95
        $status = null;
96
        $this->pcntl->waitpid($this->fork->getPid(), $status);
97
    }
98
}
99