Skip to content

Commit

Permalink
split header and body bags
Browse files Browse the repository at this point in the history
  • Loading branch information
Jean-Beru committed Nov 17, 2024
1 parent 9af8b64 commit 0a09396
Show file tree
Hide file tree
Showing 19 changed files with 134 additions and 136 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"symfony/http-foundation": "^6.4 || ^7.0",
"symfony/http-kernel": "^6.4 || ^7.0",
"symfony/mime": "^6.4 || ^7.0",
"symfony/options-resolver": "^7.1",
"symfony/options-resolver": "^7.0",
"symfony/string": "^6.4 || ^7.0"
},
"require-dev": {
Expand Down
22 changes: 16 additions & 6 deletions config/builder_pdf.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

// use Sensiolabs\GotenbergBundle\Builder\Pdf\ConvertPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\AbstractBuilder;
use Sensiolabs\GotenbergBundle\Builder\HtmlPdfBuilder;
// use Sensiolabs\GotenbergBundle\Builder\Pdf\LibreOfficePdfBuilder;
// use Sensiolabs\GotenbergBundle\Builder\Pdf\MarkdownPdfBuilder;
Expand All @@ -9,6 +10,7 @@
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use function Symfony\Component\DependencyInjection\Loader\Configurator\abstract_arg;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service_locator;

return static function (ContainerConfigurator $container): void {
$services = $container->services();
Expand All @@ -17,16 +19,24 @@
->tag('monolog.logger', ['channel' => 'sensiolabs_gotenberg'])
;

$services->set('.sensiolabs_gotenberg.pdf_builder.html', HtmlPdfBuilder::class)
->share(false)
$services->set('.sensiolabs_gotenberg.abstract_builder', AbstractBuilder::class)
->abstract()
->args([
service('sensiolabs_gotenberg.client'),
service('sensiolabs_gotenberg.asset.base_dir_formatter'),
abstract_arg('default configuration'),
service('logger')->nullOnInvalid(),
service('twig')->nullOnInvalid(),
service('router')->nullOnInvalid(),
abstract_arg('default body configuration'),
abstract_arg('default headers configuration'),
])
;

$services->set('.sensiolabs_gotenberg.pdf_builder.html', HtmlPdfBuilder::class)
->share(false)
->parent('.sensiolabs_gotenberg.abstract_builder')
->arg(4, service_locator([
'logger' => service('logger')->nullOnInvalid(),
'twig' => service('twig')->nullOnInvalid(),
'router' => service('router')->nullOnInvalid(),
]))
->tag('sensiolabs_gotenberg.pdf_builder')
;

Expand Down
33 changes: 19 additions & 14 deletions src/Builder/AbstractBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace Sensiolabs\GotenbergBundle\Builder;

use Psr\Log\LoggerInterface;
use Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies\RequireAssetTrait;
use Psr\Container\ContainerInterface;
use Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies\AssetBaseDirFormatterAwareTrait;
use Sensiolabs\GotenbergBundle\Builder\Result\GotenbergAsyncResult;
use Sensiolabs\GotenbergBundle\Builder\Result\GotenbergFileResult;
use Sensiolabs\GotenbergBundle\Client\BodyBag;
Expand All @@ -12,6 +12,7 @@
use Sensiolabs\GotenbergBundle\Formatter\AssetBaseDirFormatter;
use Sensiolabs\GotenbergBundle\Processor\NullProcessor;
use Sensiolabs\GotenbergBundle\Processor\ProcessorInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File as DataPartFile;
Expand All @@ -20,9 +21,8 @@
/**
* Builder for responses.
*/
abstract class AbstractBuilder implements BuilderInterface
abstract class AbstractBuilder implements BuilderAsyncInterface, BuilderFileInterface
{
use RequireAssetTrait;

private readonly BodyBag $bodyBag;
private readonly HeadersBag $headersBag;
Expand All @@ -39,14 +39,17 @@ public function __construct(
protected readonly GotenbergClientInterface $client,
protected readonly AssetBaseDirFormatter $asset,
array $defaultBodyData = [],
protected readonly LoggerInterface|null $logger = null,
) {
$optionsResolver = new OptionsResolver();
// $optionsResolver->setDefaults($defaultBodyData);
$this->configure($optionsResolver);

$this->bodyBag = new BodyBag($optionsResolver);
$this->headersBag = new HeadersBag($optionsResolver);
array $defaultHeadersData = [],
protected readonly ContainerInterface $dependencies = new Container(),
)
{
$bodyOptionsResolver = (new OptionsResolver())->setDefaults($defaultBodyData);
$headersOptionsResolver = (new OptionsResolver())->setRequired($defaultHeadersData);

$this->configure($bodyOptionsResolver, $headersOptionsResolver);

$this->bodyBag = new BodyBag($bodyOptionsResolver);
$this->headersBag = new HeadersBag($headersOptionsResolver);
}

/**
Expand Down Expand Up @@ -123,10 +126,12 @@ public function generateAsync(): GotenbergAsyncResult

abstract protected function getEndpoint(): string;

protected function configure(OptionsResolver $optionsResolver): void
protected function configure(OptionsResolver $bodyOptionsResolver, OptionsResolver $headersOptionsResolver): void
{
$optionsResolver->setDefined([
$bodyOptionsResolver->setDefined([
'assets',
]);
$headersOptionsResolver->setDefined([
'Gotenberg-Output-Filename',
]);
}
Expand Down
10 changes: 4 additions & 6 deletions src/Builder/Behaviors/Chromium/HeaderFooterTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

namespace Sensiolabs\GotenbergBundle\Builder\Behaviors\Chromium;

use Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies\RequireAssetTrait;
use Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies\RequireTwigTrait;
use Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies\TwigAwareTrait;
use Sensiolabs\GotenbergBundle\Client\BodyBag;
use Sensiolabs\GotenbergBundle\Enumeration\Part;
use Sensiolabs\GotenbergBundle\Exception\PdfPartRenderingException;
Expand All @@ -16,14 +15,13 @@
*/
trait HeaderFooterTrait
{
use RequireAssetTrait;
use RequireTwigTrait;
use TwigAwareTrait;

abstract protected function getBodyBag(): BodyBag;

protected function configure(OptionsResolver $optionsResolver): void
protected function configure(OptionsResolver $bodyOptionsResolver, OptionsResolver $headersOptionsResolver): void
{
$optionsResolver
$bodyOptionsResolver
->setDefined(
array_map(fn (Part $p): string => $p->value, Part::cases()),
)
Expand Down
28 changes: 14 additions & 14 deletions src/Builder/Behaviors/Chromium/PagePropertiesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,73 +13,73 @@ trait PagePropertiesTrait
{
abstract protected function getBodyBag(): BodyBag;

protected function configure(OptionsResolver $optionsResolver): void
protected function configure(OptionsResolver $bodyOptionsResolver, OptionsResolver $headersOptionsResolver): void
{
$normalizeUnit = static fn (Options $options, $value): string => is_numeric($value) ? $value.'in' : (string) $value;
// See https://regex101.com/r/XUK2Ip/1
$validateRange = static fn (string $value): bool => 1 === preg_match('/^ *(\d+ *(- *\d+)? *, *)*\d+ *(- *\d+)? *$/', $value);

$optionsResolver
$bodyOptionsResolver
->define('singlePage')
->info('Define whether to print the entire content in one single page.')
->allowedTypes('bool')
;
$optionsResolver
$bodyOptionsResolver
->define('paperWidth')
->info('Specify paper width using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('paperHeight')
->info('Specify paper height using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('marginTop')
->info('Specify top margin width using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('marginBottom')
->info('Specify bottom margin using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('marginLeft')
->info('Specify left margin using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('marginRight')
->info('Specify right margin using units like 72pt, 96px, 1in, 25.4mm, 2.54cm, or 6pc. Default unit is inches if unspecified.')
->normalize($normalizeUnit)
;
$optionsResolver
$bodyOptionsResolver
->define('preferCssPageSize')
->info('Define whether to prefer page size as defined by CSS.')
->allowedTypes('bool')
;
$optionsResolver
$bodyOptionsResolver
->define('printBackground')
->info('Print the background graphics.')
->allowedTypes('bool')
;
$optionsResolver
$bodyOptionsResolver
->define('omitBackground')
->info('Hide the default white background and allow generating PDFs with transparency.')
->allowedTypes('bool')
;
$optionsResolver
$bodyOptionsResolver
->define('landscape')
->info('Set the paper orientation to landscape.')
->allowedTypes('bool')
;
$optionsResolver
$bodyOptionsResolver
->define('scale')
->info('The scale of the page rendering.')
->allowedTypes('int', 'float')
;
$optionsResolver
$bodyOptionsResolver
->define('nativePageRanges')
->info("Page ranges to print, e.g., '1-5, 8, 11-13' - empty means all pages.")
->allowedValues($validateRange)
Expand Down
6 changes: 3 additions & 3 deletions src/Builder/Behaviors/Chromium/WaitBeforeRenderingTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ trait WaitBeforeRenderingTrait
{
abstract protected function getBodyBag(): BodyBag;

protected function configure(OptionsResolver $optionsResolver): void
protected function configure(OptionsResolver $bodyOptionsResolver, OptionsResolver $headersOptionsResolver): void
{
$optionsResolver
$bodyOptionsResolver
->setDefined(['waitDelay', 'waitForExpression'])
->setAllowedTypes('waitDelay', ['string'])
->setAllowedValues('waitDelay', fn(mixed $value): bool => 1 === preg_match('/^\d+(s|ms)$/', $value))
->setAllowedValues('waitDelay', fn (mixed $value): bool => 1 === preg_match('/^\d+(s|ms)$/', $value))
->setAllowedTypes('waitForExpression', ['string'])
;
}
Expand Down
8 changes: 4 additions & 4 deletions src/Builder/Behaviors/ChromiumTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ trait ChromiumTrait
use Chromium\PagePropertiesTrait { Chromium\PagePropertiesTrait::configure as configurePageProperties; }
use Chromium\WaitBeforeRenderingTrait { Chromium\WaitBeforeRenderingTrait::configure as configureWaitBeforeRendering; }

protected function configure(OptionsResolver $optionsResolver): void
protected function configure(OptionsResolver $bodyOptionsResolver, OptionsResolver $headersOptionsResolver): void
{
$this->configureHeaderFooter($optionsResolver);
$this->configurePageProperties($optionsResolver);
$this->configureWaitBeforeRendering($optionsResolver);
$this->configureHeaderFooter($bodyOptionsResolver, $headersOptionsResolver);
$this->configurePageProperties($bodyOptionsResolver, $headersOptionsResolver);
$this->configureWaitBeforeRendering($bodyOptionsResolver, $headersOptionsResolver);
}
}
10 changes: 0 additions & 10 deletions src/Builder/Behaviors/Dependencies/RequireAssetTrait.php

This file was deleted.

10 changes: 0 additions & 10 deletions src/Builder/Behaviors/Dependencies/RequireTwigTrait.php

This file was deleted.

10 changes: 0 additions & 10 deletions src/Builder/Behaviors/Dependencies/RequireUrlGeneratorTrait.php

This file was deleted.

20 changes: 20 additions & 0 deletions src/Builder/Behaviors/Dependencies/TwigAwareTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies;

use Psr\Container\ContainerInterface;
use Twig\Environment;

trait TwigAwareTrait
{
protected readonly ContainerInterface $dependencies;

protected function getTwig(): Environment
{
if (!($environment = $this->dependencies->get('twig')) instanceof Environment) {
throw new \LogicException(\sprintf('Twig is required to use "%s" method. Try to run "composer require symfony/twig-bundle".', __METHOD__));
}

return $environment;
}
}
20 changes: 20 additions & 0 deletions src/Builder/Behaviors/Dependencies/UrlGeneratorAwareTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Sensiolabs\GotenbergBundle\Builder\Behaviors\Dependencies;

use Psr\Container\ContainerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

trait UrlGeneratorAwareTrait
{
protected readonly ContainerInterface $dependencies;

protected function getUrlGenerator(): UrlGeneratorInterface
{
if (!($urlGenerator = $this->dependencies->get('urlGenerator')) instanceof UrlGeneratorInterface) {
throw new \LogicException(\sprintf('UrlGenerator is required to use "%s" method. Try to run "composer require symfony/router".', __METHOD__));
}

return $urlGenerator;
}
}
Loading

0 comments on commit 0a09396

Please sign in to comment.