/** * @param \SplFileInfo $file * @param string|null $filename * @param string|null $title * @throws SyntaxException * @return Dictionary */ public function parse(\SplFileInfo $file, string $filename = null, string $title = null) : Dictionary { if ($file instanceof \SplTempFileObject) { $binary = (new Parser())->getBinary($file); } $byteFormatter = new \ScriptFUSION\Byte\ByteFormatter(); $fileSize = isset($binary) ? strlen(bin2hex($binary)) / 2 : $file->getSize(); if ($fileSize > self::MAX_COMPRESSED_ARCHIVE_SIZE) { throw new SyntaxException(sprintf(_('ファイルサイズは %1$s 以下にしてください: 現在 %2$s'), $byteFormatter->format(self::MAX_COMPRESSED_ARCHIVE_SIZE), $byteFormatter->format($fileSize))); } elseif ($fileSize > self::MAX_RECOMMENDED_COMPRESSED_ARCHIVE_SIZE) { $this->logger->warning(sprintf(_('ファイルサイズは %1$s 以下にすべきです: 現在 %2$s'), $byteFormatter->format(self::MAX_RECOMMENDED_COMPRESSED_ARCHIVE_SIZE), $byteFormatter->format($fileSize))); } $finfo = new Finfo(FILEINFO_MIME_TYPE); $type = isset($binary) ? $finfo->buffer($binary) : $finfo->file($file->getRealPath()); switch ($type) { case 'application/zip': $this->header = true; $csvFile = $this->parseArchive($file); $csv = new \SplFileInfo($this->generateTempFile($csvFile)); $files = new \FilesystemIterator($csvFile->getPath(), \FilesystemIterator::SKIP_DOTS); unlink($csvFile); break; case 'text/csv': case 'text/plain': $csv = $file; break; default: throw new SyntaxException(_('汎用辞書はCSVファイルかZIPファイルでなければなりません。')); } $filesCount = (isset($files) ? iterator_count($files) : count($this->filenames)) + 1; if ($filesCount > self::MAX_FILES) { throw new SyntaxException(sprintf(_('アーカイブ中のファイル数は %1$s 個以下にしてください: 現在 %2$s 個'), self::MAX_FILES, $filesCount)); } elseif ($filesCount > self::MAX_RECOMMENDED_FILES) { $this->logger->warning(sprintf(_('アーカイブ中のファイル数は %1$s 個以下にすべきです: 現在 %2$s 個'), self::MAX_RECOMMENDED_FILES, $filesCount)); } $dictionary = new Dictionary($files ?? $this->filenames); $dictionary->setLogger($this->logger); $this->parseCSVFile($dictionary, $csv, $this->header); if (!$dictionary->getWords()) { throw new SyntaxException(_('CSVファイルが空です。')); } $metadata = $dictionary->getMetadata(); if (!isset($metadata['@title'])) { if (!is_null($title)) { $metadata['@title'] = $title; } elseif (!is_null($filename)) { $titleFromFilename = $this->getTitleFromFilename($filename); if ($titleFromFilename !== '') { $metadata['@title'] = $titleFromFilename; } } $dictionary->setMetadata($metadata); } return $dictionary; }