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 | 'write_span' => 1, |
||
22 | ]; |
||
23 | private $settings; |
||
24 | private $tmpRowText = ''; |
||
25 | private $rowCount = 0; |
||
26 | |||
27 | /** |
||
28 | * __construct |
||
29 | * |
||
30 | */ |
||
31 | public function __construct($settings = []) |
||
40 | |||
41 | /** |
||
42 | * getTmpFileName |
||
43 | * 一時ファイルの取得 |
||
44 | */ |
||
45 | private function getTmpFileName() |
||
54 | |||
55 | /** |
||
56 | * addRow |
||
57 | * 都度都度ファイルに追記をしていく |
||
58 | */ |
||
59 | public function addRow($lists) |
||
60 | { |
||
61 | if (!is_array($lists)) { |
||
62 | throw new MethodNotAllowedException('$list must be array.'); |
||
63 | } |
||
64 | $this->rowCount++; |
||
65 | $csvRow = $this->parseCsv($lists); |
||
66 | $this->tmpRowText .= $csvRow; |
||
67 | if ($this->rowCount % $this->settings['write_span'] == 0) { |
||
68 | $this->writeRow(); |
||
69 | } |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * writeRow |
||
74 | * 行の書き込み |
||
75 | */ |
||
76 | private function writeRow() |
||
77 | { |
||
78 | $this->tmpCsvFp->write($this->tmpRowText, 'a'); |
||
79 | // 一時的なテキストの初期化 |
||
80 | $this->tmpRowText = ''; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * read |
||
85 | * csvテキストデータの読み込み(及び一時ファイルの削除) |
||
86 | */ |
||
87 | public function read() |
||
88 | { |
||
89 | // 書き込みの残りがあれば書き込む |
||
90 | $this->writeRow(); |
||
91 | |||
92 | $csvText = $this->tmpCsvFp->read(); |
||
93 | // ファイル削除 |
||
94 | $this->tmpCsvFp->delete(); |
||
95 | $this->tmpCsvFp->close(); |
||
96 | return $csvText; |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * getPath |
||
101 | * ファイルパスの取得。readメソッドでメモリで落ちる場合はパスを取得してrequest->fileでDLする |
||
102 | */ |
||
103 | public function getPath() |
||
104 | { |
||
105 | // 書き込みの残りがあれば書き込む |
||
106 | $this->writeRow(); |
||
107 | return $this->tmpCsvFp->pwd(); |
||
108 | } |
||
109 | |||
110 | /* |
||
111 | * _parseCsv |
||
112 | * csv(など)の形式に変更 |
||
113 | * |
||
114 | * @param array $lists 変換する値 |
||
115 | * @param string 1行分のCSVテキストデータ |
||
116 | */ |
||
117 | private function parseCsv($lists) |
||
131 | |||
132 | } |
||
133 |
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.