diff --git a/src/Command/LatexTestCommand.php b/src/Command/LatexTestCommand.php index 7055ec9..9527ded 100644 --- a/src/Command/LatexTestCommand.php +++ b/src/Command/LatexTestCommand.php @@ -22,7 +22,7 @@ public function __construct(private readonly LatexGeneratorInterface $latexGener parent::__construct(); } - protected function configure() { + protected function configure(): void { $this ->setName('bobv:latex:test') ->setDescription('Generate a test LaTeX file (+ pdf)') @@ -56,6 +56,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->writeln($generatedLocation); - return 0; // Success + return Command::SUCCESS; } } diff --git a/src/DependencyInjection/BobvLatexExtension.php b/src/DependencyInjection/BobvLatexExtension.php index a660fea..dc1ba5c 100644 --- a/src/DependencyInjection/BobvLatexExtension.php +++ b/src/DependencyInjection/BobvLatexExtension.php @@ -9,17 +9,9 @@ use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\String\UnicodeString; -/** - * This is the class that loads and manages your bundle configuration - * - * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} - */ class BobvLatexExtension extends Extension { - /** - * {@inheritDoc} - */ - public function load(array $configs, ContainerBuilder $container) { + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index b91b6ae..2457719 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -5,17 +5,8 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; -/** - * This is the class that validates and merges configuration from your app/config files - * - * To learn more see - * {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} - */ class Configuration implements ConfigurationInterface { - /** - * {@inheritDoc} - */ public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('bobv_latex'); diff --git a/src/Exception/BibliographyGenerationException.php b/src/Exception/BibliographyGenerationException.php index cb1d30f..83b56d0 100644 --- a/src/Exception/BibliographyGenerationException.php +++ b/src/Exception/BibliographyGenerationException.php @@ -6,14 +6,8 @@ class BibliographyGenerationException extends LatexException { - - /** - * @param string $texLocation - * @param int $exitCode - * @param string|null $exitCodeText - */ - public function __construct($texLocation, $exitCode, $exitCodeText = NULL) { - if ($exitCodeText !== NULL) { + public function __construct(string $texLocation, int $exitCode, ?string $exitCodeText = null) { + if ($exitCodeText !== null) { $exitCodeText = sprintf(' (%s)', $exitCodeText); } else { $exitCodeText = ''; diff --git a/src/Exception/ImageNotFoundException.php b/src/Exception/ImageNotFoundException.php index bb072ab..4a58315 100644 --- a/src/Exception/ImageNotFoundException.php +++ b/src/Exception/ImageNotFoundException.php @@ -3,24 +3,16 @@ namespace Bobv\LatexBundle\Exception; /** - * Class ImageNotFoundException * Simple \Exception extend for better error origin check */ class ImageNotFoundException extends \Exception { - private $imageLocation; - - public function __construct($imageLocation) + public function __construct(private readonly string $imageLocation) { - $this->imageLocation = $imageLocation; - parent::__construct("The image used is not found. Did you provide the complete path? (provided path = $imageLocation)"); } - /** - * @return mixed - */ - public function getImageLocation() + public function getImageLocation(): string { return $this->imageLocation; } diff --git a/src/Exception/LatexException.php b/src/Exception/LatexException.php index 312810c..b725cc1 100644 --- a/src/Exception/LatexException.php +++ b/src/Exception/LatexException.php @@ -3,9 +3,8 @@ namespace Bobv\LatexBundle\Exception; /** - * Class LatexException * Simple \Exception extend for better error origin check */ -class LatexException extends \Exception{ - +class LatexException extends \Exception +{ } diff --git a/src/Exception/LatexNotImplementedException.php b/src/Exception/LatexNotImplementedException.php index 2018837..2de5679 100644 --- a/src/Exception/LatexNotImplementedException.php +++ b/src/Exception/LatexNotImplementedException.php @@ -3,9 +3,8 @@ namespace Bobv\LatexBundle\Exception; /** - * Class LatexNotImplementedException * Simple \Exception extend for better error origin check */ -class LatexNotImplementedException extends LatexException{ - +class LatexNotImplementedException extends LatexException +{ } diff --git a/src/Exception/LatexParseException.php b/src/Exception/LatexParseException.php index 60dd33b..b5da14d 100644 --- a/src/Exception/LatexParseException.php +++ b/src/Exception/LatexParseException.php @@ -3,32 +3,24 @@ namespace Bobv\LatexBundle\Exception; /** - * Class LatexException * Simple \Exception extend for better error origin check */ class LatexParseException extends LatexException { - - const LOG_GET_LINES = 4; const LOG_MAX_LINES = 10; const TEX_GET_LINES = 8; const TEX_MAX_LINES = 20; - protected $filteredTexSource = array(); + protected array $filteredTexSource = []; - protected $filteredLogSource = array(); + protected array $filteredLogSource = []; - /** - * @param string $texLocation - * @param int $exitCode - * @param array|NULL $pdfLatexOutput - */ - public function __construct($texLocation, $exitCode, array $pdfLatexOutput = NULL, $exitCodeText = NULL) + public function __construct(string $texLocation, int $exitCode, ?array $pdfLatexOutput = null, ?string $exitCodeText = null) { - if($exitCodeText !== NULL){ + if ($exitCodeText !== null) { $exitCodeText = sprintf(' (%s)', $exitCodeText); - }else{ + } else { $exitCodeText = ''; } @@ -41,10 +33,8 @@ public function __construct($texLocation, $exitCode, array $pdfLatexOutput = NUL /** * Return an extended error message together with the extracted errors - * - * @return string */ - public function getExtendedMessage() + public function getExtendedMessage(): string { $message = $this->getMessage(); @@ -57,28 +47,24 @@ public function getExtendedMessage() } /** - * Try to find usefull information on the error that has occurred - * - * @param array $errorOutput - * @param string $texLocation - * - * @return array Contains the filtered output which should only contain information about the errors + * Try to find useful information on the error that has occurred + * This is stored in the object properties $filteredLogSource and $filteredTexSource */ - protected function findErrors(array $errorOutput, $texLocation = NULL) + protected function findErrors(array $errorOutput, ?string $texLocation = NULL): void { $refWarning = strtolower('LaTeX Warning: Reference'); - $filteredErrors = array(); - $filteredErrors[] = "---"; + $filteredErrors = []; + $filteredErrors[] = '---'; array_walk($errorOutput, function ($value, $key) use (&$errorOutput, &$texLocation, &$filteredErrors, $refWarning) { // Find lines with an error if (preg_match_all('/error|missing|not found|undefined|too many|runaway|\$|you can\'t use|invalid/ui', $value) > 0) { - if (substr(strtolower($errorOutput[$key]), 0, strlen($refWarning)) !== $refWarning) { + if (!str_starts_with(strtolower($errorOutput[$key]), $refWarning)) { // Get the lines surrounding the error, but do not include empty lines // Get lines before the error - $temp = array(); + $temp = []; for ($count = 0, $i = 0; $count < self::LOG_GET_LINES && $i < self::LOG_MAX_LINES; $i++) { if (isset($errorOutput[$key - $i])) { $value = trim(preg_replace('/\s+/', ' ', $errorOutput[$key - $i])); @@ -105,7 +91,7 @@ protected function findErrors(array $errorOutput, $texLocation = NULL) } } - $filteredErrors[] = "---"; + $filteredErrors[] = '---'; } } @@ -116,16 +102,16 @@ protected function findErrors(array $errorOutput, $texLocation = NULL) // Try to find matching tex lines // Check if a line number can be found in the errors - $this->filteredTexSource[] = "---"; + $this->filteredTexSource[] = '---'; if ($texLocation !== NULL) { - $lineNumber = array(); + $lineNumber = []; $texFile = new \SplFileObject($texLocation); foreach ($this->filteredLogSource as $logLine) { preg_match('/l\.(\d+)/ui', $logLine, $lineNumber); if (count($lineNumber) == 2) { // Get lines before the linenumber - $temp = array(); + $temp = []; for ($count = 0, $i = 0; $count < self::TEX_GET_LINES && $i < self::TEX_MAX_LINES; $i++) { $texFile->seek($lineNumber[1] - $i); if ($texFile->valid()) { @@ -138,7 +124,7 @@ protected function findErrors(array $errorOutput, $texLocation = NULL) break; } } - $this->filteredTexSource = array_merge($this->filteredTexSource, array($lineNumber[0]), array_reverse($temp)); + $this->filteredTexSource = array_merge($this->filteredTexSource, [$lineNumber[0]], array_reverse($temp)); // Get lines after the line number for ($count = 0, $i = 1; $count < self::TEX_GET_LINES && $i < self::TEX_MAX_LINES; $i++) { @@ -153,29 +139,19 @@ protected function findErrors(array $errorOutput, $texLocation = NULL) break; } } - - $this->filteredTexSource[] = "---"; - + $this->filteredTexSource[] = '---'; } } } } - /** - * @return string - */ - public function getFilteredTexSource() + public function getFilteredTexSource(): string { return implode("\n", $this->filteredTexSource); } - /** - * @return string - */ - public function getFilteredLogSource() + public function getFilteredLogSource(): string { return implode("\n", $this->filteredLogSource); } - - } diff --git a/src/Form/Type/LatexType.php b/src/Form/Type/LatexType.php index 105b214..a77e45b 100644 --- a/src/Form/Type/LatexType.php +++ b/src/Form/Type/LatexType.php @@ -8,7 +8,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver; /** - * Class LatexType * You will want to use this type when using the html->latex conversion * * @author BobV @@ -18,42 +17,40 @@ class LatexType extends AbstractType /** * Returns the default config used so you can use it as base for your own config - * - * @return array */ - public static function getDefaultConfig() + public static function getDefaultConfig(): array { - return array( - 'config' => array( + return [ + 'config' => [ 'entities' => false, 'basicEntities' => false, 'entities_greek' => false, 'entities_latin' => false, - 'toolbar' => array( - array( + 'toolbar' => [ + [ 'name' => 'basicstyles', - 'groups' => array('basicstyles', 'cleanup'), - 'items' => array('Bold', 'Italic', 'Underline', 'Subscript', 'Superscript', '-', 'RemoveFormat'), - ), - array( + 'groups' => ['basicstyles', 'cleanup'], + 'items' => ['Bold', 'Italic', 'Underline', 'Subscript', 'Superscript', '-', 'RemoveFormat'], + ], + [ 'name' => 'paragraph', - 'groups' => array('list', 'indent', 'blocks', 'align'), - 'items' => array('NumberedList', 'BulletedList' + 'groups' => ['list', 'indent', 'blocks', 'align'], + 'items' => ['NumberedList', 'BulletedList' /** * @todo Add support for the floats * , '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' */ - ), - ), - array( + ], + ], + [ 'name' => 'links', - 'items' => array('Link', 'Unlink'), - ), - array( + 'items' => ['Link', 'Unlink'], + ], + [ 'name' => 'clipboard', - 'groups' => array('clipboard', 'undo'), - 'items' => array('Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'), - ), + 'groups' => ['clipboard', 'undo'], + 'items' => ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'], + ], /** * @todo: add support for tables/special chars * array( @@ -61,50 +58,40 @@ public static function getDefaultConfig() * 'items' => array('Table', 'SpecialChar'), * ), */ - array( + [ 'name' => 'document', - 'groups' => array('mode', 'document', 'doctools'), - 'items' => array('Source'), - ), - array( + 'groups' => ['mode', 'document', 'doctools'], + 'items' => ['Source'], + ], + [ 'name' => 'tools', - 'items' => array('Maximize'), - ), - ), + 'items' => ['Maximize'], + ], + ], 'extraPlugins' => '', 'removeDialogTabs' => 'link:upload;image:Upload;image:advanced;link:advanced', - ) - ); + ] + ]; } - /** - * {@inheritdoc} - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { - if (!is_array($view->vars['attr'])) $view->vars['attr'] = array(); - $view->vars['attr']['data-bobv-latex'] = NULL; + if (!is_array($view->vars['attr'])) { + $view->vars['attr'] = []; + } + $view->vars['attr']['data-bobv-latex'] = null; } - /** - * {@inheritdoc} - */ public function getName(): string { return $this->getBlockPrefix(); } - /** - * {@inheritdoc} - */ public function getBlockPrefix() : string { return 'bobv_latex'; } - /** - * {@inheritdoc} - */ public function getParent(): ?string { $ivory_form_class = 'Ivory\CKEditorBundle\Form\Type\CKEditorType'; @@ -114,10 +101,7 @@ public function getParent(): ?string return method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix') ? $form_class : 'ckeditor'; } - /** - * {@inheritdoc} - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults(self::getDefaultConfig()); } diff --git a/src/Generator/LatexGenerator.php b/src/Generator/LatexGenerator.php index 8ce4bdc..7b3d0f9 100644 --- a/src/Generator/LatexGenerator.php +++ b/src/Generator/LatexGenerator.php @@ -8,6 +8,7 @@ use Bobv\LatexBundle\Exception\LatexParseException; use Bobv\LatexBundle\Latex\LatexBaseInterface; use DateTime; +use DateTimeInterface; use Exception; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; @@ -21,75 +22,37 @@ use Twig\Error\RuntimeError; use Twig\Error\SyntaxError; -/** - * Class LatexGenerator - */ class LatexGenerator implements LatexGeneratorInterface { - - /** @var string */ - protected $cacheDir; - /** @var string */ - protected $env; - /** @var Filesystem */ - protected $filesystem; - /** @var bool */ - protected $forceRegenerate; - /** @var LatexBaseInterface */ - protected $latex; - /** @var DateTime */ - protected $maxAge; - /** @var string */ - protected $pdfLatexBinaryLocation; - /** @var string */ - protected $bibliographyBinaryLocation; - /** @var string */ - protected $outputDir; - /** @var int|float|null */ - protected $timeout; - /** @var Environment */ - protected $twig; - - /** - * @param string $cacheDir - * @param string $env - * @param Environment $twig - * @param DateTime $maxAge - * @param string $pdfLatexBinaryLocation - * @param string $bibliographyBinaryLocation - */ - public function __construct($cacheDir, $env, $twig, $maxAge, $pdfLatexBinaryLocation, $bibliographyBinaryLocation) { - $this->cacheDir = $cacheDir; - $this->env = $env; - $this->twig = $twig; + protected Filesystem $filesystem; + protected bool $forceRegenerate = false; + protected ?LatexBaseInterface $latex = null; + protected ?string $outputDir = null; + protected int|float|null $timeout = 60; // Default timeout from the Symfony Process component + protected DateTimeInterface $maxAge; + + public function __construct( + protected string $cacheDir, + protected readonly string $env, + protected readonly Environment $twig, + string $maxAge, + protected readonly string $pdfLatexBinaryLocation, + protected readonly string $bibliographyBinaryLocation) { $this->filesystem = new Filesystem(); $this->maxAge = new DateTime(); $this->maxAge->modify($maxAge); - - $this->pdfLatexBinaryLocation = $pdfLatexBinaryLocation; - $this->bibliographyBinaryLocation = $bibliographyBinaryLocation; - - $this->forceRegenerate = false; - - // Default timeout from the Symfony Process component - $this->timeout = 60; } /** * Generate a response containing a PDF document * - * @param LatexBaseInterface $latex - * @param bool $download - * - * @return BinaryFileResponse - * * @throws ImageNotFoundException * @throws LatexException * @throws LoaderError * @throws RuntimeError * @throws SyntaxError */ - public function createPdfResponse(LatexBaseInterface $latex, bool $download = true) { + public function createPdfResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse { $pdfLocation = $this->generate($latex); $response = new BinaryFileResponse($pdfLocation); @@ -103,17 +66,13 @@ public function createPdfResponse(LatexBaseInterface $latex, bool $download = tr /** * Generate a response containing a generated .tex file * - * @param LatexBaseInterface $latex - * @param bool $download - * - * @return BinaryFileResponse * @throws ImageNotFoundException * @throws LatexException * @throws LoaderError * @throws RuntimeError * @throws SyntaxError */ - public function createTexResponse(LatexBaseInterface $latex, bool $download = true) { + public function createTexResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse { $texLocation = $this->generateLatex($latex); $response = new BinaryFileResponse($texLocation); @@ -127,8 +86,6 @@ public function createTexResponse(LatexBaseInterface $latex, bool $download = tr /** * Compile a LaTeX object into the wanted PDF file * - * @param LatexBaseInterface $latex - * * @return string Location of the PDF document * * @throws ImageNotFoundException @@ -137,7 +94,7 @@ public function createTexResponse(LatexBaseInterface $latex, bool $download = tr * @throws RuntimeError * @throws SyntaxError */ - public function generate(LatexBaseInterface $latex) { + public function generate(LatexBaseInterface $latex): string { $this->latex = $latex; $texLocation = $this->generateLatex(); @@ -147,8 +104,6 @@ public function generate(LatexBaseInterface $latex) { /** * Generates a latex file for the given LaTeX object * - * @param LatexBaseInterface $latex - * * @return string Location of the generated LaTeX file * * @throws ImageNotFoundException @@ -157,7 +112,7 @@ public function generate(LatexBaseInterface $latex) { * @throws RuntimeError * @throws SyntaxError */ - public function generateLatex(LatexBaseInterface $latex = NULL) { + public function generateLatex(LatexBaseInterface $latex = NULL): string { if ($this->latex === NULL && $latex === NULL) { throw new LatexException("No latex file given"); @@ -175,7 +130,7 @@ public function generateLatex(LatexBaseInterface $latex = NULL) { // Check if there are undefined images $matches = array(); - preg_match_all('/\\\\includegraphics(\[.+\])?\{([^}]+)\}/u', $texData, $matches); + preg_match_all('/\\\\includegraphics(\[.+])?\{([^}]+)}/u', $texData, $matches); foreach ($matches[2] as $imageLocation) { if (!$this->filesystem->exists($imageLocation)) { throw new ImageNotFoundException($imageLocation); @@ -217,7 +172,7 @@ public function generateLatex(LatexBaseInterface $latex = NULL) { * @throws IOException * @throws LatexException */ - public function generatePdf($texLocation, array $compileOptions = array()) { + public function generatePdf(string $texLocation, array $compileOptions = []): string { // Check if the compiled tex file exists if (!$this->filesystem->exists($texLocation)) { @@ -242,34 +197,19 @@ public function generatePdf($texLocation, array $compileOptions = array()) { } - /** - * @param $cacheDir - * - * @return $this - */ - public function setCacheDir($cacheDir) { + public function setCacheDir(string $cacheDir): self { $this->cacheDir = $cacheDir; return $this; } - /** - * @param boolean $forceRegenerate - * - * @return LatexGenerator - */ - public function setForceRegenerate($forceRegenerate) { + public function setForceRegenerate(bool $forceRegenerate): self { $this->forceRegenerate = $forceRegenerate; return $this; } - /** - * @param DateTime $maxAge - * - * @return LatexGenerator - */ - public function setMaxAge($maxAge) { + public function setMaxAge(DateTimeInterface $maxAge): self { $this->maxAge = $maxAge; return $this; @@ -280,10 +220,8 @@ public function setMaxAge($maxAge) { * To disable the timeout, set this value to null. * * @param int|float|null $timeout The timeout in seconds - * - * @return LatexGenerator */ - public function setTimeout($timeout) { + public function setTimeout(int|float|null $timeout): self { $this->timeout = $timeout; return $this; @@ -294,7 +232,7 @@ public function setTimeout($timeout) { * * @throws IOException */ - protected function checkFilesystem() { + protected function checkFilesystem(): void { // Check if the cache dir exists if (!$this->filesystem->exists($this->getCacheBasePath())) { try { @@ -312,10 +250,9 @@ protected function checkFilesystem() { * @param string $texLocation Location of the .tex file * @param array $compileOptions Optional compile options for pdflatex * - * @return string * @throws Exception */ - protected function compilePdf($texLocation, array $compileOptions = array()) { + protected function compilePdf(string $texLocation, array $compileOptions = []): string { $pdfLocation = explode('.tex', $texLocation)[0] . '.pdf'; // Do not regenerate unless cache is off (dev mode or force regenerate or passed maxAge) @@ -399,23 +336,17 @@ protected function compilePdf($texLocation, array $compileOptions = array()) { return $pdfLocation; } - /** - * Returns the cache path - */ - protected function getCacheBasePath() { + protected function getCacheBasePath(): string { return $this->cacheDir . '/BobvLatex/'; } /** * Write the file to the cache directory * - * @param string $texData - * @param $fileName - * * @return string The location of the saved .tex file * @throws IOException */ - protected function writeTexFile($texData, $fileName) { + protected function writeTexFile(string $texData, string $fileName): string { $this->checkFilesystem(); $this->outputDir = $this->getCacheBasePath() . hash('ripemd160', $texData) . '/'; $texLocation = $this->outputDir . $fileName . '.tex'; @@ -443,28 +374,13 @@ protected function writeTexFile($texData, $fileName) { /** * Check if the line contains a reference error - * - * @param $value - * - * @return bool */ - private function findReferenceError($value) { + private function findReferenceError(string $value): bool { return preg_match_all('/reference|change/ui', $value) > 0; } - /** - * Run a latex process - * - * @param string $commandLine - * - * @return Process - */ - private function runProcess(string $commandLine) { - if (method_exists(Process::class, 'fromShellCommandline')) { - $process = Process::fromShellCommandline($commandLine); - } else { - $process = new Process($commandLine); - } + private function runProcess(string $commandLine): Process { + $process = Process::fromShellCommandline($commandLine); $process->setTimeout($this->timeout); $process->run(); diff --git a/src/Generator/LatexGeneratorInterface.php b/src/Generator/LatexGeneratorInterface.php index a0f28ab..eda1114 100644 --- a/src/Generator/LatexGeneratorInterface.php +++ b/src/Generator/LatexGeneratorInterface.php @@ -3,6 +3,7 @@ namespace Bobv\LatexBundle\Generator; use Bobv\LatexBundle\Latex\LatexBaseInterface; +use DateTimeInterface; use Symfony\Component\HttpFoundation\BinaryFileResponse; interface LatexGeneratorInterface @@ -11,42 +12,32 @@ interface LatexGeneratorInterface /** * Generate a response containing a PDF document * - * @param LatexBaseInterface $latex * @param bool $download If set to false, the attachment value will be omitted from the * Content-Disposition field. Defaults to true. - * - * @return BinaryFileResponse */ - public function createPdfResponse(LatexBaseInterface $latex, bool $download = true); + public function createPdfResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse; /** * Generate a response containing a generated .tex file * - * @param LatexBaseInterface $latex * @param bool $download If set to false, the attachment value will be omitted from the * Content-Disposition field. Defaults to true. - * - * @return BinaryFileResponse */ - public function createTexResponse(LatexBaseInterface $latex, bool $download = true); + public function createTexResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse; /** * Compile a LaTeX object into the wanted PDF file * - * @param \Bobv\LatexBundle\Latex\LatexBaseInterface $latex - * * @return string Location of the PDF document */ - public function generate(LatexBaseInterface $latex); + public function generate(LatexBaseInterface $latex): string; /** * Generates a latex file for the given LaTeX object * - * @param \Bobv\LatexBundle\Latex\LatexBaseInterface $latex - * * @return string Location of the generated LaTeX file */ - public function generateLatex(LatexBaseInterface $latex = NULL); + public function generateLatex(LatexBaseInterface $latex = null): string; /** * Generates a PDF from a given LaTeX location @@ -56,36 +47,19 @@ public function generateLatex(LatexBaseInterface $latex = NULL); * * @return string Location of the generated PDF file */ - public function generatePdf($texLocation, array $compileOptions = array()); + public function generatePdf(string $texLocation, array $compileOptions = []): string; - /** - * @param $cacheDir - * - * @return LatexGeneratorInterface - */ - public function setCacheDir($cacheDir); + public function setCacheDir(string $cacheDir): self; - /** - * @param boolean $forceRegenerate - * - * @return LatexGeneratorInterface - */ - public function setForceRegenerate($forceRegenerate); + public function setForceRegenerate(bool $forceRegenerate): self; - /** - * @param \DateTime $maxAge - * - * @return LatexGeneratorInterface - */ - public function setMaxAge($maxAge); + public function setMaxAge(DateTimeInterface $maxAge): self; /** * Sets the process timeout (max. runtime). * To disable the timeout, set this value to null. * * @param int|float|null $timeout The timeout in seconds - * - * @return LatexGeneratorInterface */ - public function setTimeout($timeout); + public function setTimeout(int|float|null $timeout): self; } diff --git a/src/Generator/LockedLatexGenerator.php b/src/Generator/LockedLatexGenerator.php index ec5384e..6098aa1 100644 --- a/src/Generator/LockedLatexGenerator.php +++ b/src/Generator/LockedLatexGenerator.php @@ -4,41 +4,27 @@ use Bobv\LatexBundle\Exception\LatexNotLockedException; use Bobv\LatexBundle\Latex\LatexBaseInterface; +use DateTimeInterface; use LogicException; +use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\Lock\Lock; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\FlockStore; /** - * Class LockedLatexGenerator - * * Lock LaTeX pdf generation to prevent the same files being rendered at the same time. */ class LockedLatexGenerator implements LatexGeneratorInterface, LockedLatexGeneratorInterface { - /** - * @var LatexGeneratorInterface - */ - private $generator; - /** - * @var LockFactory - */ - private $lockFactory; - /** - * @var Lock|null - */ - private $lock; - /** - * @var int - */ - private $timeout; + private LockFactory $lockFactory; // Set in constructor + private ?Lock $lock = null; + private float|int|null $timeout; // Set in constructor - public function __construct(LatexGeneratorInterface $generator) { + public function __construct(private readonly LatexGeneratorInterface $generator) { if (!class_exists(LockFactory::class)) { throw new LogicException('In order to use the LockedLatexGenerator, try running "composer require symfony/lock".'); } - $this->generator = $generator; $this->setTimeout(60); $this->lockFactory = new LockFactory(new FlockStore()); } @@ -65,82 +51,55 @@ public function releaseLock(): LatexGeneratorInterface { return $this; } - /** - * @inheritDoc - */ - public function createPdfResponse(LatexBaseInterface $latex, bool $download = true) { + public function createPdfResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse { $this->ensureLock(); return $this->generator->createPdfResponse($latex, $download); } - /** - * @inheritDoc - */ - public function createTexResponse(LatexBaseInterface $latex, bool $download = true) { + public function createTexResponse(LatexBaseInterface $latex, bool $download = true): BinaryFileResponse { $this->ensureLock(); return $this->generator->createTexResponse($latex, $download); } - /** - * @inheritDoc - */ - public function generate(LatexBaseInterface $latex) { + public function generate(LatexBaseInterface $latex): string { $this->ensureLock(); return $this->generator->generate($latex); } - /** - * @inheritDoc - */ - public function generateLatex(LatexBaseInterface $latex = NULL) { + public function generateLatex(LatexBaseInterface $latex = null): string { $this->ensureLock(); return $this->generator->generateLatex($latex); } - /** - * @inheritDoc - */ - public function generatePdf($texLocation, array $compileOptions = array()) { + public function generatePdf($texLocation, array $compileOptions = []): string { $this->ensureLock(); return $this->generator->generatePdf($texLocation, $compileOptions); } - /** - * @inheritDoc - */ - public function setCacheDir($cacheDir) { + public function setCacheDir(string $cacheDir): self { $this->generator->setCacheDir($cacheDir); return $this; } - /** - * @inheritDoc - */ - public function setForceRegenerate($forceRegenerate) { + public function setForceRegenerate(bool $forceRegenerate): self { $this->generator->setForceRegenerate($forceRegenerate); return $this; } - /** - * @inheritDoc - */ - public function setMaxAge($maxAge) { + public function setMaxAge(DateTimeInterface $maxAge): self { $this->generator->setMaxAge($maxAge); return $this; } - /** - * @inheritDoc - */ - public function setTimeout($timeout) { + public function setTimeout(float|int|null $timeout): self { $this->generator->setTimeout($timeout); // Save timeout for lock, include some trivial overhead margin, and refresh when required @@ -155,7 +114,7 @@ public function setTimeout($timeout) { /** * Verify the callee has already exclusive access */ - private function ensureLock() { + private function ensureLock(): void { if (!$this->lock->isAcquired()) { throw new LatexNotLockedException(); } diff --git a/src/Generator/LockedLatexGeneratorInterface.php b/src/Generator/LockedLatexGeneratorInterface.php index 5a21047..f6077d7 100644 --- a/src/Generator/LockedLatexGeneratorInterface.php +++ b/src/Generator/LockedLatexGeneratorInterface.php @@ -3,8 +3,6 @@ namespace Bobv\LatexBundle\Generator; /** - * Class LockedLatexGenerator - * * Lock LaTeX pdf generation to prevent the same files being rendered at the same time. */ interface LockedLatexGeneratorInterface extends LatexGeneratorInterface diff --git a/src/Helper/Parser.php b/src/Helper/Parser.php index 8f4334d..30b94d8 100644 --- a/src/Helper/Parser.php +++ b/src/Helper/Parser.php @@ -3,25 +3,17 @@ namespace Bobv\LatexBundle\Helper; /** - * Class Parser * @author BobV */ class Parser { - - /** - * @var array - */ - private $htmlCodes; + private array $htmlCodes; // Set in constructor /** * @var string[] */ - private $greekMap; + private array $greekMap; - /** - * Parser constructor. - */ public function __construct() { $this->htmlCodes = array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)); @@ -75,15 +67,13 @@ public function __construct() { /** * Parse the text and replace known special latex characters correctly * - * @param string $text The string that needs to be parsed - * @param boolean $checkTable If set, tables should be detected automatically (default true) - * @param boolean $removeLatex If set, all LaTeX commands will be removed (default false) - * @param boolean $parseNewLines If set, newline characters will be replaced by LaTeX entities (default false) - * @param bool $removeGreek If set, any greek character will be replace by their LaTeX math equivalent (default false) - * - * @return mixed + * @param string|null $text The string that needs to be parsed + * @param boolean $checkTable If set, tables should be detected automatically (default true) + * @param boolean $removeLatex If set, all LaTeX commands will be removed (default false) + * @param boolean $parseNewLines If set, newline characters will be replaced by LaTeX entities (default false) + * @param bool $removeGreek If set, any greek character will be replaced by their LaTeX math equivalent (default false) */ - public function parseText($text, $checkTable = true, $removeLatex = false, $parseNewLines = false, $removeGreek = false) { + public function parseText(?string $text, bool $checkTable = true, bool $removeLatex = false, bool $parseNewLines = false, bool $removeGreek = false): string { // Try to replace HTML entities preg_match_all('/&[a-zA-Z]+;/iu', $text, $matches); @@ -236,12 +226,8 @@ public function parseText($text, $checkTable = true, $removeLatex = false, $pars /** * Parse the html input and create latex code of it - * - * @param $text - * - * @return mixed */ - public static function parseHtml($text) { + public static function parseHtml(?string $text): ?string { // Replace NO-BREAK-SPACE with normal space $text = str_replace("\xc2\xa0", ' ', $text); @@ -272,25 +258,20 @@ public static function parseHtml($text) { $text = $DOM->saveHTML(); // Replace junk from URL to get it readable - $text = preg_replace("/(mailto:|https?:\/\/)?(([\da-z\.-]+)(\.|@)([a-z\.]{2,6})([\/\w\.-]*[\/\w-])*\/?)/smui", '$2', $text); + $text = preg_replace("/(mailto:|https?:\/\/)?(([\da-z.-]+)([.@])([a-z.]{2,6})([\/\w.-]*[\/\w-])*\/?)/smui", '$2', $text); return strip_tags($text); } /** * Encapsulate the content of all given tags in the given document with the replacement - * - * @param \DOMDocument $document - * @param string $tag - * @param string $replacementStart - * @param string $replacementEnd */ - private static function updateNode(\DOMDocument &$document, $tag, $replacementStart, $replacementEnd = '}') { + private static function updateNode(\DOMDocument &$document, string $tag, string $replacementStart, string $replacementEnd = '}'): void { $elements = $document->getElementsByTagName($tag); /** @var \DOMElement $element */ foreach ($elements as $element) { - // Check if a attribute from the tag is needed for the replacement start + // Check if an attribute from the tag is needed for the replacement start $replacementStartNode = $document->createTextNode($replacementStart); // Create the replacement end node diff --git a/src/Helper/Sanitize.php b/src/Helper/Sanitize.php index 213654b..e93d3b8 100644 --- a/src/Helper/Sanitize.php +++ b/src/Helper/Sanitize.php @@ -2,7 +2,6 @@ namespace Bobv\LatexBundle\Helper; /** - * Class Sanitizer * @author BobV */ class Sanitize @@ -15,10 +14,10 @@ class Sanitize * * @return string */ - public static function sanitizeText($text) { - $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]", + public static function sanitizeText(string $text): string { + $strip = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]", "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—", - "—", "–", ",", "<", ".", ">", "/", "?"); + "—", "–", ",", "<", ".", ">", "/", "?"]; $text = trim(str_replace($strip, "", strip_tags($text))); diff --git a/src/Latex/Base/Article.php b/src/Latex/Base/Article.php index 8cd5dbe..4a4c7e3 100644 --- a/src/Latex/Base/Article.php +++ b/src/Latex/Base/Article.php @@ -3,7 +3,6 @@ namespace Bobv\LatexBundle\Latex\Base; /** - * Class LatexArticle * Base article * * @author BobV @@ -13,10 +12,8 @@ class Article extends Base /** * Article constructor, sets defaults - * - * @param string $filename */ - public function __construct($filename) + public function __construct(string $filename) { // Define standard values $this->template = '@BobvLatex/Base/article.tex.twig'; diff --git a/src/Latex/Base/Base.php b/src/Latex/Base/Base.php index 2c19147..bd3f0ec 100644 --- a/src/Latex/Base/Base.php +++ b/src/Latex/Base/Base.php @@ -5,8 +5,6 @@ use Bobv\LatexBundle\Latex\LatexBase; /** - * Class Base - * * @internal Note that this class does not define a template! * It currently is only used by Article and Book as base to avoid code duplication * @@ -14,17 +12,11 @@ */ abstract class Base extends LatexBase { - - /** - * Book constructor, sets defaults - * - * @param string $filename - */ - public function __construct($filename) + public function __construct(string $filename) { // Define standard values $dateTime = new \DateTime(); - $this->params = array( + $this->params = [ 'options' => null, 'lhead' => '', // Top left header @@ -55,9 +47,9 @@ public function __construct($filename) 'tocdepth' => '2', // TOC depth - 'extra_commands' => array(), // Define extra commands if needed - 'packages' => array(), // Define extra packages to use - ); + 'extra_commands' => [], // Define extra commands if needed + 'packages' => [], // Define extra packages to use + ]; // Use the ulem package $this->addPackage('ulem'); @@ -65,5 +57,4 @@ public function __construct($filename) // Call parent constructor parent::__construct($filename); } - } diff --git a/src/Latex/Base/Book.php b/src/Latex/Base/Book.php index 82175e7..2dee113 100644 --- a/src/Latex/Base/Book.php +++ b/src/Latex/Base/Book.php @@ -3,7 +3,6 @@ namespace Bobv\LatexBundle\Latex\Base; /** - * Class LatexBook * Base Book * * @author BobV @@ -13,10 +12,8 @@ class Book extends Base /** * Book constructor, sets defaults - * - * @param string $filename */ - public function __construct($filename) + public function __construct(string $filename) { // Define standard values $this->template = '@BobvLatex/Base/book.tex.twig'; diff --git a/src/Latex/Base/Letter.php b/src/Latex/Base/Letter.php index a14f6ae..676c96d 100644 --- a/src/Latex/Base/Letter.php +++ b/src/Latex/Base/Letter.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexBase; /** - * Class LatexLetter * Base letter * * @author BobV @@ -15,15 +14,13 @@ class Letter extends LatexBase /** * Letter constructor, sets defaults - * - * @param string $filename */ - public function __construct($filename) + public function __construct(string $filename) { // Define standard values $this->template = '@BobvLatex/Base/letter.tex.twig'; $datetime = new \DateTime(); - $this->params = array( + $this->params = [ 'pagenumber' => 'false', // Whether to print pagenumbers from page 2 and forward 'parskip' => 'full', // Spacing between paragraphs (full, half, ..) 'fromalign' => 'right', // Alignment of the from address @@ -44,9 +41,9 @@ public function __construct($filename) 'date' => $datetime->format('d-m-Y'), - 'extra_commands' => array(), // Define extra commands if needed - 'packages' => array(), // Define extra packages to use - ); + 'extra_commands' => [], // Define extra commands if needed + 'packages' => [], // Define extra packages to use + ]; // Use the ulem package $this->addPackage('ulem'); diff --git a/src/Latex/Base/Standalone.php b/src/Latex/Base/Standalone.php index fc4c390..00ea67f 100644 --- a/src/Latex/Base/Standalone.php +++ b/src/Latex/Base/Standalone.php @@ -8,19 +8,17 @@ class Standalone extends LatexBase { /** * Standalone constructor, sets defaults - * - * @param string $filename */ - public function __construct($filename) { + public function __construct(string $filename) { // Define standard values $this->template = '@BobvLatex/Base/standalone.tex.twig'; - $this->params = array( + $this->params = [ 'mode' => 'crop', // Define the standalone mode 'border' => '1pt', // Content border 'varwidth' => true, // Variable width mode - 'extra_commands' => array(), // Define extra commands if needed - 'packages' => array(), // Define extra packages to use - ); + 'extra_commands' => [], // Define extra commands if needed + 'packages' => [], // Define extra packages to use + ]; // Call parent constructor parent::__construct($filename); diff --git a/src/Latex/Element/BlackTitle.php b/src/Latex/Element/BlackTitle.php index f02fc2c..735f161 100644 --- a/src/Latex/Element/BlackTitle.php +++ b/src/Latex/Element/BlackTitle.php @@ -4,23 +4,16 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class BlackTitle - * * @author BobV */ class BlackTitle extends LatexElement { - - /** - * @param $title - */ - public function __construct($title) + public function __construct(string $title) { $this->template = '@BobvLatex/Element/blacktitle.tex.twig'; - $this->params = array( + $this->params = [ 'title' => $title, - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } - } diff --git a/src/Latex/Element/CustomCommand.php b/src/Latex/Element/CustomCommand.php index 7add029..64930d7 100644 --- a/src/Latex/Element/CustomCommand.php +++ b/src/Latex/Element/CustomCommand.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class CustomCommand * Custom command * * @author BobV @@ -15,16 +14,14 @@ class CustomCommand extends LatexElement /** * Constructor of the custom command, also defines the defaults - * - * @param string $text */ - public function __construct($custom) + public function __construct(string $custom) { // Define defaults $this->template = '@BobvLatex/Element/custom_command.tex.twig'; - $this->params = array( - 'custom' => $custom, - ); + $this->params = [ + 'custom' => $custom, + ]; } } diff --git a/src/Latex/Element/CustomElement.php b/src/Latex/Element/CustomElement.php index 748418a..81f2627 100644 --- a/src/Latex/Element/CustomElement.php +++ b/src/Latex/Element/CustomElement.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class CustomElement * Custom element * * @author BobV @@ -15,16 +14,14 @@ class CustomElement extends LatexElement /** * Constructor of the custom element, also defines the defaults - * - * @param string $custom */ - public function __construct($custom) + public function __construct(string $custom) { // Define defaults $this->template = '@BobvLatex/Element/custom_element.tex.twig'; - $this->params = array( - 'custom' => $custom, - ); + $this->params = [ + 'custom' => $custom, + ]; } } diff --git a/src/Latex/Element/EscapedText.php b/src/Latex/Element/EscapedText.php index 2077842..d605bfc 100644 --- a/src/Latex/Element/EscapedText.php +++ b/src/Latex/Element/EscapedText.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class EscapedText * Base text element (fully escaped) * * @author BobV @@ -15,17 +14,15 @@ class EscapedText extends LatexElement /** * Constructor of the title element, also defines the defaults - * - * @param string $text */ - public function __construct($text) + public function __construct(string $text) { // Define defaults $this->template = '@BobvLatex/Element/escaped_text.tex.twig'; - $this->params = array( + $this->params = [ 'text' => $text, - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } } diff --git a/src/Latex/Element/Graphic.php b/src/Latex/Element/Graphic.php index 6771ae5..fd7f001 100644 --- a/src/Latex/Element/Graphic.php +++ b/src/Latex/Element/Graphic.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class Graphic * Base graphic element * * @author BobV @@ -15,15 +14,12 @@ class Graphic extends LatexElement /** * Constructor of the graphic element, also defines the defaults - * - * @param string $graphic_location - * @param string $caption */ - public function __construct($graphic_location, $caption = false) + public function __construct(string $graphic_location, string|bool $caption = false) { // Define defaults $this->template = '@BobvLatex/Element/graphic.tex.twig'; - $this->params = array( + $this->params = [ 'placement' => 'ht!', 'centering' => true, 'location' => $graphic_location, @@ -31,8 +27,8 @@ public function __construct($graphic_location, $caption = false) 'options' => '', 'caption' => $caption, 'label' => 'fig:' . basename($graphic_location), - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } } diff --git a/src/Latex/Element/IncludePdf.php b/src/Latex/Element/IncludePdf.php index 44e65a5..281eb48 100644 --- a/src/Latex/Element/IncludePdf.php +++ b/src/Latex/Element/IncludePdf.php @@ -6,7 +6,6 @@ use Symfony\Component\Process\Process; /** - * Class IncludePdf * Include PDF * * @author BobV @@ -16,24 +15,21 @@ class IncludePdf extends LatexElement /** * Constructor of the include pdf element, also defines the defaults - * - * @param string $fileLocation - * @param boolean $skipFirstWallpaper */ - public function __construct($fileLocation, $skipFirstWallpaper = true) + public function __construct(string $fileLocation, bool $skipFirstWallpaper = true) { // Check amount of pages to avoid a newpage - if (!$skipFirstWallpaper){ + if (!$skipFirstWallpaper) { $totalPages = $this->getPDFPages($fileLocation); $pages = '{2-}'; - }else{ + } else { $totalPages = 0; $pages = '{1-}'; } // Define defaults $this->template = '@BobvLatex/Element/includepdf.tex.twig'; - $this->params = array( + $this->params = [ 'totalPages' => $totalPages, 'skip_first_wallpaper' => $skipFirstWallpaper, 'pages' => $pages, @@ -44,27 +40,19 @@ public function __construct($fileLocation, $skipFirstWallpaper = true) 'y_offset' => '0pt', 'x_offset' => '0pt', 'wallpaper_scaling' => '0.83' - ); + ]; } /** * Source: http://stackoverflow.com/questions/14644353/get-the-number-of-pages-in-a-pdf-document - * - * @param $document - * - * @return int */ - private function getPDFPages($document) + private function getPDFPages(string $document): int { $commandLine = sprintf('pdfinfo %s', $document); - if (method_exists(Process::class, 'fromShellCommandline')) { - $process = Process::fromShellCommandline($commandLine); - } else { - $process = new Process($commandLine); - } + $process = Process::fromShellCommandline($commandLine); $process->run(); - if($process->getExitCode() !== 0){ + if ($process->getExitCode() !== 0) { return 0; } $output = explode("\n", $process->getOutput()); diff --git a/src/Latex/Element/Letter.php b/src/Latex/Element/Letter.php index 638e937..e36775a 100644 --- a/src/Latex/Element/Letter.php +++ b/src/Latex/Element/Letter.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class Letter * Base letter element * * @author BobV @@ -15,22 +14,18 @@ class Letter extends LatexElement /** * Constructor of the title element, also defines the defaults - * - * @param string $address - * @param string $opening - * @param string $text */ - public function __construct($address, $opening, $text) + public function __construct(string $address, string $opening, string $text) { // Define defaults $this->template = '@BobvLatex/Element/letter.tex.twig'; - $this->params = array( + $this->params = [ 'address' => $address, // Address 'opening' => $opening, // Opening of the letter 'text' => $text, // Content of the letter - 'extra_commands' => array(), // Define extra commands if needed - ); + 'extra_commands' => [], // Define extra commands if needed + ]; } } diff --git a/src/Latex/Element/Listing.php b/src/Latex/Element/Listing.php index 7822f8a..acb23d8 100644 --- a/src/Latex/Element/Listing.php +++ b/src/Latex/Element/Listing.php @@ -5,7 +5,6 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class Listing * Base list element * * @author BobV @@ -15,18 +14,15 @@ class Listing extends LatexElement /** * Constructor of the listing element, also defines the defaults - * - * @param array $list - * @param bool $enumerate If set, use enumerate instead of itemize */ public function __construct(array $list, bool $enumerate = false) { // Define defaults $this->template = '@BobvLatex/Element/listing.tex.twig'; - $this->params = array( + $this->params = [ 'list' => $list, - 'extra_commands' => array(), + 'extra_commands' => [], 'enumerate' => $enumerate, - ); + ]; } } diff --git a/src/Latex/Element/LongTable.php b/src/Latex/Element/LongTable.php index 70b5e6c..8341d0f 100644 --- a/src/Latex/Element/LongTable.php +++ b/src/Latex/Element/LongTable.php @@ -5,34 +5,32 @@ class LongTable extends LatexElement { - /** * @param array $rows Alignment rows, for example array(l,r,c) */ - public function __construct($rows = array()) + public function __construct(array $rows = []) { - // Define defaults $this->template = '@BobvLatex/Element/longtable.tex.twig'; - $this->params = array( + $this->params = [ 'caption' => NULL, 'firsthead' => NULL, 'head' => NULL, 'foot' => NULL, 'lastfoot' => NULL, 'rows' => $rows, - 'data' => array(), - 'extra_commands' => array(), - ); + 'data' => [], + 'extra_commands' => [], + ]; } - public function addRow($row) + public function addRow($row): self { $data = $this->getParams()['data']; - $data[] = array( + $data[] = [ 'newRule' => true, 'data' => $row, - ); + ]; $this->setParam('data', $data); return $this; diff --git a/src/Latex/Element/TOC.php b/src/Latex/Element/TOC.php index 2eb66ec..4fe5de7 100644 --- a/src/Latex/Element/TOC.php +++ b/src/Latex/Element/TOC.php @@ -4,13 +4,10 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class TOC - * * @author BobV */ class TOC extends LatexElement { - /** * Constructor of the TOC element, also defines the default */ diff --git a/src/Latex/Element/Table.php b/src/Latex/Element/Table.php index 2665002..da961d9 100644 --- a/src/Latex/Element/Table.php +++ b/src/Latex/Element/Table.php @@ -5,40 +5,39 @@ class Table extends LatexElement { - /** * @param array $rows Alignment rows, for example array(l,r,c) */ - public function __construct($rows = array()) + public function __construct(array $rows = []) { // Define defaults $this->template = '@BobvLatex/Element/table.tex.twig'; - $this->params = array( + $this->params = [ 'tabularx' => true, 'caption' => null, 'rows' => $rows, - 'data' => array(), + 'data' => [], 'width' => '\textwidth', - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } - public function addBottomRule() + public function addBottomRule(): self { $this->addRule('\bottomrule'); return $this; } - public function addMidRule() + public function addMidRule(): self { $this->addRule('\midrule'); return $this; } - public function addRow($row) + public function addRow($row): self { $data = $this->getParams()['data']; $data[] = array( @@ -50,14 +49,14 @@ public function addRow($row) return $this; } - public function addTopRule() + public function addTopRule(): self { $this->addRule('\toprule'); return $this; } - private function addRule($rule) + private function addRule($rule): void { $data = $this->getParams()['data']; $data[] = array( @@ -66,5 +65,4 @@ private function addRule($rule) ); $this->setParam('data', $data); } - } diff --git a/src/Latex/Element/Text.php b/src/Latex/Element/Text.php index a8586b1..e5f0e35 100644 --- a/src/Latex/Element/Text.php +++ b/src/Latex/Element/Text.php @@ -5,27 +5,22 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class Text * Base text element * * @author BobV */ class Text extends LatexElement { - /** * Constructor of the title element, also defines the defaults - * - * @param string $text */ - public function __construct($text) + public function __construct(string $text) { // Define defaults $this->template = '@BobvLatex/Element/text.tex.twig'; - $this->params = array( + $this->params = [ 'text' => $text, - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } - } diff --git a/src/Latex/Element/TitlePage.php b/src/Latex/Element/TitlePage.php index d54c1e6..e18475a 100644 --- a/src/Latex/Element/TitlePage.php +++ b/src/Latex/Element/TitlePage.php @@ -5,27 +5,20 @@ use Bobv\LatexBundle\Latex\LatexElement; /** - * Class TitlePage * Base title page element * * @author BobV */ class TitlePage extends LatexElement { - /** * Constructor of the title page element, also defines the defaults - * - * @param string $title - * @param string $subtitle - * @param string $author - * @param string $date */ - public function __construct($title, $subtitle='', $author='', $date = '') + public function __construct(string $title, string $subtitle = '', string $author = '', string $date = '') { // Define defaults $this->template = '@BobvLatex/Element/titlepage.tex.twig'; - $this->params = array( + $this->params = [ 'title' => $title, 'subtitle' => $subtitle, 'author' => $author, @@ -34,9 +27,7 @@ public function __construct($title, $subtitle='', $author='', $date = '') 'vspace' => '2in', 'vspace_subtitle' => '0.1in', - - 'extra_commands' => array(), - ); + 'extra_commands' => [], + ]; } - } diff --git a/src/Latex/LatexBase.php b/src/Latex/LatexBase.php index 0de58c9..1816fae 100644 --- a/src/Latex/LatexBase.php +++ b/src/Latex/LatexBase.php @@ -6,30 +6,20 @@ class LatexBase extends LatexParams implements LatexBaseInterface { - /** @var array */ - protected $elements = array(); - /** @var string */ - protected $fileName; - /** @var string */ - protected $template; - /** @var array */ - protected $dependencies = array(); + protected array $elements = []; + protected string $fileName; // Set in constructor + protected ?string $template = null; + protected array $dependencies = []; - /** - * @param string $filename - */ - public function __construct($filename) + public function __construct(string $filename) { $this->setFileName($filename); } /** - * @param LatexInterface $latexInterface - * - * @return $this - * @throws \Bobv\LatexBundle\Exception\LatexException + * @throws LatexException */ - public function addElement(LatexInterface $latexInterface) + public function addElement(LatexInterface $latexInterface): self { if ($latexInterface instanceof LatexBaseInterface) { throw new LatexException("A base LaTeX object can not have another base LaTeX object as element!"); @@ -40,89 +30,56 @@ public function addElement(LatexInterface $latexInterface) return $this; } - /** - * @return array - */ - public function getContext() + public function getContext(): array { return array_merge( $this->getParams(), - array( + [ 'elements' => $this->getElements(), - ) + ] ); } - /** - * @return array - */ - public function getElements() + public function getElements(): array { return $this->elements; } - /** - * @param array $elements - */ - public function setElements($elements) + public function setElements(array $elements): void { $this->elements = $elements; } - /** - * @return string - */ - public function getFileName() + public function getFileName(): string { return $this->fileName; } - /** - * @param string $fileName - * - * @return LatexBaseInterface $this - */ - public function setFileName($fileName) + public function setFileName(string $fileName): self { $this->fileName = $fileName; return $this; } - /** - * @return string - */ - public function getTemplate() + public function getTemplate(): string { return $this->template; } - /** - * @param string $template - * - * @return LatexBaseInterface $this - */ - public function setTemplate($template) + public function setTemplate(string $template): self { $this->template = $template; return $this; } - /** - * @return array - */ - public function getDependencies() + public function getDependencies(): array { return $this->dependencies; } - /** - * @param $dependency - * - * @return LatexBaseInterface $this - */ - public function addDependency($dependency) + public function addDependency(mixed $dependency): self { $this->dependencies[] = $dependency; @@ -131,12 +88,8 @@ public function addDependency($dependency) /** * To add multiple dependencies locations - * - * @param $dependencies - * - * @return LatexBaseInterface */ - public function addDependencies($dependencies) + public function addDependencies(iterable $dependencies): self { foreach ($dependencies as $dependency) { $this->addDependency($dependency); @@ -146,17 +99,12 @@ public function addDependencies($dependencies) } /** - * Add an package to include - * - * @param $package - * @param $options - * - * @return LatexBaseInterface $this + * Add a package to include */ - public function addPackage($package, $options = '') + public function addPackage(mixed $package, string $options = ''): self { $matches = array(); - preg_match_all('/\\\usepackage\{([^}]+)\}/u', $package, $matches); + preg_match_all('/\\\usepackage\{([^}]+)}/u', $package, $matches); if (count($matches[1]) > 0) { $package = $matches[1][0]; } @@ -171,12 +119,8 @@ public function addPackage($package, $options = '') /** * Add multiple packages to include (without options) - * - * @param $packages - * - * @return mixed */ - public function addPackages($packages) + public function addPackages(iterable $packages): self { foreach ($packages as $package) { $this->addPackage($package); diff --git a/src/Latex/LatexBaseInterface.php b/src/Latex/LatexBaseInterface.php index 5ea9e08..800d82b 100644 --- a/src/Latex/LatexBaseInterface.php +++ b/src/Latex/LatexBaseInterface.php @@ -4,71 +4,41 @@ interface LatexBaseInterface extends LatexInterface { - /** - * Constructor - * - * @param string $fileName - */ - public function __construct($fileName); + public function __construct(string $fileName); /** * Should return the filename for the pdf file - * - * @return string */ - public function getFileName(); + public function getFileName(): string; /** * In case you want to change the filename, use this method - * - * @param string $fileName - * - * @return LatexBaseInterface */ - public function setFileName($fileName); + public function setFileName(string $fileName): self; /** * Should return an array with dependency locations - * - * @return array */ - public function getDependencies(); + public function getDependencies(): array; /** - * To add an dependency location - * - * @param $dependency - * - * @return LatexBaseInterface + * To add a dependency location */ - public function addDependency($dependency); + public function addDependency(mixed $dependency): self; /** * To add multiple dependencies locations - * - * @param $dependencies - * - * @return LatexBaseInterface */ - public function addDependencies($dependencies); + public function addDependencies(iterable $dependencies): self; /** - * Add an package to include - * - * @param $package - * @param $options - * - * @return LatexBaseInterface $this + * Add a package to include */ - public function addPackage($package, $options = ''); + public function addPackage(mixed $package, string $options = ''): self; /** * Add multiple packages to include (without options) - * - * @param $packages - * - * @return mixed */ - public function addPackages($packages); + public function addPackages(iterable $packages): self; } diff --git a/src/Latex/LatexElement.php b/src/Latex/LatexElement.php index fcbc88a..832dfa0 100644 --- a/src/Latex/LatexElement.php +++ b/src/Latex/LatexElement.php @@ -3,28 +3,19 @@ class LatexElement extends LatexParams implements LatexInterface { - /** @var string */ - protected $template; + protected string $template; - public function getContext() + public function getContext(): array { return $this->getParams(); } - /** - * @return string - */ - public function getTemplate() + public function getTemplate(): string { return $this->template; } - /** - * @param string $template - * - * @return LatexInterface $this - */ - public function setTemplate($template) + public function setTemplate(string $template): self { $this->template = $template; diff --git a/src/Latex/LatexInterface.php b/src/Latex/LatexInterface.php index 4b758ba..285d8db 100644 --- a/src/Latex/LatexInterface.php +++ b/src/Latex/LatexInterface.php @@ -3,52 +3,33 @@ namespace Bobv\LatexBundle\Latex; /** - * Interface LatexInterface * All Latex objects should implement this class - * - * @package Bobv\LatexBundle\Latex */ interface LatexInterface { - /** * Needs to return the parameters for the twig render - * - * @return array */ - public function getContext(); + public function getContext(): array; /** * Return all set params - * - * @return array */ - public function getParams(); + public function getParams(): array; /** * Set a specific param in the context for Twig - * - * @param string $param - * @param mixed $value - * - * @return LatexInterface */ - public function setParam($param, $value); + public function setParam(string $param, mixed $value): self; /** * Should return the twig template - * - * @return string */ - public function getTemplate(); + public function getTemplate(): string; /** * In case you want to change the twig template, use this method - * - * @param string $template - * - * @return LatexInterface */ - public function setTemplate($template); + public function setTemplate(string $template): self; } diff --git a/src/Latex/LatexParams.php b/src/Latex/LatexParams.php index 12be6e8..4515458 100644 --- a/src/Latex/LatexParams.php +++ b/src/Latex/LatexParams.php @@ -4,47 +4,37 @@ use Bobv\LatexBundle\Exception\LatexException; /** - * Class LatexContext * Use this to predefine the context methods and vars * * @author BobV */ -class LatexParams { +class LatexParams +{ + protected array $params = []; - /** @var array */ - protected $params = array(); - - /** - * Return the params - * @return array - */ - public function getParams(){ + public function getParams(): array { return $this->params; } /** * Set a specific parameter for the class * - * @param string $param - * @param mixed $value - * - * @return LatexInterface $this * @throws \Bobv\LatexBundle\Exception\LatexException */ - public function setParam($param, $value){ - if(array_key_exists($param, $this->params)){ + public function setParam(string $param, mixed $value): LatexInterface { + if (array_key_exists($param, $this->params)) { // Check if the param is defined as array - if(is_array($this->params[$param])){ + if (is_array($this->params[$param])) { // If the value is an array, replace the complete array, else add a new array element - if(is_array($value)){ + if (is_array($value)) { $this->params[$param] = $value; - }else{ + } else { $this->params[$param][] = $value; } - }else{ + } else { $this->params[$param] = $value; } - }else{ + } else { throw new LatexException("The param $param is not defined for " . get_class($this)); } return $this; diff --git a/src/Latex/LatexSection.php b/src/Latex/LatexSection.php index 75c58af..9f147f1 100644 --- a/src/Latex/LatexSection.php +++ b/src/Latex/LatexSection.php @@ -5,18 +5,13 @@ class LatexSection extends LatexParams implements LatexInterface { - /** @var array */ - protected $elements = array(); - /** @var string */ - protected $template; + protected array $elements = []; + protected string $template; /** - * @param LatexInterface $latexInterface - * - * @return $this * @throws \Bobv\LatexBundle\Exception\LatexException */ - public function addElement(LatexInterface $latexInterface) + public function addElement(LatexInterface $latexInterface): self { if ($latexInterface instanceof LatexBaseInterface) { throw new LatexException("A base LaTeX object can not have another base LaTeX object as element!"); @@ -27,49 +22,32 @@ public function addElement(LatexInterface $latexInterface) return $this; } - /** - * @return array - */ - public function getContext() + public function getContext(): array { return array_merge( $this->getParams(), - array( + [ 'elements' => $this->getElements(), - ) + ] ); } - /** - * @return array - */ - public function getElements() + public function getElements(): array { return $this->elements; } - /** - * @param array $elements - */ - public function setElements($elements) + public function setElements(array $elements): void { $this->elements = $elements; } - /** - * @return string - */ - public function getTemplate() + public function getTemplate(): string { return $this->template; } - /** - * @param string $template - * - * @return LatexInterface $this - */ - public function setTemplate($template) + public function setTemplate(string $template): self { $this->template = $template; diff --git a/src/Latex/Section/Box.php b/src/Latex/Section/Box.php index 3457df5..99f10f1 100644 --- a/src/Latex/Section/Box.php +++ b/src/Latex/Section/Box.php @@ -3,18 +3,18 @@ use Bobv\LatexBundle\Latex\LatexSection; -class Box extends LatexSection { - +class Box extends LatexSection +{ /** - * Constructor of the section section, also defines the default + * Constructor of the box section, also defines the default */ - public function __construct(){ + public function __construct() { $this->template = '@BobvLatex/Section/box.tex.twig'; - $this->params = array( + $this->params = [ 'newpage' => false, // Standard a section starts on a new page - 'extra_commands' => array(), // Define extra commands at the begin of the section - ); + 'extra_commands' => [], // Define extra commands at the beginning of the section + ]; } } diff --git a/src/Latex/Section/MiniPage.php b/src/Latex/Section/MiniPage.php index eec3e79..aaa7d84 100644 --- a/src/Latex/Section/MiniPage.php +++ b/src/Latex/Section/MiniPage.php @@ -5,19 +5,18 @@ class MiniPage extends LatexSection { - /** * Constructor of the section minipage, also defines the default */ public function __construct() { $this->template = '@BobvLatex/Section/minipage.tex.twig'; - $this->params = array( + $this->params = [ 'width' => '\textwidth', // Width of the minipage 'newpage' => false, // Standard a section starts on a new page - 'extra_commands' => array(), // Define extra commands at the begin of the section - ); + 'extra_commands' => [], // Define extra commands at the beginning of the section + ]; } } diff --git a/src/Latex/Section/Section.php b/src/Latex/Section/Section.php index 02a4b30..be91cf5 100644 --- a/src/Latex/Section/Section.php +++ b/src/Latex/Section/Section.php @@ -7,18 +7,16 @@ class Section extends LatexSection { /** * Constructor of the section section, also defines the default - * - * @param string $sectionTitle */ - public function __construct($sectionTitle = ''){ + public function __construct(string $sectionTitle = ''){ $this->template = '@BobvLatex/Section/section.tex.twig'; - $this->params = array( + $this->params = [ 'sectionTitle' => $sectionTitle, 'includeTOC' => true, 'newpage' => true, // Standard a section starts on a new page - 'extra_commands' => array(), // Define extra commands at the begin of the section - ); + 'extra_commands' => [], // Define extra commands at the beginning of the section + ]; } } diff --git a/src/Latex/Section/SubSection.php b/src/Latex/Section/SubSection.php index b6bf962..16732f1 100644 --- a/src/Latex/Section/SubSection.php +++ b/src/Latex/Section/SubSection.php @@ -3,22 +3,20 @@ use Bobv\LatexBundle\Latex\LatexSection; -class SubSection extends LatexSection { - +class SubSection extends LatexSection +{ /** * Constructor of the subsection section, also defines the default - * - * @param string $subsectionTitle */ - public function __construct($subsectionTitle = ''){ + public function __construct(string $subsectionTitle = '') { $this->template = '@BobvLatex/Section/sub_section.tex.twig'; - $this->params = array( + $this->params = [ 'subsectionTitle' => $subsectionTitle, 'includeTOC' => true, 'newpage' => false, // Standard a subsection does not start on a new page - 'extra_commands' => array(), // Define extra commands at the begin of the section - ); + 'extra_commands' => [], // Define extra commands at the beginning of the section + ]; } } diff --git a/src/Latex/Section/SubSubSection.php b/src/Latex/Section/SubSubSection.php index 03ce9ad..97c4c44 100644 --- a/src/Latex/Section/SubSubSection.php +++ b/src/Latex/Section/SubSubSection.php @@ -3,22 +3,20 @@ use Bobv\LatexBundle\Latex\LatexSection; -class SubSubSection extends LatexSection { - +class SubSubSection extends LatexSection +{ /** * Constructor of the subsubsection section, also defines the default - * - * @param string $subsubsectionTitle */ - public function __construct($subsubsectionTitle = ''){ + public function __construct(string $subsubsectionTitle = '') { $this->template = '@BobvLatex/Section/sub_sub_section.tex.twig'; - $this->params = array( + $this->params = [ 'subsubsectionTitle' => $subsubsectionTitle, 'includeTOC' => true, 'newpage' => false, // Standard a subsubsection does not start on a new page - 'extra_commands' => array(), // Define extra commands at the begin of the section - ); + 'extra_commands' => [], // Define extra commands at the beginning of the section + ]; } } diff --git a/src/Twig/AbstractBobvLatexExtension.php b/src/Twig/AbstractBobvLatexExtension.php index 959cba4..605e6db 100644 --- a/src/Twig/AbstractBobvLatexExtension.php +++ b/src/Twig/AbstractBobvLatexExtension.php @@ -2,12 +2,8 @@ namespace Bobv\LatexBundle\Twig; -if (class_exists('Twig\Extension\AbstractExtension')) { - class AbstractBobvLatexExtension extends \Twig\Extension\AbstractExtension - { - } -} else { - class AbstractBobvLatexExtension extends \Twig_Extension - { - } +use Twig\Extension\AbstractExtension; + +class AbstractBobvLatexExtension extends AbstractExtension +{ } diff --git a/src/Twig/BobvLatexExtension.php b/src/Twig/BobvLatexExtension.php index 9088ee7..e8d81ae 100644 --- a/src/Twig/BobvLatexExtension.php +++ b/src/Twig/BobvLatexExtension.php @@ -6,28 +6,18 @@ use function Symfony\Component\String\u; /** - * Class BobvLatexExtension - * * @author BobV */ class BobvLatexExtension extends AbstractBobvLatexExtension { + private Parser $parser; // Set in constructor - /** @var Parser */ - private $parser; - /** @var bool */ - private $useSymfonyString; - - public function __construct(bool $useSymfonyString) + public function __construct(private readonly bool $useSymfonyString) { - $this->parser = new Parser(); - $this->useSymfonyString = $useSymfonyString; + $this->parser = new Parser(); } - /** - * @return array - */ - public function getFilters() + public function getFilters(): array { $filterClass = class_exists('\\Twig\\TwigFilter') ? '\\Twig\\TwigFilter' : '\\Twig_SimpleFilter'; @@ -38,15 +28,12 @@ public function getFilters() ]; } - /** - * @return string - */ - public function getName() + public function getName(): string { return 'bobv_latex_twig_extension'; } - private function passThroughSfString($text) + private function passThroughSfString(?string $text): ?string { if (!$this->useSymfonyString) { return $text; @@ -55,12 +42,7 @@ private function passThroughSfString($text) return u($text)->ascii()->toString(); } - /** - * @param string $text - * - * @return string - */ - public function latexEscape($text, $checkTable = true, $removeLatex = false, $parseNewLines = false, $removeGreek = false) + public function latexEscape(?string $text, bool $checkTable = true, bool $removeLatex = false, bool $parseNewLines = false, bool $removeGreek = false): string { return $this->passThroughSfString( $this->parser->parseText($text, $checkTable, $removeLatex, $parseNewLines, $removeGreek) @@ -69,24 +51,15 @@ public function latexEscape($text, $checkTable = true, $removeLatex = false, $pa /** * Proxy method to set some params for the parseText call - * - * @param string $text - * - * @return string */ - public function latexEscapeAll($text) + public function latexEscapeAll(?string $text): ?string { return $this->passThroughSfString( $this->parser->parseText($text, false, true, true, true) ); } - /** - * @param string $text - * - * @return string - */ - public function latexParseHtml($text) + public function latexParseHtml(?string $text): ?string { return $this->passThroughSfString( $this->parser::parseHtml($text)