file = $file; } /** * CSVファイルから全データを読み込む * カプセル化: protectedで外部から直接呼び出せない * @return array CSVデータの配列 * @throws RuntimeException ファイル読み込みに失敗した場合 */ protected function readData() { if (!file_exists($this->file)) { return array(); } $handle = fopen($this->file, "r"); if ($handle === false) { throw new RuntimeException("ファイルを開けませんでした: " . $this->file); } try { $data = array(); while ($row = fgetcsv($handle)) { // 空行や必要列数が足りない場合はスキップ if (empty($row) || count($row) < 3) { continue; } $data[] = $row; } return $data; } finally { fclose($handle); } } /** * CSVファイルにデータを書き込む * カプセル化: protectedで外部から直接呼び出せない * @param array $data 書き込むデータの配列 * @return bool 書き込み成功時true * @throws RuntimeException ファイル書き込みに失敗した場合 */ protected function writeData($data) { if (!is_array($data)) { throw new InvalidArgumentException("書き込むデータは配列である必要があります"); } // ディレクトリが存在しない場合は作成 $directory = dirname($this->file); if (!is_dir($directory)) { if (!mkdir($directory, 0755, true)) { throw new RuntimeException("ディレクトリを作成できませんでした: " . $directory); } } $handle = fopen($this->file, "w"); if ($handle === false) { throw new RuntimeException("ファイルに書き込めませんでした: " . $this->file); } try { foreach ($data as $row) { if (fputcsv($handle, $row) === false) { throw new RuntimeException("CSVデータの書き込みに失敗しました"); } } return true; } finally { fclose($handle); } } /** * ファイルパスを取得(カプセル化: 読み取り専用アクセサ) * @return string ファイルパス */ public function getFilePath() { return $this->file; } }