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 |
||
14 | class LargeCsvExport { |
||
15 | |||
16 | private $tmpCsvFp; |
||
17 | private $defaultSettings = [ |
||
18 | 'delimiter' => ',', |
||
19 | 'export_encoding' => 'SJIS-win', |
||
20 | 'array_encoding' => 'UTF-8', |
||
21 | ]; |
||
22 | private $settings; |
||
23 | |||
24 | /** |
||
25 | * __construct |
||
26 | * |
||
27 | */ |
||
28 | public function __construct($settings = []) |
||
29 | { |
||
30 | // 設定値 |
||
31 | $this->settings = array_merge( |
||
32 | $this->defaultSettings, |
||
33 | $settings |
||
34 | ); |
||
35 | $this->tmpCsvFp = new File($this->getTmpFileName()); |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * getTmpFileName |
||
40 | * 一時ファイルの取得 |
||
41 | */ |
||
42 | private function getTmpFileName() |
||
43 | { |
||
44 | $tmpFileName = TMP . 'csv_file_' . Security::hash(time() . rand()); |
||
45 | // ファイルが存在した場合は何もしない |
||
46 | if (file_exists($tmpFileName)) { |
||
47 | return $this->getTmpFileName(); |
||
48 | } |
||
49 | return $tmpFileName; |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * addRow |
||
54 | * 都度都度ファイルに追記をしていく |
||
55 | */ |
||
56 | public function addRow($lists) |
||
64 | |||
65 | /** |
||
66 | * read |
||
67 | * csvテキストデータの読み込み(及び一時ファイルの削除) |
||
68 | */ |
||
69 | public function read() |
||
70 | { |
||
71 | $csvText = $this->tmpCsvFp->read(); |
||
72 | // ファイル削除 |
||
73 | $this->tmpCsvFp->delete(); |
||
74 | $this->tmpCsvFp->close(); |
||
75 | return $csvText; |
||
76 | } |
||
77 | |||
78 | /* |
||
79 | * _parseCsv |
||
80 | * csv(など)の形式に変更 |
||
81 | * |
||
82 | * @param array $lists 変換する値 |
||
83 | * @param string 1行分のCSVテキストデータ |
||
84 | */ |
||
85 | private function parseCsv($lists) |
||
99 | |||
100 | } |
||
101 |
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.