Completed
Push — master ( 5002cd...65c93a )
by Akihito
02:22
created

ForkContainer::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Ackintosh\Snidel;
3
4
use Ackintosh\Snidel\Fork;
5
use Ackintosh\Snidel\ForkCollection;
6
use Ackintosh\Snidel\Pcntl;
7
8
class ForkContainer
9
{
10
    /** @var \Ackintosh\Snidel\Fork[] */
11
    private $forks = array();
12
13
    /** @var \Ackintosh\Snidel\Pcntl */
14
    private $pcntl;
15
16
    /** @var array */
17
    private $tagsToPids = array();
18
19
    public function __construct()
20
    {
21
        $this->pcntl = new Pcntl();
22
    }
23
24
    /**
25
     * fork process
26
     *
27
     * @return \Ackintosh\Snidel\Fork
28
     * @throws \RuntimeException
29
     */
30
    public function fork($tag = null)
31
    {
32
        $pid = $this->pcntl->fork();
33
        if ($pid === -1) {
34
            throw new \RuntimeException('could not fork a new process');
35
        }
36
37
        $this->forks[$pid] = new Fork($pid);
38
        if ($tag !== null) {
39
            $this->tagsToPids[$pid] = $tag;
40
        }
41
42
        return $this->forks[$pid];
43
    }
44
45
    /**
46
     *
47
     * @param   string  $tag
48
     * @return  bool
49
     */
50
    public function hasTag($tag)
51
    {
52
        return in_array($tag, $this->tagsToPids, true);
53
    }
54
55
    /**
56
     * wait child
57
     *
58
     * @return \Ackintosh\Snidel\Fork
59
     */
60
    public function wait()
61
    {
62
        $status = null;
63
        $childPid = $this->pcntl->waitpid(-1, $status);
64
        $this->get($childPid)->setStatus($status);
65
        $this->get($childPid)->loadResult();
66
67
        return $this->get($childPid);
68
    }
69
70
    /**
71
     * return fork
72
     *
73
     * @param   int     $pid
74
     * @return  \Ackintosh\Snidel\Fork
75
     */
76
    public function get($pid)
77
    {
78
        return $this->forks[$pid];
79
    }
80
81
    public function getCollection($tag = null)
82
    {
83
        if ($tag === null) {
84
            return new ForkCollection($this->forks);
85
        }
86
87
        return $this->getCollectionWithTag($tag);
88
    }
89
90
    /**
91
     * return forks
92
     *
93
     * @param   string  $tag
94
     * @return  \Ackintosh\Snidel\Fork[]
95
     */
96
    private function getCollectionWithTag($tag)
97
    {
98
        return new ForkCollection(
99
            array_filter($this->forks, function ($fork) use ($tag) {
100
                return $this->tagsToPids[$fork->getPid()] === $tag;
101
            })
102
        );
103
    }
104
}
105