You are here

public function BibtexEncoder::decode in Bibliography & Citation 8

Same name and namespace in other branches
  1. 2.0.x modules/bibcite_bibtex/src/Encoder/BibtexEncoder.php \Drupal\bibcite_bibtex\Encoder\BibtexEncoder::decode()

File

modules/bibcite_bibtex/src/Encoder/BibtexEncoder.php, line 32

Class

BibtexEncoder
BibTeX format encoder.

Namespace

Drupal\bibcite_bibtex\Encoder

Code

public function decode($data, $format, array $context = []) {
  $data = $this
    ->lineEndingsReplace($data);

  /*
   * Handle type as case-insensitive.
   * Tags should be handled as case-insensitive as well, but it's done by BibtexParser library.
   * @see https://www.drupal.org/node/2890060
   */
  $data = preg_replace_callback('/^@(\\w+){/m', function ($word) {
    return '@' . strtolower($word[1]) . '{';
  }, $data);

  /*
   * Ignore "type" tag inside records.
   * Type in BibTeX must go before content.
   * @see https://en.wikipedia.org/wiki/BibTeX
   * @see https://www.drupal.org/node/2882855
   */
  $data = preg_replace('/^ *type *= *{.*}.*$/m', '', $data);
  $parsed = BibtexParser::parse_string($data);
  foreach ($parsed as $i => $entry) {
    unset($entry['raw']);
    unset($entry['lines']);
    $parsed[$i] = $entry;

    // BibtexParser library treat "editor" field as regular string instead
    // of array as it does with "author" field.
    // Hotfix "editor" field so it behaves the same as "author" field.
    // @todo Remove this hotfix once used library is fixed or different library is used.
    if (isset($parsed[$i]['editor'])) {
      $parsed[$i]['editor'] = explode(' and ', $parsed[$i]['editor']);
    }
  }
  $keys = array_keys($parsed);
  if (count($keys) === 0 || $keys[0] === -1) {
    $format_definition = \Drupal::service('plugin.manager.bibcite_format')
      ->getDefinition($format);
    $format_label = $format_definition['label'];
    throw new UnexpectedValueException("Incorrect '{$format_label}' format or empty set.");
  }
  $this
    ->processEntries($parsed);
  return $parsed;
}