Completed
Push — master ( 1bc12c...a15f7e )
by Akihito
02:19
created

Log::write()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 8.5806
cc 4
eloc 23
nc 4
nop 2
1
<?php
2
namespace Ackintosh\Snidel;
3
4
class Log
5
{
6
    /** @var int */
7
    private $ownerPid;
8
9
    /** @var int */
10
    private $masterPid;
11
12
    /** @var resource */
13
    private $destination;
14
15
    /**
16
     * @param   int     $ownerPid
17
     */
18
    public function __construct($ownerPid)
19
    {
20
        $this->ownerPid = $ownerPid;
21
    }
22
23
    public function setMasterPid($pid)
24
    {
25
        $this->masterPid = $pid;
26
    }
27
28
    /**
29
     * sets the resource for the log.
30
     *
31
     * @param   resource    $resource
32
     * @return  void
33
     */
34
    public function setDestination($resource)
35
    {
36
        $this->destination = $resource;
37
    }
38
39
    /**
40
     * writes log
41
     *
42
     * @param   string  $type
43
     * @param   string  $message
44
     * @return  void
45
     */
46
    private function write($type, $message)
47
    {
48
        if ($this->destination === null) {
49
            return;
50
        }
51
        $pid = getmypid();
52
        switch (true) {
53
        case $this->ownerPid === $pid:
54
            $role = 'owner';
55
            break;
56
        case $this->masterPid === $pid:
57
            $role = 'master';
58
            break;
59
        default:
60
            $role = 'worker';
61
            break;
62
        }
63
        fputs(
64
            $this->destination,
65
            sprintf(
66
                '[%s][%s][%d(%s)] %s',
67
                date('Y-m-d H:i:s'),
68
                $type,
69
                $pid,
70
                $role,
71
                $message . PHP_EOL
72
            )
73
        );
74
    }
75
76
    /**
77
     * writes log
78
     *
79
     * @param   string  $message
80
     * @return  void
81
     */
82
    public function info($message)
83
    {
84
        $this->write('info', $message);
85
    }
86
87
    /**
88
     * writes log
89
     *
90
     * @param   string  $message
91
     * @return  void
92
     */
93
    public function error($message)
94
    {
95
        $this->write('error', $message);
96
    }
97
}
98