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 |
||
13 | class NativeWriteStream extends NativeStream { |
||
14 | const CHUNK_SIZE = 1048576; // 1MB chunks |
||
15 | /** |
||
16 | * @var resource |
||
17 | */ |
||
18 | private $writeBuffer = null; |
||
19 | |||
20 | private $bufferSize = 0; |
||
21 | |||
22 | private $pos = 0; |
||
23 | |||
24 | public function stream_open($path, $mode, $options, &$opened_path) { |
||
25 | $this->writeBuffer = fopen('php://memory', 'r+'); |
||
26 | |||
27 | return parent::stream_open($path, $mode, $options, $opened_path); |
||
28 | |||
29 | } |
||
30 | |||
31 | /** |
||
32 | * Wrap a stream from libsmbclient-php into a regular php stream |
||
33 | * |
||
34 | * @param \Icewind\SMB\NativeState $state |
||
35 | * @param resource $smbStream |
||
36 | * @param string $mode |
||
37 | * @param string $url |
||
38 | * @return resource |
||
39 | */ |
||
40 | View Code Duplication | public static function wrap($state, $smbStream, $mode, $url) { |
|
41 | stream_wrapper_register('nativesmb', NativeWriteStream::class); |
||
42 | $context = stream_context_create(array( |
||
43 | 'nativesmb' => array( |
||
44 | 'state' => $state, |
||
45 | 'handle' => $smbStream, |
||
46 | 'url' => $url |
||
47 | ) |
||
48 | )); |
||
49 | $fh = fopen('nativesmb://', $mode, false, $context); |
||
50 | stream_wrapper_unregister('nativesmb'); |
||
51 | return $fh; |
||
52 | } |
||
53 | |||
54 | public function stream_seek($offset, $whence = SEEK_SET) { |
||
62 | |||
63 | private function flushWrite() { |
||
64 | rewind($this->writeBuffer); |
||
65 | $this->state->write($this->handle, stream_get_contents($this->writeBuffer)); |
||
66 | $this->writeBuffer = fopen('php://memory', 'r+'); |
||
67 | $this->bufferSize = 0; |
||
68 | } |
||
69 | |||
70 | public function stream_write($data) { |
||
71 | $written = fwrite($this->writeBuffer, $data); |
||
72 | $this->bufferSize += $written; |
||
73 | $this->pos += $written; |
||
74 | |||
75 | if ($this->bufferSize >= self::CHUNK_SIZE) { |
||
76 | $this->flushWrite(); |
||
77 | } |
||
78 | |||
79 | return $written; |
||
80 | } |
||
81 | |||
82 | public function stream_close() { |
||
83 | $this->flushWrite(); |
||
84 | return parent::stream_close(); |
||
85 | } |
||
86 | |||
87 | public function stream_tell() { |
||
90 | |||
91 | public function stream_read($count) { |
||
94 | |||
95 | public function stream_truncate($size) { |
||
96 | $this->flushWrite(); |
||
97 | $this->pos = $size; |
||
98 | return parent::stream_truncate($size); |
||
99 | } |
||
100 | } |
||
101 |
This check looks for a call to a parent method whose name is different than the method from which it is called.
Consider the following code:
The
getFirstName()
method in theSon
calls the wrong method in the parent class.