Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
12 | class Pipe |
||
13 | { |
||
14 | /** |
||
15 | * @var resource |
||
16 | */ |
||
17 | protected $read; |
||
18 | |||
19 | /** |
||
20 | * @var resource |
||
21 | */ |
||
22 | protected $write; |
||
23 | |||
24 | /** |
||
25 | * @var string |
||
26 | */ |
||
27 | protected $filename; |
||
28 | |||
29 | /** |
||
30 | * @var bool |
||
31 | */ |
||
32 | protected $block; |
||
33 | |||
34 | /** |
||
35 | * @param string $filename fifo filename |
||
36 | * @param int $mode |
||
37 | * @param bool $block if blocking |
||
38 | */ |
||
39 | 3 | public function __construct($filename = '/tmp/simple-fork.pipe', $mode = 0666, $block = false) |
|
51 | |||
52 | 3 | public function setBlock($block = true) |
|
53 | { |
||
54 | 3 | if (is_resource($this->read)) { |
|
55 | $set = stream_set_blocking($this->read, $block); |
||
56 | if (!$set) { |
||
57 | throw new \RuntimeException("stream_set_blocking failed"); |
||
58 | } |
||
59 | } |
||
60 | |||
61 | 3 | if (is_resource($this->write)) { |
|
62 | $set = stream_set_blocking($this->write, $block); |
||
63 | if (!$set) { |
||
64 | throw new \RuntimeException("stream_set_blocking failed"); |
||
65 | } |
||
66 | } |
||
67 | |||
68 | 3 | $this->block = $block; |
|
69 | 3 | } |
|
70 | |||
71 | /** |
||
72 | * @param int $size |
||
73 | * @return string |
||
74 | */ |
||
75 | 3 | View Code Duplication | public function read($size = 1024) |
76 | { |
||
77 | 3 | if (!is_resource($this->read)) { |
|
78 | 3 | $this->read = fopen($this->filename, 'r+'); |
|
79 | 3 | if (!is_resource($this->read)) { |
|
80 | throw new \RuntimeException("open file failed"); |
||
81 | } |
||
82 | 3 | if (!$this->block) { |
|
83 | $set = stream_set_blocking($this->read, false); |
||
84 | if (!$set) { |
||
85 | throw new \RuntimeException("stream_set_blocking failed"); |
||
86 | } |
||
87 | } |
||
88 | 3 | } |
|
89 | |||
90 | 3 | return fread($this->read, $size); |
|
91 | } |
||
92 | |||
93 | /** |
||
94 | * @param $message |
||
95 | * @return int |
||
96 | */ |
||
97 | View Code Duplication | public function write($message) |
|
114 | |||
115 | /** |
||
116 | * |
||
117 | */ |
||
118 | 3 | public function close() |
|
127 | |||
128 | /** |
||
129 | * |
||
130 | */ |
||
131 | 3 | public function __destruct() |
|
135 | |||
136 | public function remove() |
||
140 | } |
||
141 |