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 Printer |
||
17 | { |
||
18 | private $output; |
||
19 | |||
20 | 6 | public function __construct(OutputInterface $output) |
|
24 | |||
25 | 5 | public function command(Host $host, string $command) |
|
26 | { |
||
27 | // -v for run command |
||
28 | 5 | if ($this->output->isVerbose()) { |
|
29 | 2 | $this->output->writeln("[{$host->tag()}] <fg=green;options=bold>run</> $command"); |
|
30 | } |
||
31 | 5 | } |
|
32 | |||
33 | /** |
||
34 | * Returns a callable for use with the symfony Process->run($callable) method. |
||
35 | * |
||
36 | * @param Host $host |
||
37 | * @return callable A function expecting a int $type (e.g. Process::OUT or Process::ERR) and string $buffer parameters. |
||
38 | */ |
||
39 | 5 | public function callback(Host $host) |
|
40 | { |
||
41 | return function ($type, $buffer) use ($host) { |
||
42 | 5 | if ($this->output->isVerbose()) { |
|
43 | 2 | $this->printBuffer($type, $host, $buffer); |
|
44 | } |
||
45 | 5 | }; |
|
46 | } |
||
47 | |||
48 | /** |
||
49 | * @param string $type Process::OUT or Process::ERR |
||
50 | * @param Host $host |
||
51 | * @param string $buffer |
||
52 | */ |
||
53 | 2 | public function printBuffer(string $type, Host $host, string $buffer) |
|
54 | { |
||
55 | 2 | foreach (explode("\n", rtrim($buffer)) as $line) { |
|
56 | 2 | $this->writeln($type, $host, $line); |
|
57 | } |
||
58 | 2 | } |
|
59 | |||
60 | /** |
||
61 | * @param string $type Process::OUT or Process::ERR |
||
62 | * @param Host $host |
||
63 | * @param string $line |
||
64 | */ |
||
65 | 2 | View Code Duplication | public function writeln(string $type, Host $host, string $line) |
66 | { |
||
67 | 2 | $line = self::filterOutput($line); |
|
68 | |||
69 | // Omit empty lines |
||
70 | 2 | if (empty($line)) { |
|
71 | return; |
||
72 | } |
||
73 | |||
74 | 2 | if ($type === Process::ERR) { |
|
75 | $line = "[{$host->tag()}] <fg=red>err</> $line"; |
||
76 | } else { |
||
77 | 2 | $line = "[{$host->tag()}] $line"; |
|
78 | } |
||
79 | |||
80 | 2 | $this->output->writeln($line); |
|
81 | 2 | } |
|
82 | |||
83 | /** |
||
84 | * This filtering used only in Ssh\Client, but for simplify putted here. |
||
85 | * |
||
86 | * @param string $output |
||
87 | * @return string |
||
88 | */ |
||
89 | 5 | public static function filterOutput($output) |
|
93 | } |
||
94 |