Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add a builder to write pdf metadata #93

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions config/builder_pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Sensiolabs\GotenbergBundle\Builder\Pdf\MarkdownPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\MergePdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\UrlPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\WriteMetadataPdfBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;

Expand Down Expand Up @@ -71,6 +72,16 @@
->tag('sensiolabs_gotenberg.pdf_builder')
;

$services->set('.sensiolabs_gotenberg.pdf_builder.write_metadata', WriteMetadataPdfBuilder::class)
->share(false)
->args([
service('sensiolabs_gotenberg.client'),
service('sensiolabs_gotenberg.asset.base_dir_formatter'),
])
->call('setLogger', [service('logger')->nullOnInvalid()])
->tag('sensiolabs_gotenberg.pdf_builder')
;

$services->set('.sensiolabs_gotenberg.pdf_builder.convert', ConvertPdfBuilder::class)
->share(false)
->args([
Expand Down
90 changes: 90 additions & 0 deletions src/Builder/Pdf/WriteMetadataPdfBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

namespace Sensiolabs\GotenbergBundle\Builder\Pdf;

use Sensiolabs\GotenbergBundle\Exception\InvalidBuilderConfiguration;
use Sensiolabs\GotenbergBundle\Exception\MissingRequiredFieldException;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File as DataPartFile;

final class WriteMetadataPdfBuilder extends AbstractPdfBuilder
{
private const ENDPOINT = '/forms/pdfengines/metadata/write';

/**
* To set configurations by an array of configurations.
*
* @param array<string, mixed> $configurations
*/
public function setConfigurations(array $configurations): static
{
foreach ($configurations as $property => $value) {
$this->addConfiguration($property, $value);
}

return $this;
}

public function files(string ...$paths): self
{
$this->formFields['files'] = [];

foreach ($paths as $path) {
$this->assertFileExtension($path, ['pdf']);

$dataPart = new DataPart(new DataPartFile($this->asset->resolve($path)));

$this->formFields['files'][$path] = $dataPart;
}

return $this;
}

/**
* Resets the metadata.
*
* @see https://gotenberg.dev/docs/routes#metadata-chromium
* @see https://exiftool.org/TagNames/XMP.html#pdf
*
* @param array<string, mixed> $metadata
*/
public function metadata(array $metadata): static
{
$this->formFields['metadata'] = $metadata;

return $this;
}

/**
* The metadata to write.
*/
public function addMetadata(string $key, string $value): static
{
$this->formFields['metadata'] ??= [];
$this->formFields['metadata'][$key] = $value;

return $this;
}

public function getMultipartFormData(): array
{
if ([] === ($this->formFields['files'] ?? [])) {
ConstantBqt marked this conversation as resolved.
Show resolved Hide resolved
throw new MissingRequiredFieldException('At least one PDF file is required');
}

return parent::getMultipartFormData();
}

protected function getEndpoint(): string
{
return self::ENDPOINT;
}

private function addConfiguration(string $configurationName, mixed $value): void
{
match ($configurationName) {
'metadata' => $this->metadata($value),
default => throw new InvalidBuilderConfiguration(sprintf('Invalid option "%s": no method does not exist in class "%s" to configured it.', $configurationName, self::class)),
};
}
}
18 changes: 18 additions & 0 deletions src/Debug/TraceableGotenbergPdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Sensiolabs\GotenbergBundle\Builder\Pdf\MergePdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\PdfBuilderInterface;
use Sensiolabs\GotenbergBundle\Builder\Pdf\UrlPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\WriteMetadataPdfBuilder;
use Sensiolabs\GotenbergBundle\Debug\Builder\TraceablePdfBuilder;
use Sensiolabs\GotenbergBundle\GotenbergPdfInterface;

Expand Down Expand Up @@ -122,6 +123,23 @@ public function merge(): PdfBuilderInterface
return $traceableBuilder;
}

/**
* @return WriteMetadataPdfBuilder|TraceablePdfBuilder
*/
public function writeMetadata(): PdfBuilderInterface
{
/** @var WriteMetadataPdfBuilder|TraceablePdfBuilder $traceableBuilder */
$traceableBuilder = $this->inner->writeMetadata();

if (!$traceableBuilder instanceof TraceablePdfBuilder) {
return $traceableBuilder;
}

$this->builders[] = ['write_metadata', $traceableBuilder];

return $traceableBuilder;
}

/**
* @return ConvertPdfBuilder|TraceablePdfBuilder
*/
Expand Down
9 changes: 8 additions & 1 deletion src/GotenbergPdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Sensiolabs\GotenbergBundle\Builder\Pdf\MergePdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\PdfBuilderInterface;
use Sensiolabs\GotenbergBundle\Builder\Pdf\UrlPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\WriteMetadataPdfBuilder;

final class GotenbergPdf implements GotenbergPdfInterface
{
Expand All @@ -24,14 +25,15 @@ public function get(string $builder): PdfBuilderInterface
}

/**
* @param 'html'|'url'|'markdown'|'office'|'merge'|'convert' $key
* @param 'html'|'url'|'markdown'|'office'|'merge'|'write_metadata'|'convert' $key
*
* @return (
* $key is 'html' ? HtmlPdfBuilder :
* $key is 'url' ? UrlPdfBuilder :
* $key is 'markdown' ? MarkdownPdfBuilder :
* $key is 'office' ? LibreOfficePdfBuilder :
* $key is 'merge' ? MergePdfBuilder :
* $key is 'write_metadata' ? WriteMetadataPdfBuilder :
* $key is 'convert' ? ConvertPdfBuilder :
* PdfBuilderInterface
* )
Expand Down Expand Up @@ -66,6 +68,11 @@ public function merge(): PdfBuilderInterface
return $this->getInternal('merge');
}

public function writeMetadata(): PdfBuilderInterface
{
return $this->getInternal('write_metadata');
}

public function convert(): PdfBuilderInterface
{
return $this->getInternal('convert');
Expand Down
6 changes: 6 additions & 0 deletions src/GotenbergPdfInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Sensiolabs\GotenbergBundle\Builder\Pdf\MergePdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\PdfBuilderInterface;
use Sensiolabs\GotenbergBundle\Builder\Pdf\UrlPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\WriteMetadataPdfBuilder;

interface GotenbergPdfInterface
{
Expand Down Expand Up @@ -46,6 +47,11 @@ public function markdown(): PdfBuilderInterface;
*/
public function merge(): PdfBuilderInterface;

/**
* @return WriteMetadataPdfBuilder
*/
public function writeMetadata(): PdfBuilderInterface;

/**
* @return ConvertPdfBuilder
*/
Expand Down
81 changes: 81 additions & 0 deletions tests/Builder/Pdf/WriteMetadataPdfBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace Builder\Pdf;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\UsesClass;
use Sensiolabs\GotenbergBundle\Builder\Pdf\AbstractPdfBuilder;
use Sensiolabs\GotenbergBundle\Builder\Pdf\WriteMetadataPdfBuilder;
use Sensiolabs\GotenbergBundle\Exception\MissingRequiredFieldException;
use Sensiolabs\GotenbergBundle\Formatter\AssetBaseDirFormatter;
use Sensiolabs\GotenbergBundle\Tests\Builder\AbstractBuilderTestCase;

#[CoversClass(WriteMetadataPdfBuilder::class)]
#[UsesClass(AbstractPdfBuilder::class)]
#[UsesClass(AssetBaseDirFormatter::class)]
final class WriteMetadataPdfBuilderTest extends AbstractBuilderTestCase
{
private const PDF_DOCUMENTS_DIR = 'pdf';

public function testEndpointIsCorrect(): void
{
$this->gotenbergClient
->expects($this->once())
->method('call')
->with(
$this->equalTo('/forms/pdfengines/metadata/write'),
$this->anything(),
$this->anything(),
)
;

$this->getWriteMetadataPdfBuilder()
->files(
self::PDF_DOCUMENTS_DIR.'/simple_pdf.pdf',
self::PDF_DOCUMENTS_DIR.'/simple_pdf_1.pdf',
)
->generate()
;
}

public static function configurationIsCorrectlySetProvider(): \Generator
{
yield 'metadata' => ['metadata', ['Author' => 'SensioLabs'], [
'metadata' => '{"Author":"SensioLabs"}',
]];
}

/**
* @param array<mixed> $expected
*/
#[DataProvider('configurationIsCorrectlySetProvider')]
public function testConfigurationIsCorrectlySet(string $key, mixed $value, array $expected): void
{
$builder = $this->getWriteMetadataPdfBuilder();
$builder->setConfigurations([
$key => $value,
]);
$builder->files(
self::PDF_DOCUMENTS_DIR.'/simple_pdf.pdf',
self::PDF_DOCUMENTS_DIR.'/simple_pdf_1.pdf',
);

self::assertEquals($expected, $builder->getMultipartFormData()[0]);
}

public function testRequiredFormData(): void
{
$builder = $this->getWriteMetadataPdfBuilder();

$this->expectException(MissingRequiredFieldException::class);
$this->expectExceptionMessage('At least one PDF file is required');

$builder->getMultipartFormData();
}

private function getWriteMetadataPdfBuilder(): WriteMetadataPdfBuilder
{
return new WriteMetadataPdfBuilder($this->gotenbergClient, self::$assetBaseDirFormatter);
}
}