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 |
||
16 | class FileHandlerLock implements LockInterface |
||
17 | { |
||
18 | /** @var resource|SplFileObject */ |
||
19 | private $fileHandler; |
||
20 | |||
21 | /** @var bool */ |
||
22 | private $isLocked = false; |
||
23 | |||
24 | /** @var bool */ |
||
25 | private $isResource = false; |
||
26 | |||
27 | /** |
||
28 | * @return boolean |
||
29 | */ |
||
30 | public function isLocked() |
||
31 | { |
||
32 | return $this->isLocked; |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * @throws \RuntimeException |
||
37 | */ |
||
38 | public function acquire() |
||
39 | { |
||
40 | if ($this->lockCouldBeAcquired()) { |
||
41 | $this->isLocked = true; |
||
42 | } else { |
||
43 | throw new RuntimeException( |
||
44 | 'Can not acquire lock, lock already exists.' |
||
45 | ); |
||
46 | } |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * @throws \RuntimeException |
||
51 | */ |
||
52 | public function release() |
||
53 | { |
||
54 | if ($this->lockCouldBeReleased()) { |
||
55 | $this->isLocked = false; |
||
56 | } else { |
||
57 | throw new RuntimeException( |
||
58 | 'Can not release lock, no lock exists.' |
||
59 | ); |
||
60 | } |
||
61 | } |
||
62 | |||
63 | /** |
||
64 | * @return mixed|resource|SplFileObject|null |
||
65 | */ |
||
66 | public function getResource() |
||
67 | { |
||
68 | return $this->fileHandler; |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * @param resource|SplFileObject $resource |
||
73 | * @throws InvalidArgumentException |
||
74 | */ |
||
75 | public function setResource($resource) |
||
76 | { |
||
77 | if (is_resource($resource)) { |
||
78 | $this->fileHandler = $resource; |
||
79 | $this->isResource = true; |
||
80 | } else if ($resource instanceof SplFileObject) { |
||
81 | $this->fileHandler = $resource; |
||
82 | $this->isResource = false; |
||
83 | } else { |
||
84 | throw new InvalidArgumentException( |
||
85 | 'provided resource must be of type "resource" or "SplFileObject"' |
||
86 | ); |
||
87 | } |
||
88 | |||
89 | } |
||
90 | |||
91 | /** |
||
92 | * @return bool |
||
93 | */ |
||
94 | View Code Duplication | private function lockCouldBeAcquired() |
|
104 | |||
105 | /** |
||
106 | * @return bool |
||
107 | */ |
||
108 | View Code Duplication | private function lockCouldBeReleased() |
|
118 | } |
||
119 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.