/** * ZIPアーカイブを解析し、ファイルの矯正を行います。 * @param \SplFileInfo $file * @throws SyntaxException * @return \SplFileInfo */ protected function parseArchive(\SplFileInfo $file) : \SplFileInfo { $archive = new ZipOutputFile(ZipFile::openFromFile($file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath())); $this->correctArchiveFilenamesEncoding($archive); $this->flattenArchive($archive); $this->filenames = $this->correctArchiveFilenames($archive); $tempDirectoryPath = (new GenericDictionaryParser())->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach (new \FilesystemIterator($tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME) as $filename => $file) { if ($file->getExtension() === 'txt') { if (isset($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが2つ以上含まれています。')); } if (!in_array((new Finfo(FILEINFO_MIME_TYPE))->file($file), ['text/plain', 'text/csv'])) { throw new SyntaxException(sprintf(_('「%s」は通常のテキストファイルとして認識できません。'), $filename)); } $quizFile = $file; } } if (empty($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが見つかりません。')); } return $quizFile; }
/** * ZIPアーカイブを解析し、ファイルの矯正を行います。 * @param SplFileInfo $file * @throws SyntaxException * @throws \LogicException 権限エラーなどでZIPファイルを開けなかった場合、または書き込めなかった場合。 * @return \SplFileObject CSVファイル。 */ protected function parseArchive(\SplFileInfo $file) : \SplFileInfo { $archive = new \ZipArchive(); $result = $archive->open($file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath(), \ZipArchive::CHECKCONS); if ($result !== true) { switch ($result) { case \ZipArchive::ER_INCONS: case \ZipArchive::ER_NOZIP: throw new SyntaxException(_('妥当なZIPファイルではありません。')); default: throw new \LogicException("ZIPファイルの解析に失敗しました。エラーコード: {$result}"); } } $tempDirectoryPath = $this->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $files = new \FilesystemIterator($tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME); $finfo = new Finfo(FILEINFO_MIME_TYPE); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach ($files as $filename => $file) { if ($filename === 'dictionary.csv') { if (!in_array($finfo->file($file), ['text/plain', 'text/csv'])) { throw new SyntaxException(_('「dictionary.csv」は通常のテキストファイルとして認識できません。')); } $csvFile = $file; continue; } $validator->correct($file, $filename); } if (empty($csvFile)) { throw new SyntaxException(_('「dictionary.csv」が見つかりません。')); } return $csvFile; }