Skip to content

Commit

Permalink
Creation of the Pandoc converter & checking for installed packages no…
Browse files Browse the repository at this point in the history
…w only happens once, and throws an exception in case requirements aren't met
  • Loading branch information
extracts committed Aug 17, 2023
1 parent 5490164 commit 82d8327
Showing 1 changed file with 30 additions and 28 deletions.
58 changes: 30 additions & 28 deletions src/Processor/LatexToUnicodeProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Exception;
use Pandoc\Pandoc;
use RenanBr\BibTexParser\Exception\ProcessorException;
use RuntimeException;

/**
* Translates LaTeX texts to unicode.
Expand All @@ -23,8 +24,8 @@ class LatexToUnicodeProcessor
{
use TagCoverageTrait;

/** @var Pandoc|null */
private $pandoc;
/** @var (callable(string): string)|null */
private $converter;

/**
* @return array
Expand Down Expand Up @@ -53,49 +54,50 @@ public function __invoke(array $entry)
}

/**
* Returns true if the ueberdosis/pandoc package is installed, otherwise returns false.
* @param mixed $text
*
* @return bool
* @return string
*/
private function isUeberdosisPandocAvailable()
private function decode($text)
{
return InstalledVersions::isInstalled('ueberdosis/pandoc');
try {
return $this->getConverter()($text);
} catch (Exception $exception) {
throw new ProcessorException(sprintf('Error while processing LaTeX to Unicode: %s', $exception->getMessage()), 0, $exception);
}
}

/**
* @param mixed $text
*
* @return string
* @return (callable(string): string)
*/
private function decode($text)
private function getConverter()
{
try {
if (!$this->pandoc) {
$this->pandoc = new Pandoc();
}
if ($this->converter) {
return $this->converter;
}

if ($this->isUeberdosisPandocAvailable()) {
// use ueberdosis/pandoc
$output = $this->pandoc->input($text)->execute([
if (InstalledVersions::isInstalled('ueberdosis/pandoc')) {
$pandoc = new Pandoc();

return $this->converter = function ($text) use ($pandoc) {
return substr($pandoc->input($text)->execute([
'--from', 'latex',
'--to', 'plain',
'--wrap', 'none',
]);
]), 0, -1);
};
} else if (InstalledVersions::isInstalled('ryakad/pandoc-php')) {
$pandoc = new Pandoc();

// remove newline character added by Pandoc conversion
$output = substr($output, 0, -1);
} else {
// use ryakad/pandoc-php
$output = $this->pandoc->runWith($text, [
return $this->converter = function ($text) use ($pandoc) {
return $pandoc->runWith($text, [
'from' => 'latex',
'to' => 'plain',
'wrap' => 'none',
]);
}

return $output;
} catch (Exception $exception) {
throw new ProcessorException(sprintf('Error while processing LaTeX to Unicode: %s', $exception->getMessage()), 0, $exception);
};
}

throw new RuntimeException('Pandoc wrapper not installed. Try running "composer require ueberdosis/pandoc"');
}
}

0 comments on commit 82d8327

Please sign in to comment.