no message

This commit is contained in:
a-kizaki
2026-10-22 08:48:13 +09:00
commit f81638a7b3
13 changed files with 934 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
<?php
/**
* CSVファイル操作の基底クラス
* カプセル化: ファイル操作の詳細をprotectedメソッドで隠蔽
*/
abstract class BaseAccess
{
/** @var string CSVファイルのパス(カプセル化: protectedで継承クラスのみアクセス可能) */
protected $file;
/**
* コンストラクタ
* @param string $file CSVファイルのパス
* @throws InvalidArgumentException ファイルパスが無効な場合
*/
public function __construct($file)
{
if (empty($file)) {
throw new InvalidArgumentException("ファイルパスが指定されていません");
}
$this->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;
}
}