Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
85 changes: 85 additions & 0 deletions .github/actions/setup-bernard-ledit/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
name: Build bernard-ledit
description: Build and load the PHP extension from the refacto branch
inputs:
php-version:
description: PHP version used by the runner
required: true
runs:
using: composite
steps:
- uses: ./bernard-ledit/.github/actions/php-windows-toolchain
if: runner.os == 'Windows'
id: windows-toolchain
with:
php-version: ${{ inputs.php-version }}

- uses: ilammy/msvc-dev-cmd@v1
if: runner.os == 'Windows'
with:
arch: x64
toolset: ${{ steps.windows-toolchain.outputs.msvc }}

- uses: ./bernard-ledit/.github/actions/setup-libheif

- uses: ./bernard-ledit/.github/actions/setup-clang
if: runner.os == 'Linux'

- uses: ./bernard-ledit/.github/actions/setup-pdfium
with:
target: ${{ runner.os == 'Windows' && steps.windows-toolchain.outputs.pdfium-target || '' }}

- uses: dtolnay/rust-toolchain@1.99.0
if: runner.os != 'Windows'

- uses: dtolnay/rust-toolchain@nightly
if: runner.os == 'Windows'

- uses: Swatinem/rust-cache@v2
with:
workspaces: bernard-ledit
key: php-${{ inputs.php-version }}

- name: Build the PHP extension
if: runner.os != 'Windows'
shell: bash
working-directory: bernard-ledit
run: cargo build -p bernard-ledit-php

- name: Build the PHP extension (Windows)
if: runner.os == 'Windows'
shell: pwsh
working-directory: bernard-ledit
run: |
cargo +nightly build -p bernard-ledit-php
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

- name: Configure the PHP extension
shell: bash
run: |
php -r '
$name = match (PHP_OS_FAMILY) {
"Windows" => "bernard_ledit_php.dll",
"Darwin" => "libbernard_ledit_php.dylib",
default => "libbernard_ledit_php.so",
};
$extension = realpath("bernard-ledit/target/debug/" . $name);
if ($extension === false) {
throw new RuntimeException("Built Bernard extension not found");
}
$dir = getenv("RUNNER_TEMP") . DIRECTORY_SEPARATOR . "bernard-php-ini";
if (!is_dir($dir) && !mkdir($dir, 0777, true)) {
throw new RuntimeException("Cannot create PHP configuration directory");
}
if (file_put_contents($dir . "/bernard.ini", "log_errors=On\nextension=\"" . str_replace("\\", "/", $extension) . "\"\n") === false) {
throw new RuntimeException("Cannot write Bernard PHP configuration");
}
$scan = getenv("PHP_INI_SCAN_DIR");
if (file_put_contents(getenv("GITHUB_ENV"), "PHP_INI_SCAN_DIR=" . ($scan === false ? "" : $scan) . PATH_SEPARATOR . $dir . PHP_EOL, FILE_APPEND) === false) {
throw new RuntimeException("Cannot set PHP_INI_SCAN_DIR");
}
'

- name: Verify the PHP extension
shell: bash
run: |
php -r 'if (!extension_loaded("bernard_ledit")) { throw new RuntimeException("Bernard extension did not load"); } BernardLedit\Pdf\PdfDocument::create(); echo "bernard_ledit ", phpversion("bernard_ledit"), PHP_EOL;'
4 changes: 4 additions & 0 deletions .github/workflows/_test-cli.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}

- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3

Expand Down
25 changes: 9 additions & 16 deletions .github/workflows/_test-integrations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}
extensions: curl, fileinfo, json
tools: pie

- name: Install bernard-ledit extension
run: bash tools/install-bernard-ledit.sh
- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3
Expand Down Expand Up @@ -76,10 +76,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}
extensions: curl, fileinfo, json
tools: pie

- name: Install bernard-ledit extension
run: bash tools/install-bernard-ledit.sh
- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3
Expand Down Expand Up @@ -108,17 +108,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}
extensions: curl, fileinfo, json
tools: pie

- name: Install bernard-ledit extension (Windows)
shell: pwsh
run: |
pie install "mindee/bernard-ledit"
if (-not (php -m | Select-String -Pattern '^bernard_ledit$' -Quiet)) {
Write-Error "bernard_ledit did not load"
exit 1
}
php -r 'echo "bernard_ledit ", phpversion("bernard_ledit"), PHP_EOL;'
- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/_test-smoke.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}

- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3

Expand Down
18 changes: 3 additions & 15 deletions .github/workflows/_test-units.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,22 +79,10 @@ jobs:
with:
php-version: ${{ matrix.php-version }}
extensions: curl, fileinfo, json
tools: pie

- name: Install bernard-ledit extension
if: runner.os != 'Windows'
run: bash tools/install-bernard-ledit.sh

- name: Install bernard-ledit extension (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
pie install "mindee/bernard-ledit"
if (-not (php -m | Select-String -Pattern '^bernard_ledit$' -Quiet)) {
Write-Error "bernard_ledit did not load"
exit 1
}
php -r 'echo "bernard_ledit ", phpversion("bernard_ledit"), PHP_EOL;'
- uses: ./.github/actions/setup-bernard-ledit
with:
php-version: ${{ matrix.php-version }}

- name: Install dependencies
uses: ramsey/composer-install@v3
Expand Down
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[submodule "tests/resources"]
path = tests/resources
url = git@github.com:mindee/client-lib-test-data.git
[submodule "bernard-ledit"]
path = bernard-ledit
url = https://github.com/mindee/bernard-ledit.git
branch = refacto
18 changes: 16 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,21 @@ PDF and image operations (page cutting and merging, compression, crop and split
on [bernard-ledit](https://github.com/mindee/bernard-ledit), a native PHP extension. It is optional for users, but you
need it to run the full unit test suite.

Refer to the version constraint in `composer.json`.
CI builds the extension from the `bernard-ledit` submodule. To use the same build locally, follow
the [Bernard build prerequisites](bernard-ledit/README.md#development), then run:

```bash
cd bernard-ledit
cargo build -p bernard-ledit-php
cd ..
```

Load the built extension in `php.ini` before you run the SDK tests. See the
[PHP binding instructions](bernard-ledit/bindings/php/README.md#installation) for the
extension filename. To use a newer commit from `refacto`, update the submodule and commit its
new revision.

For a released extension, refer to the version constraint in `composer.json`.

Install the pinned version with [PIE](https://github.com/php/pie):

Expand Down Expand Up @@ -137,7 +151,7 @@ To move the SDK to a new bernard-ledit version:

1. Change the version in the `conflict` line of `composer.json`.
2. Run `composer setup:bernard-ledit` and `composer update:bernard-ledit-stubs`, then commit the updated stubs.
3. Run the tests: CI installs the new version on its own.
3. Run the tests. CI builds the extension from the pinned submodule commit.

### Running the tests

Expand Down
1 change: 1 addition & 0 deletions bernard-ledit
Submodule bernard-ledit added at cb09a3
24 changes: 5 additions & 19 deletions src/Image/ExtractedImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Exception;

use function BernardLedit\Image\decode;
use function BernardLedit\Common\formatFromExtension;
use function sprintf;
use function strlen;

Expand Down Expand Up @@ -52,8 +53,10 @@ public function __construct(public string $buffer, public string $filename, prot
public function writeToFile(string $outputPath, ?string $format = null, ?int $quality = null): void
{
$imagePath = $outputPath . DIRECTORY_SEPARATOR . $this->filename;
$encodedFormat = self::getEncodedImageFormat($format ?? $this->saveFormat);
if (null === $quality && $encodedFormat === self::getEncodedImageFormat($this->saveFormat)) {
$extension = pathinfo($this->filename, PATHINFO_EXTENSION);
$formatToEncode = $format ?? ('' !== $extension ? $extension : $this->saveFormat);
$encodedFormat = formatFromExtension($formatToEncode);
if (null === $quality && $encodedFormat === formatFromExtension($this->saveFormat)) {
self::writeBytes($imagePath, $this->buffer);
return;
}
Expand All @@ -71,23 +74,6 @@ public function asInputSource(): BytesInput
return new BytesInput($this->buffer, $this->filename);
}

/**
* Get the encoded image format, as understood by bernard_ledit.
*
* @param string $saveFormat Format to save the file as.
* @return string Encoded image format.
*/
public static function getEncodedImageFormat(string $saveFormat): string
{
return match (strtolower($saveFormat)) {
'png' => 'png',
'bmp', => 'bmp',
'gif' => 'gif',
'webp' => 'webp',
default => 'jpeg',
};
}

/**
* Writes bytes to a file, and fails if they weren't all written.
*
Expand Down
4 changes: 2 additions & 2 deletions src/Image/ImageCompressor.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Mindee\Error\MindeeImageException;
use Mindee\Error\MindeeUnhandledException;

use function BernardLedit\Image\compress as compressImage;
use function BernardLedit\Image\compressToJpeg as compressImage;

/**
* Image compressor class to handle image compression.
Expand All @@ -36,7 +36,7 @@ public static function compress(
): string {
DependencyChecker::requireBernardLedit();
try {
[$bytes] = compressImage($inputImage, $quality, $maxWidth, $maxHeight);
[$bytes] = compressImage($inputImage, $quality, null, $maxWidth, $maxHeight);
return $bytes;
} catch (Exception $e) {
throw new MindeeImageException("Image compression failed.", ErrorCode::FILE_OPERATION_ABORTED, $e);
Expand Down
26 changes: 20 additions & 6 deletions src/Image/ImageExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@

use BernardLedit\Image\Image;
use BernardLedit\Image\ImageException;
use BernardLedit\Image\ImageExtractException;
use BernardLedit\Pdf\PdfExtractException;
use BernardLedit\Pdf\PdfDocument;
use BernardLedit\Pdf\PdfiumException;
use InvalidArgumentException;
use Mindee\Dependency\DependencyChecker;
Expand All @@ -17,10 +16,11 @@
use Mindee\Geometry\Point;
use Mindee\Geometry\Polygon;
use Mindee\Input\LocalInputSource;
use Mindee\Pdf\PdfUtils;
use ValueError;

use function BernardLedit\Common\formatFromExtension;
use function BernardLedit\Image\guessFormat;
use function BernardLedit\Image\extractFromPolygons;
use function count;
use function sprintf;
use function is_array;
Expand Down Expand Up @@ -204,8 +204,22 @@ protected function cropPolygons(array $polygons, int $pageIndex): array
{
$pairs = array_map(static::polygonToPairs(...), $polygons);
try {
return extractFromPolygons($this->sourceData, $pageIndex, $pairs, $this->pdfDpi);
} catch (ImageException|ImageExtractException|PdfExtractException|PdfiumException|ValueError $e) {
if ($this->inputSource->isPdf()) {
$pdf = new PdfDocument($this->sourceData);
try {
$sourceImage = $pdf->getPage($pageIndex)->render($this->pdfDpi / 72.0);
} finally {
PdfUtils::closeQuietly($pdf);
}
} else {
$sourceImage = new Image($this->sourceData);
}

return array_map(
static fn(array $polygon): Image => $sourceImage->cropPolygon($polygon),
$pairs
);
} catch (ImageException|PdfiumException|ValueError $e) {
throw new MindeeImageException($e->getMessage(), $e->getCode(), $e);
}
}
Expand All @@ -223,7 +237,7 @@ protected function encodeCrop(
string $format
): ExtractedImage {
try {
$data = $crop->encode(ExtractedImage::getEncodedImageFormat($format), self::CROP_QUALITY);
$data = $crop->encode(formatFromExtension($format), self::CROP_QUALITY);
} catch (ImageException|ValueError $e) {
throw new MindeeImageException($e->getMessage(), $e->getCode(), $e);
}
Expand Down
8 changes: 4 additions & 4 deletions src/Input/LocalInputSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
use function BernardLedit\Pdf\applyPageOptions as nativeApplyPageOptions;
use function BernardLedit\Pdf\fixPdf as nativeFixPdf;
use function in_array;
use function BernardLedit\Image\compress as compressImage;
use function BernardLedit\Pdf\compress as compressPdf;
use function BernardLedit\Image\compressToJpeg as compressImage;
use function BernardLedit\Pdf\compressToJpeg as compressPdf;

/**
* List of allowed mime types for document parsing.
Expand Down Expand Up @@ -284,7 +284,7 @@ public function compress(
if ($this->isPdf()) {
$compressed = compressPdf($bytes, $quality, $optimize, $dpi);
} else {
[$compressed] = compressImage($bytes, $quality, $maxWidth, $maxHeight, $optimize);
[$compressed] = compressImage($bytes, $quality, $optimize, $maxWidth, $maxHeight);
if ($compressed !== $bytes) {
$this->fileMimetype = 'image/jpeg';
$extension = strtolower(pathinfo($this->fileName, PATHINFO_EXTENSION));
Expand Down Expand Up @@ -353,7 +353,7 @@ public function applyPageOptions(?PageOptions $pageOptions): void
return;
}
try {
$documentBytes = $document->asBytes();
$documentBytes = $document->toBytes();
$this->saveBytesAsFile($documentBytes);
$this->pageCount = $document->getPageCount();
} catch (Exception $e) {
Expand Down
4 changes: 3 additions & 1 deletion src/Pdf/ExtractedPdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use Mindee\Error\MindeeUnhandledException;
use Mindee\Input\BytesInput;

use function BernardLedit\Common\formatFromExtension;

use const DIRECTORY_SEPARATOR;

/**
Expand Down Expand Up @@ -71,7 +73,7 @@ public function writeToFile(string $outputPath): void
$pdfPath = $outputPath;
}
}
if (!str_ends_with(strtolower($pdfPath), 'pdf')) {
if ('PDF' !== formatFromExtension(pathinfo($pdfPath, PATHINFO_EXTENSION))) {
$pdfPath .= '.pdf';
}
file_put_contents($pdfPath, $this->pdfBytes);
Expand Down
Loading
Loading