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
5 changes: 4 additions & 1 deletion .github/workflows/_static-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,7 @@ jobs:
- name: Run lint
run: |
composer lint


- name: Run PHPStan
run: |
composer phpstan
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.38",
"phpunit/phpunit": "^9.6",
"madewithlove/license-checker": "^v1.0"
"madewithlove/license-checker": "^v1.0",
"phpstan/phpstan": "^2.1"
},
"suggest": {
"ext-imagick": "Required for PDF rasterization and image processing features",
Expand All @@ -33,6 +34,7 @@
],
"scripts": {
"lint": "php-cs-fixer fix --dry-run --diff",
"phpstan": "phpstan analyse src --level 6",
"format": "php-cs-fixer fix"
}
}
1 change: 1 addition & 0 deletions src/Dependency/DependencyChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public static function isImageMagickPolicyAllowed(): void
$imagick = new Imagick();
try {
$imagick->readImage(
/** @phpstan-ignore-next-line */
TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg"
);
} catch (Exception $e) {
Expand Down
22 changes: 11 additions & 11 deletions src/Error/MindeeHttpException.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@ class MindeeHttpException extends MindeeException
*/
public int $statusCode;
/**
* @var string|mixed|null API code as sent by the server.
* @var string|null API code as sent by the server.
*/
public ?string $apiCode;
/**
* @var mixed|null API details field as sent by the server.
* @var string|array<string,mixed>|null API details field as sent by the server.
*/
public $apiDetails;
public mixed $apiDetails;
/**
* @var string|mixed|null API message field as sent by the server.
* @var string|array<string,mixed>|null API message field as sent by the server.
*/
public ?string $apiMessage;
public mixed $apiMessage;

/**
* @param array $httpError Array containing the error data.
* @param array<string,mixed> $httpError Array containing the error data.
* @param string $url Remote URL the error was found on.
* @param integer $code Error code.
*/
Expand Down Expand Up @@ -71,11 +71,11 @@ public function __construct(array $httpError, string $url, int $code)
/**
* Builds an appropriate error object from the server reply.
*
* @param array|string $response Parsed server response.
* @param array<string,mixed>|string|null $response Parsed server response.
* @return string[]
* @throws MindeeException Throws if the error itself can't be built.
*/
public static function createErrorObj($response): array
public static function createErrorObj(mixed $response): array
{
if (is_string($response)) {
if (str_contains($response, 'Maximum pdf pages')) {
Expand Down Expand Up @@ -125,7 +125,7 @@ public static function createErrorObj($response): array
) {
return $response['api_request']['error'];
}
if (!$response) {
if (!isset($response)) {
throw new MindeeException(
"Request to the API failed.",
ErrorCode::API_REQUEST_FAILED
Expand All @@ -139,9 +139,9 @@ public static function createErrorObj($response): array

/**
* @param string $url Remote URL the error was found on.
* @param array|string|boolean $response Raw server response.
* @param array<string,mixed>|string|boolean $response Raw server response.
*/
public static function handleError(string $url, $response): self
public static function handleError(string $url, mixed $response): self
{
if (is_array($response)) {
$dataResponse = $response['data'] ?? ["data" => null];
Expand Down
3 changes: 2 additions & 1 deletion src/Error/MindeeV2HttpException.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Mindee\Error;

use Mindee\V2\Parsing\ErrorItem;
use Mindee\V2\Parsing\ErrorResponse;

/**
Expand All @@ -29,7 +30,7 @@ class MindeeV2HttpException extends MindeeException
*/
public ?string $errorCode;
/**
* @var array List of associated errors.
* @var array<ErrorItem> List of associated errors.
*/
public array $errors;

Expand Down
2 changes: 1 addition & 1 deletion src/Extraction/ExtractedImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function writeToFile(string $outputPath, ?string $format = null, int $qua
$quality = min(100, max(0, $quality));
if ('png' === $format) {
$finalQuality = round($quality * 0.09);
$this->image->setOption('png:compression-level', $finalQuality);
$this->image->setOption('png:compression-level', (string) $finalQuality);
} elseif (in_array($format, ['jpg', 'jpeg'], true)) {
$this->image->setImageCompression(Imagick::COMPRESSION_JPEG);
}
Expand Down
24 changes: 12 additions & 12 deletions src/Extraction/ImageExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

namespace Mindee\Extraction;

use Exception;
use Mindee\Dependency\DependencyChecker;
use Mindee\Error\ErrorCode;
use Mindee\Error\MindeeGeometryException;
use Mindee\Error\MindeeImageException;
use Mindee\Error\MindeePDFException;
use Mindee\Geometry\BBox;
use Mindee\Geometry\BBoxUtils;
use Mindee\Geometry\Point;
use Mindee\Geometry\Polygon;
use Mindee\Input\LocalInputSource;
use Mindee\V1\Parsing\Standard\BaseField;
Expand Down Expand Up @@ -129,11 +131,11 @@ public function getPageCount(): int
/**
* Extract multiple images on a given page from a list of fields having position data.
*
* @param array $fields List of Fields to extract.
* @param array<BaseField<mixed>> $fields List of Fields to extract.
* @param integer $pageIndex The page index to extract, begins at 0.
* @param null|string $outputName The base output filename, must have an image extension.
*
* @return array a list of extracted images
* @return array<ExtractedImage> a list of extracted images
*/
public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array
{
Expand All @@ -144,12 +146,12 @@ public function extractImagesFromPage(array $fields, int $pageIndex, ?string $ou
/**
* Extracts images from a page.
*
* @param array $polygons List of polygons to extract.
* @param array<Polygon|array<Point>> $polygons List of polygons to extract.
* @param integer $pageIndex The page index to extract, begins at 0.
* @param null|string $filenamePrefix Output filename prefix.
* @param null|string $format Save format for extracted images. Defaults to the original format.
*
* @return array an array of created images
* @return array<ExtractedImage> An array of created images
* @throws MindeeImageException Throws if the image can't be processed.
*/
public function extractPolygonsFromPage(
Expand All @@ -173,7 +175,7 @@ public function extractPolygonsFromPage(
$saveFormat
);
}
} catch (ImagickException $e) {
} catch (Exception $e) {
throw new MindeeImageException($e->getMessage(), $e->getCode(), $e);
}

Expand Down Expand Up @@ -205,16 +207,15 @@ public function extractPolygonFromPage(
} catch (ImagickException $e) {
throw new MindeeImageException($e->getMessage(), $e->getCode(), $e);
}
$filename ??= $this->filename;
$format ??= $this->saveFormat;
$filename ??= sprintf('%s.%s_page%d-%d.%s', $filename, $format, $pageIndex, $index, $format);
$filename ??= sprintf('%s_page%d-%d.%s', $this->filename, $pageIndex, $index, $format);
return new ExtractedImage($extractedImageData, $filename, $format, $pageIndex, $index);
}

/**
* Extracts a single image from a Position field.
*
* @param BaseField $field The field to extract.
* @param BaseField<mixed> $field The field to extract.
* @param integer $pageIndex The page index to extract, begins at 0.
* @param integer $index The index to use for naming the extracted image.
* @param string $filename The output filename.
Expand Down Expand Up @@ -264,16 +265,15 @@ public function getInputSource(): LocalInputSource
/**
* Extracts images from a page.
*
* @param array $fields List of Fields to extract.
* @param array<BaseField<mixed>> $fields List of Fields to extract.
* @param integer $pageIndex The page index to extract, begins at 0.
* @param string $outputName Name of the created file.
* @param string $format The output format.
*
* @return array an array of created images
* @return array<ExtractedImage> An array of created images
*/
protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array
{
$format ??= $this->saveFormat;
$extractedImages = [];

$i = 0;
Expand Down Expand Up @@ -316,7 +316,7 @@ protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): Imagi
* Splits the filename into name and extension.
*
* @param string $filename Name of the file.
* @return array An array containing the name and extension of the file.
* @return array{0: string, 1: string} An array containing the name and extension of the file.
*/
protected static function splitNameStrict(string $filename): array
{
Expand Down
4 changes: 2 additions & 2 deletions src/Extraction/PDFExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function getPageCount(): int
/**
* Extracts sub-documents from the source document using list of page indexes.
*
* @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep.
* @param array<array<integer>>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep.
*
* @return ExtractedPDF[] list of extracted documents
*
Expand Down Expand Up @@ -141,7 +141,7 @@ public function extractSubDocuments(mixed $pageIndexes): array
/**
* Extracts invoices as complete PDFs from the document.
*
* @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep.
* @param array<array<integer>>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep.
* @param boolean $strict Whether to trust confidence scores or not.
*
* @return ExtractedPDF[] a list of extracted invoices
Expand Down
4 changes: 2 additions & 2 deletions src/Geometry/BBox.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ public function getMaxY(): float
/**
* Extends the BBox with the provided points.
*
* @param array|Polygon $points Series of points to add to the BBox.
* @param array<Point>|Polygon $points Series of points to add to the BBox.
*/
public function extendWith(Polygon|array $points): void
public function extendWith(mixed $points): void
{
if ($points instanceof Polygon) {
$sequence = $points->getCoordinates();
Expand Down
24 changes: 10 additions & 14 deletions src/Geometry/BBoxUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,27 @@ public static function generateBBoxFromPolygon(Polygon $polygon): ?BBox
/**
* Generates a BBox from an array of polygons. Returns null if no polygons are provided.
*
* @param array $polygons Series of polygons to get the BBox of.
* @param array<Polygon|null> $polygons Series of polygons to get the BBox of.
*/
public static function generateBBoxFromPolygons(array $polygons): ?BBox
{
if (!$polygons) {
return null;
}
$merged = $polygons[0];
$bboxes = [];

foreach ($polygons as $polygon) {
if ($polygon && $merged !== $polygon) {
$merged = PolygonUtils::merge($merged, $polygon);
if (null === $polygon || !$polygon->getCoordinates()) {
continue;
}

$bboxes[] = self::generateBBoxFromPolygon($polygon);
}
return new BBox(
$merged->getMinX(),
$merged->getMaxX(),
$merged->getMinY(),
$merged->getMaxY(),
);

return self::mergeBBoxes($bboxes);
}

/**
* Merges an array of bboxes.
*
* @param array $bboxes BBoxes to merge.
* @param array<BBox> $bboxes BBoxes to merge.
*/
public static function mergeBBoxes(array $bboxes): ?BBox
{
Expand Down
14 changes: 10 additions & 4 deletions src/Geometry/MinMaxUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ class MinMaxUtils
/**
* Retrieves the upper and lower bounds of the y-axis from an array of points.
*
* @param array $points An array of points.
* @param array<Point>|Polygon $points An array of points.
* @throws MindeeGeometryException Throws if the provided array is too small.
*/
public static function getMinMaxY(array $points): MinMax
public static function getMinMaxY(mixed $points): MinMax
{
if ($points instanceof Polygon) {
$points = $points->getCoordinates();
}
if (count($points) < 1) {
throw new MindeeGeometryException(
'The provided point array must have at least 1 point to calculate the Y bounds.',
Expand All @@ -38,11 +41,14 @@ public static function getMinMaxY(array $points): MinMax
/**
* Retrieves the upper and lower bounds of the x-axis from an array of points.
*
* @param array $points An array of points.
* @param array<Point>|Polygon $points An array of points.
* @throws MindeeGeometryException Throws if the provided array is too small.
*/
public static function getMinMaxX(array $points): MinMax
public static function getMinMaxX(mixed $points): MinMax
{
if ($points instanceof Polygon) {
$points = $points->getCoordinates();
}
if (count($points) < 1) {
throw new MindeeGeometryException(
'The provided point array must have at least 1 point to calculate the X bounds.',
Expand Down
11 changes: 4 additions & 7 deletions src/Geometry/Point.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
namespace Mindee\Geometry;

use ArrayAccess;
use BadMethodCallException;
use InvalidArgumentException;

/**
* Representation of the coordinates of a point.
*
* @implements ArrayAccess<int, float>
*/
class Point implements ArrayAccess
{
Expand Down Expand Up @@ -101,12 +104,6 @@ public function offsetSet($offset, $value): void
*/
public function offsetUnset($offset): void
{
if ($offset === 0) {
$this->x = null;
} elseif ($offset === 1) {
$this->y = null;
} else {
throw new InvalidArgumentException("Use 0 for X or 1 for Y");
}
throw new BadMethodCallException("Cannot unset coordinates of a Point.");
}
}
6 changes: 3 additions & 3 deletions src/Geometry/Polygon.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class Polygon
{
/**
* @var Point[]|null Vertices of the polygon.
* @var array<Point>|null Vertices of the polygon.
*/
public ?array $coordinates;

Expand All @@ -27,7 +27,7 @@ class Polygon
private MinMax $minMaxX;

/**
* @param array|null $coordinates Coordinates of the polygon as a set of Points.
* @param array<array<float|integer>>|array<Point>|null $coordinates Coordinates of the polygon as a set of Points.
*/
public function __construct(?array $coordinates = null)
{
Expand Down Expand Up @@ -146,7 +146,7 @@ public function isEmpty(): bool

/**
* Retrieves the coordinates of the polygon.
*
* @return array<Point>|null Coordinates of the polygon.
*/
public function getCoordinates(): ?array
{
Expand Down
Loading
Loading