/**
  * @param Dictionary $dictionary
  * @throws EmptyOutputException 該当の辞書形式に変換可能なお題が一つも存在しなかった。
  * @return string[]
  */
 public function serialize(Dictionary $dictionary) : array
 {
     foreach ($dictionary->getWords() as $word) {
         $serialized = $this->serializeWord($word);
         if ($serialized !== '') {
             $words[] = $serialized;
         }
     }
     if (empty($words)) {
         throw new EmptyOutputException(sprintf(_('%sの辞書形式に変換可能なお題が見つかりませんでした。'), 'ピクトセンス'));
     }
     $wordsLength = count($words);
     if ($wordsLength > PictsenseParser::WORDS_MAX) {
         $this->logger->critical(sprintf(_('お題が%1$d個あります。%2$d個以内でなければピクトセンスに辞書登録することはできません。'), $wordsLength, PictsenseParser::WORDS_MAX));
     } elseif ($wordsLength < PictsenseParser::WORDS_MIN) {
         $this->logger->critical(sprintf(_('お題が%1$d個しかありません。%2$d個以上でなければピクトセンスに辞書登録することはできません。'), $wordsLength, PictsenseParser::WORDS_MIN));
     }
     $dictioanryCodePoints = mb_strlen(implode('', $words), 'UTF-8');
     if ($dictioanryCodePoints > PictsenseParser::DICTIONARY_CODE_POINTS_MAX) {
         $this->logger->critical(sprintf(_('辞書全体で%1$d文字あります。%2$d文字以内でなければピクトセンスに辞書登録することはできません。'), $dictioanryCodePoints, PictsenseParser::DICTIONARY_CODE_POINTS_MAX));
     }
     $name = $this->getFilename($dictionary, 'csv');
     $nameLength = (new PictsenseParser())->getLengthAs16BitCodeUnits(str_replace('.csv', '', $name));
     if ($nameLength > PictsenseParser::TITLE_MAX) {
         $this->logger->error(sprintf(_('辞書名が%1$d文字 (補助文字は2文字扱い) あります。ピクトセンスに辞書登録する場合、%2$d文字より後の部分は切り詰められます。'), $dictioanryCodePoints, PictsenseParser::TITLE_MAX));
     }
     return ['bytes' => implode("\r\n", $words) . "\r\n", 'type' => 'text/csv; charset=UTF-8; header=absent', 'name' => $name];
 }
 /**
  * @param Dictionary $dictionary
  * @throws EmptyOutputException 該当の辞書形式に変換可能なお題が一つも存在しなかった。
  * @return string[]
  */
 public function serialize(Dictionary $dictionary) : array
 {
     foreach ($dictionary->getWords() as $word) {
         $serialized = $this->serializeWord($word);
         if ($serialized !== '') {
             $words[] = $serialized;
         }
     }
     if (empty($words)) {
         throw new EmptyOutputException(_('きゃっちまの辞書形式に変換可能なお題が見つかりませんでした。'));
     }
     return ['bytes' => mb_convert_encoding($this->serializeMetadata($dictionary, '//', ['[', ']']) . implode('', $words), 'Windows-31J', 'UTF-8'), 'type' => 'text/plain; charset=Shift_JIS', 'name' => $this->getFilename($dictionary, 'dat')];
 }
 /**
  * @param Dictionary $dictionary
  * @throws EmptyOutputException 該当の辞書形式に変換可能なお題が一つも存在しなかった。
  * @return string[]
  */
 public function serialize(Dictionary $dictionary) : array
 {
     foreach ($dictionary->getWords() as $word) {
         $serialized = $this->serializeWord($word);
         if ($serialized !== '') {
             $words[] = $serialized;
         }
     }
     if (empty($words)) {
         throw new EmptyOutputException(sprintf(_('%sの辞書形式に変換可能なお題が見つかりませんでした。'), 'キャッチフィーリング'));
     }
     return ['bytes' => mb_convert_encoding(implode('', $words), 'Windows-31J', 'UTF-8'), 'type' => 'text/plain; charset=Shift_JIS', 'name' => $this->getFilename($dictionary, 'cfq', ' [語数 ' . count($words) . ']')];
 }
 /**
  * ヘッダ行に用いるフィールド名の一覧を生成します。
  * @param Dictionary $dictionary
  * @return string[]
  */
 protected function getFieldNames(Dictionary $dictionary) : array
 {
     // 各フィールド名について、全レコード中の最大数をそれぞれ取得
     foreach ($dictionary->getWords() as $word) {
         foreach ($word as $fieldName => $fields) {
             $fieldLengths[$fieldName] = max(count($fields), $fieldLengths[$fieldName] ?? 0);
         }
     }
     $fieldLengths += array_fill_keys(array_keys($dictionary->getMetadata()), 1);
     uksort($fieldLengths, function (string $a, string $b) : int {
         return $this->getColumnPosition($a) <=> $this->getColumnPosition($b);
     });
     // ヘッダを生成
     return array_merge(...array_map(function (string $fieldName, int $length) : array {
         return array_fill(0, $length, $fieldName);
     }, array_keys($fieldLengths), $fieldLengths));
 }
 /**
  * @param Dictionary $dictionary
  * @throws \BadMethodCallException $this->textFileOnly が偽、かつ「画像・音声・動画ファイルを含む場合のファイル形式」をCSVファイルのみで構文解析していた場合。
  * @throws EmptyOutputException 該当の辞書形式に変換可能なお題が一つも存在しなかった。
  * @return string[]
  */
 public function serialize(Dictionary $dictionary) : array
 {
     $directoryName = (new \esperecyan\dictionary_php\validator\FilenameValidator())->convertToValidFilenameWithoutExtensionInArchives($dictionary->getTitle());
     foreach ($dictionary->getWords() as $word) {
         $serialized = $this->type === 'Inteligenceω しりとり' ? $this->serializeWordAsShiritori($word) : $this->serializeWordAsQuiz($word, $directoryName);
         if ($serialized !== '') {
             $words[] = $serialized;
         }
     }
     if (empty($words)) {
         throw new EmptyOutputException(sprintf(_('%sの辞書形式に変換可能なお題が見つかりませんでした。'), $this->type));
     }
     $previousSubstituteCharacter = mb_substitute_character();
     mb_substitute_character(\IntlChar::ord(self::SUBSTITUTE_CHARACTER));
     $bytes = mb_convert_encoding($this->serializeMetadata($dictionary, '%') . implode('', $words), 'Windows-31J', 'UTF-8');
     mb_substitute_character($previousSubstituteCharacter);
     $files = $dictionary->getFiles();
     if (!$files && !$this->textFileOnly && $dictionary->getFilenames()) {
         throw new \BadMethodCallException();
     } elseif ($this->type === 'Inteligenceω クイズ' && $files && !$this->textFileOnly) {
         $archive = $this->generateArchive();
         foreach ($files as $file) {
             $archive->addFile($file, "{$directoryName}/" . $file->getFilename());
         }
         $archive->addFromString("{$directoryName}.txt", $bytes);
         $archivePath = $archive->filename;
         $archive->close();
         return ['bytes' => file_get_contents($archivePath), 'type' => 'application/zip', 'name' => $this->getFilename($dictionary, 'zip')];
     } else {
         return ['bytes' => $bytes, 'type' => 'text/plain; charset=Shift_JIS', 'name' => $this->getFilename($dictionary, 'txt')];
     }
 }
 /**
  * Q&Aを解析します。
  * @param Dictionary $dictioanry
  * @param string $question
  * @param string $answer
  */
 protected function parseQuizLines(Dictionary $dictioanry, string $question, string $answer)
 {
     $line = "{$question}\n{$answer}";
     $specifics = new URLSearchParams();
     $questionFields = explode(',', $question, 5);
     $answerFields = explode(',', $answer);
     if (!$this->isNumeric($questionFields[1])) {
         throw new SyntaxException(sprintf(_('出題の種類「%s」は数値として認識できません。'), $questionFields[1]));
     } elseif (!$this->isNumeric($answerFields[1])) {
         throw new SyntaxException(sprintf(_('解答の種類「%s」は数値として認識できません。'), $answerFields[1]));
     }
     /** @var int 出題の種類。 */
     $questionType = $this->convertToInt($questionFields[1]);
     switch ($questionType) {
         case 1:
             // 音声ファイルを再生
         // 音声ファイルを再生
         case 2:
             // 画像ファイルを表示
             if (empty($questionFields[3])) {
                 throw new SyntaxException(_('ファイルが指定されていません。'));
             }
             // ファイル名
             $fieldsAsMultiDimensionalArray[$questionType === 1 ? 'audio' : 'image'][] = $questionFields[3];
             // 問題オプション
             if (isset($questionFields[4])) {
                 foreach (explode(',', $questionFields[4]) as $option) {
                     $option = explode('=', $option, 2);
                     $name = $option[0];
                     $value = $option[1] ?? '';
                     if (!$this->isNumeric($value)) {
                         throw new SyntaxException(sprintf(_('問題オプション %1$s の値「%2$s」は数値として認識できません。'), $name, $value));
                     }
                     $int = $this->convertToInt($value);
                     switch ($name) {
                         case 'start':
                         case 'media_start':
                             $specifics->set('start', $int / self::SECONDS_TO_MILISECONDS);
                             break;
                         case 'repeat':
                             $specifics->set('repeat', $int);
                             break;
                         case 'length':
                             $specifics->set('length', $int / self::SECONDS_TO_MILISECONDS);
                             break;
                         case 'speed':
                             $specifics->set('speed', $int / self::DECIMAL_TO_PERCENT);
                             break;
                         case 'zoom_start':
                             $specifics->set('magnification', $int);
                             break;
                         case 'zoom_end':
                             $specifics->set('last-magnification', $int);
                             break;
                         case 'mozaic':
                             if ($int === 1) {
                                 $specifics->set('pixelization', '');
                             } else {
                                 $specifics->delete('pixelization');
                             }
                             break;
                         case 'score':
                             $specifics->set('score', $int);
                             break;
                         case 'finalscore':
                             $specifics->set('last-score', $int);
                             break;
                     }
                 }
             }
             break;
         case 3:
             // Wikipediaクイズ
         // Wikipediaクイズ
         case 4:
             // アンサイクロペディアクイズ
             $this->logInconvertibleError("{$question}\n{$answer}");
             return;
     }
     // 問題文
     if (isset($questionFields[2])) {
         $fieldsAsMultiDimensionalArray['question'][] = $this->parseQuestionSentence($questionFields[2]);
     }
     /** @var int 解答の種類。 */
     $answerType = $this->convertToInt($answerFields[1]);
     if (in_array($answerType, [1, 2, 3])) {
         $fieldsAsMultiDimensionalArray['type'][] = 'selection';
         if ($answerType === 3) {
             $specifics->set('require-all-right', '');
         }
     } else {
         $answerType = 0;
     }
     $mode = '|';
     $answerValidator = new \esperecyan\dictionary_php\validator\AnswerValidator();
     foreach (array_slice($answerFields, 2) as $i => $field) {
         if (isset($field[0]) && $field[0] === '\\' && isset($field[1]) && $field[1] !== '\\') {
             // 解答オプション
             if ($field === '\\norandom') {
                 // 選択肢をシャッフルしない
                 if (in_array($answerType, [1, 3])) {
                     $specifics->set('no-random', '');
                 }
             } elseif ($field === '\\seikai') {
                 // 直前の選択肢を正解扱いに
                 if (in_array($answerType, [1, 3])) {
                     if (empty($fieldsAsMultiDimensionalArray['option'])) {
                         throw new SyntaxException(_('\\seikai の前には選択肢が必要です。'));
                     }
                     $fieldsAsMultiDimensionalArray['answer'][] = end($fieldsAsMultiDimensionalArray['option']);
                 }
             } elseif (preg_match('/^\\\\explain=(.+)$/u', $field, $matches) === 1) {
                 // 解説
                 $fieldsAsMultiDimensionalArray['description'][] = $this->parseQuestionSentence($matches[1]);
             } elseif ($answerType === 0 && preg_match('/^\\\\bonus=(.*)$/u', $field, $matches) === 1) {
                 // ボーナスポイント
                 if (!$this->isNumeric($matches[1])) {
                     throw new SyntaxException(sprintf(_('解答オプション \\bonus の値「%s」は数値として認識できません。'), $matches[1]));
                 }
                 if (empty($answerPattenAndBonuses['|'])) {
                     throw new SyntaxException(sprintf(_('解答オプション「%s」の前には解答本体が必要です。'), $field));
                 }
                 $bonus = $this->convertToInt($matches[1]);
                 if ($bonus !== 0) {
                     $answerPattenAndBonuses['|'][count($answerPattenAndBonuses['|']) - 1]['bonus'] = $bonus;
                 }
             }
             continue;
         }
         switch ($answerType) {
             case 0:
                 // 記述形式
                 if ($field === '[[' || $field === '||') {
                     // 正規表現
                     if (empty($answerPattenAndBonuses['|'])) {
                         throw new SyntaxException(sprintf(_('「%s」の前には解答本体が必要です。'), $field));
                     }
                     $end = count($answerPattenAndBonuses['|']) - 1;
                     $answerPattenAndBonuses['|'][$end]['regexp'] = ($field === '||' ? '.*' : '') . preg_quote($answerPattenAndBonuses['|'][$end]['body'], '/') . '.*';
                 } elseif (in_array($field, ['[', '|', ']'])) {
                     // モード変更
                     $mode = $field;
                 } elseif ($mode === '|') {
                     $answerPattenAndBonuses['|'][]['body'] = $field;
                 } else {
                     $answerPattenAndBonuses[$mode][] = $field;
                 }
                 break;
             case 1:
                 // 選択形式
             // 選択形式
             case 3:
                 // 全選択形式
                 $fieldsAsMultiDimensionalArray['option'][] = $answerValidator->isRegExp($field) ? trim($field, '/') : $field;
                 break;
             case 2:
                 // 並べ替え形式
                 if ($i % 2 === 0) {
                     $numbersAndOptions[] = [$answerValidator->isRegExp($field) ? trim($field, '/') : $field];
                 } else {
                     $number = $this->isNumeric($field) ? $this->convertToInt($field) : 0;
                     if ($number > 0) {
                         array_unshift($numbersAndOptions[count($numbersAndOptions) - 1], $number);
                     } else {
                         // 順番が0以下であれば選択肢自体を削除
                         array_pop($numbersAndOptions);
                     }
                 }
                 break;
         }
     }
     switch ($answerType) {
         case 0:
             // 記述形式
             $noRegExpAnswerExisted = false;
             foreach ($answerPattenAndBonuses['|'] as $infix) {
                 // 接頭辞の付加
                 if (isset($answerPattenAndBonuses['['])) {
                     foreach ($answerPattenAndBonuses['['] as $prefix) {
                         $tmpInfix = $infix;
                         $tmpInfix['body'] = $prefix . $tmpInfix['body'];
                         if (isset($tmpInfix['regexp'])) {
                             $tmpInfix['regexp'] = preg_quote($prefix, '/') . $tmpInfix['regexp'];
                         }
                         $answersAndBonusesWithPrefix[] = $tmpInfix;
                     }
                 } else {
                     $answersAndBonusesWithPrefix[] = $infix;
                 }
                 // 接尾辞の付加
                 if (isset($answerPattenAndBonuses[']'])) {
                     foreach ($answerPattenAndBonuses[']'] as $suffix) {
                         foreach ($answersAndBonusesWithPrefix as $answer) {
                             $answer['body'] .= $suffix;
                             if (isset($answer['regexp'])) {
                                 $answer['regexp'] .= preg_quote($prefix, '/');
                             }
                             $answersAndBonusesWithPrefixAndSuffix[] = $answer;
                         }
                     }
                 } else {
                     $answersAndBonusesWithPrefixAndSuffix = $answersAndBonusesWithPrefix;
                 }
                 unset($answersAndBonusesWithPrefix);
                 foreach ($answersAndBonusesWithPrefixAndSuffix as &$answer) {
                     if ($answerValidator->isRegExp($answer['body'])) {
                         $answer['body'] = trim($answer['body'], '/');
                         if ($answer['body'] === '') {
                             unset($answer['body']);
                         }
                     }
                     if (isset($answer['regexp']) || isset($answer['body'])) {
                         $fieldsAsMultiDimensionalArray['answer'][] = isset($answer['regexp']) ? "/{$answer['regexp']}/" : $answer['body'];
                         if (isset($answer['regexp'])) {
                             if (!isset($noRegExpAnswerAndBonus)) {
                                 $noRegExpAnswerAndBonus = ['answer' => $answer['body'], 'bonus' => isset($answer['bonus']) ? (string) $answer['bonus'] : ''];
                             }
                         } else {
                             $noRegExpAnswerExisted = true;
                         }
                         $bonuses[] = isset($answer['bonus']) ? (string) $answer['bonus'] : '';
                     }
                 }
                 unset($answersAndBonusesWithPrefixAndSuffix);
             }
             if (!$noRegExpAnswerExisted) {
                 // answerフィールドがすべて正規表現なら
                 if (isset($noRegExpAnswerAndBonus)) {
                     array_unshift($fieldsAsMultiDimensionalArray['answer'], $noRegExpAnswerAndBonus['answer']);
                     array_unshift($bonuses, $noRegExpAnswerAndBonus['bonus']);
                 } else {
                     $this->logInconvertibleError($line);
                     return;
                 }
             }
             // specificsフィールドのbonusの設定
             if (isset($bonuses)) {
                 foreach (array_reverse($bonuses, true) as $i => $bonus) {
                     if ($bonus) {
                         $lastBonusPosition = $i;
                         break;
                     }
                 }
             }
             if (isset($lastBonusPosition)) {
                 foreach (array_slice($bonuses, 0, $lastBonusPosition + 1) as $bonus) {
                     $specifics->append('bonus', $bonus);
                 }
             }
             $fieldsAsMultiDimensionalArray['text'][] = $fieldsAsMultiDimensionalArray['answer'][0];
             if (count($fieldsAsMultiDimensionalArray['answer']) === 1) {
                 unset($fieldsAsMultiDimensionalArray['answer']);
             }
             break;
         case 1:
             // 選択形式
         // 選択形式
         case 3:
             // 全選択形式
             if (empty($fieldsAsMultiDimensionalArray['answer'])) {
                 throw new SyntaxException(_('\\seikai が設定されていません。'));
             }
             $fieldsAsMultiDimensionalArray['text'][] = count($fieldsAsMultiDimensionalArray['answer']) === 1 ? $fieldsAsMultiDimensionalArray['answer'][0] : '「' . implode('」' . ($answerType === 1 ? 'か' : 'と') . '「', $fieldsAsMultiDimensionalArray['answer']) . '」';
             break;
         case 2:
             // 並べ替え形式
             if (isset($numbersAndOptions)) {
                 if (count(end($numbersAndOptions)) === 1) {
                     // 順番が指定されていない選択肢を削除
                     array_pop($numbersAndOptions);
                 }
                 sort($numbersAndOptions);
                 $fieldsAsMultiDimensionalArray['option'] = array_column($numbersAndOptions, 1);
                 $fieldsAsMultiDimensionalArray['text'][] = implode(' → ', $fieldsAsMultiDimensionalArray['option']);
             }
             break;
     }
     $encoded = (string) $specifics;
     if ($encoded !== '') {
         $fieldsAsMultiDimensionalArray['specifics'][] = $encoded;
     }
     try {
         $dictioanry->addWord($fieldsAsMultiDimensionalArray);
         if ($answerType === 0) {
             // 記述形式
             $words = $dictioanry->getWords();
             $word = $words[count($words) - 1];
             if (isset($word['answer'])) {
                 foreach ($word['answer'] as $answer) {
                     $this->wholeText .= $answerValidator->isRegExp($answer) ? preg_replace('#^/|\\.\\*|/$#u', '', $answer) : $answer;
                 }
             } else {
                 $this->wholeText .= $word['text'][0];
             }
         }
     } catch (SyntaxException $e) {
         $this->logInconvertibleError($line, $e);
     }
 }