diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 8aaf8407..510b2452 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -34,4 +34,7 @@ jobs: - name: Run lint run: | composer lint - + + - name: Run PHPStan + run: | + composer phpstan diff --git a/composer.json b/composer.json index a8315df5..96a7daaf 100644 --- a/composer.json +++ b/composer.json @@ -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", @@ -33,6 +34,7 @@ ], "scripts": { "lint": "php-cs-fixer fix --dry-run --diff", + "phpstan": "phpstan analyse src --level 6", "format": "php-cs-fixer fix" } } diff --git a/src/Dependency/DependencyChecker.php b/src/Dependency/DependencyChecker.php index c374e933..cde460a1 100644 --- a/src/Dependency/DependencyChecker.php +++ b/src/Dependency/DependencyChecker.php @@ -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) { diff --git a/src/Error/MindeeHttpException.php b/src/Error/MindeeHttpException.php index f2f33d46..71c8961f 100644 --- a/src/Error/MindeeHttpException.php +++ b/src/Error/MindeeHttpException.php @@ -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|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|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 $httpError Array containing the error data. * @param string $url Remote URL the error was found on. * @param integer $code Error code. */ @@ -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|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')) { @@ -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 @@ -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|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]; diff --git a/src/Error/MindeeV2HttpException.php b/src/Error/MindeeV2HttpException.php index 22766176..75f23d01 100644 --- a/src/Error/MindeeV2HttpException.php +++ b/src/Error/MindeeV2HttpException.php @@ -4,6 +4,7 @@ namespace Mindee\Error; +use Mindee\V2\Parsing\ErrorItem; use Mindee\V2\Parsing\ErrorResponse; /** @@ -29,7 +30,7 @@ class MindeeV2HttpException extends MindeeException */ public ?string $errorCode; /** - * @var array List of associated errors. + * @var array List of associated errors. */ public array $errors; diff --git a/src/Extraction/ExtractedImage.php b/src/Extraction/ExtractedImage.php index 1725f366..36dde536 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Extraction/ExtractedImage.php @@ -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); } diff --git a/src/Extraction/ImageExtractor.php b/src/Extraction/ImageExtractor.php index 498c1df7..670a05cb 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Extraction/ImageExtractor.php @@ -4,6 +4,7 @@ namespace Mindee\Extraction; +use Exception; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeGeometryException; @@ -11,6 +12,7 @@ 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; @@ -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> $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 a list of extracted images */ public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array { @@ -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> $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 An array of created images * @throws MindeeImageException Throws if the image can't be processed. */ public function extractPolygonsFromPage( @@ -173,7 +175,7 @@ public function extractPolygonsFromPage( $saveFormat ); } - } catch (ImagickException $e) { + } catch (Exception $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } @@ -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 $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. @@ -264,16 +265,15 @@ public function getInputSource(): LocalInputSource /** * Extracts images from a page. * - * @param array $fields List of Fields to extract. + * @param array> $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 An array of created images */ protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array { - $format ??= $this->saveFormat; $extractedImages = []; $i = 0; @@ -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 { diff --git a/src/Extraction/PDFExtractor.php b/src/Extraction/PDFExtractor.php index a11f7fb1..34d1c4c2 100644 --- a/src/Extraction/PDFExtractor.php +++ b/src/Extraction/PDFExtractor.php @@ -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>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * * @return ExtractedPDF[] list of extracted documents * @@ -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>|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 diff --git a/src/Geometry/BBox.php b/src/Geometry/BBox.php index e6ebac3c..da0399d8 100644 --- a/src/Geometry/BBox.php +++ b/src/Geometry/BBox.php @@ -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|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(); diff --git a/src/Geometry/BBoxUtils.php b/src/Geometry/BBoxUtils.php index af3a4ec6..b089f996 100644 --- a/src/Geometry/BBoxUtils.php +++ b/src/Geometry/BBoxUtils.php @@ -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 $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 $bboxes BBoxes to merge. */ public static function mergeBBoxes(array $bboxes): ?BBox { diff --git a/src/Geometry/MinMaxUtils.php b/src/Geometry/MinMaxUtils.php index 55f30026..e4b1f8c8 100644 --- a/src/Geometry/MinMaxUtils.php +++ b/src/Geometry/MinMaxUtils.php @@ -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|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.', @@ -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|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.', diff --git a/src/Geometry/Point.php b/src/Geometry/Point.php index 99c93529..57906202 100644 --- a/src/Geometry/Point.php +++ b/src/Geometry/Point.php @@ -5,10 +5,13 @@ namespace Mindee\Geometry; use ArrayAccess; +use BadMethodCallException; use InvalidArgumentException; /** * Representation of the coordinates of a point. + * + * @implements ArrayAccess */ class Point implements ArrayAccess { @@ -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."); } } diff --git a/src/Geometry/Polygon.php b/src/Geometry/Polygon.php index b458eec0..75aad681 100644 --- a/src/Geometry/Polygon.php +++ b/src/Geometry/Polygon.php @@ -12,7 +12,7 @@ class Polygon { /** - * @var Point[]|null Vertices of the polygon. + * @var array|null Vertices of the polygon. */ public ?array $coordinates; @@ -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|null $coordinates Coordinates of the polygon as a set of Points. */ public function __construct(?array $coordinates = null) { @@ -146,7 +146,7 @@ public function isEmpty(): bool /** * Retrieves the coordinates of the polygon. - * + * @return array|null Coordinates of the polygon. */ public function getCoordinates(): ?array { diff --git a/src/Geometry/PolygonUtils.php b/src/Geometry/PolygonUtils.php index 02297b28..5dd4c149 100644 --- a/src/Geometry/PolygonUtils.php +++ b/src/Geometry/PolygonUtils.php @@ -17,10 +17,13 @@ abstract class PolygonUtils /** * Gets the centroid (Point) of a set of points. * - * @param array $vertices Array of points. + * @param array|Polygon $vertices Array of points. */ - public static function getCentroid(array $vertices): Point + public static function getCentroid(mixed $vertices): Point { + if ($vertices instanceof Polygon) { + $vertices = $vertices->getCoordinates(); + } $verticesSum = count($vertices); $xSum = 0.0; @@ -45,7 +48,7 @@ public static function getCentroid(array $vertices): Point public static function compareOnY(Polygon $polygon1, Polygon $polygon2): int { $sort = ($polygon1->getMinY() - $polygon2->getMinY()); - if ($sort === 0) { + if ($sort === 0.0) { return 0; } return $sort < 0 ? -1 : 1; @@ -106,15 +109,15 @@ public static function createBoundingBoxFrom(Polygon $base, ?Polygon $target = n /** * Generates a quadrilateral Polygon from a given prediction. * - * @param array $prediction Raw prediction array. + * @param array $rawResponse Raw prediction array. * @throws MindeeGeometryException Throws if the polygon isn't a quadrilateral. */ - public static function quadrilateralFromPrediction(array $prediction): Polygon + public static function quadrilateralFromPrediction(array $rawResponse): Polygon { - if (count($prediction) !== 4) { + if (count($rawResponse) !== 4) { throw new MindeeGeometryException('Prediction must have exactly 4 points.'); } - return new Polygon($prediction); + return new Polygon($rawResponse); } /** diff --git a/src/Image/ImageUtils.php b/src/Image/ImageUtils.php index d8330892..43fb6837 100644 --- a/src/Image/ImageUtils.php +++ b/src/Image/ImageUtils.php @@ -21,7 +21,7 @@ class ImageUtils { /** - * @param mixed $image Image handle. + * @param Imagick|SplFileObject|CURLFile|string|resource $image Image handle. * @return Imagick A valid Imagick handle, CURLFile, SplFileObject or resource. * The resulting image is formatted to jpeg. * @throws MindeeImageException Throws if something goes wrong during image conversion. @@ -31,7 +31,6 @@ public static function toMagickImage(mixed $image): Imagick try { if ($image instanceof Imagick) { $imagickHandle = $image; - $imagickHandle->setImageFormat('jpeg'); } elseif ($image instanceof SplFileObject) { $imagickHandle = new Imagick(); $imagickHandle->readImage($image->getRealPath()); @@ -43,7 +42,14 @@ public static function toMagickImage(mixed $image): Imagick $imagickHandle->readImage($image); } elseif (is_resource($image)) { $imagickHandle = new Imagick(); - $imagickHandle->readImageBlob($image); + rewind($image); + $imageData = stream_get_contents($image); + + if ($imageData === false) { + throw new MindeeImageException('Failed to read from image resource.'); + } + + $imagickHandle->readImageBlob($imageData); } else { throw new MindeeImageException( 'Input image must be a SplFileObject, path, resource or Imagick handle.' diff --git a/src/Input/Base64Input.php b/src/Input/Base64Input.php index e38a2c5f..cadbcbe3 100644 --- a/src/Input/Base64Input.php +++ b/src/Input/Base64Input.php @@ -35,7 +35,7 @@ public function __construct(string $strBase64, string $fileName) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/BytesInput.php b/src/Input/BytesInput.php index a5084b16..bc5ad5b4 100644 --- a/src/Input/BytesInput.php +++ b/src/Input/BytesInput.php @@ -35,7 +35,7 @@ public function __construct(string $fileBytes, string $fileName) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/FileInput.php b/src/Input/FileInput.php index 289f2aef..6436bd32 100644 --- a/src/Input/FileInput.php +++ b/src/Input/FileInput.php @@ -33,21 +33,11 @@ public function __construct(mixed &$file) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { $fileContents = fread($this->file, filesize($this->filePath)); return [$this->fileName, $fileContents]; } - - /** - * Returns the reference to the file object. Only used for testing purposes. - * - * @return mixed - */ - public function getFilePtr() - { - return $this->file; - } } diff --git a/src/Input/LocalInputSource.php b/src/Input/LocalInputSource.php index 9016e8b9..968a29b4 100644 --- a/src/Input/LocalInputSource.php +++ b/src/Input/LocalInputSource.php @@ -163,7 +163,7 @@ private function saveBytesAsFile(string $fileBytes): void /** * Create a new PDF from pages and set it as the main file object. - * @param array $pageNumbers Array of page numbers to add to the newly created PDF. + * @param array $pageNumbers Array of page numbers to add to the newly created PDF. * @throws MindeePDFException Throws if the pdf file can't be processed. */ public function mergePDFPages(array $pageNumbers): void @@ -222,7 +222,7 @@ public function isPDFEmpty(int $threshold = 1024): bool /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/LocalResponse.php b/src/Input/LocalResponse.php index 62805ef3..e2e2a0d6 100644 --- a/src/Input/LocalResponse.php +++ b/src/Input/LocalResponse.php @@ -23,49 +23,41 @@ class LocalResponse private $file; /** - * @param mixed $inputFile A string, path or file-like object to load as a local response. + * @param resource|string|array $inputFile A string, path or file-like object to load as a local response. * @throws MindeeException Throws if the input file isn't acceptable. */ public function __construct(mixed $inputFile) { - if (is_resource($inputFile) && get_resource_type($inputFile) === 'file') { - $content = fread($inputFile, filesize($inputFile)); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_resource($inputFile) && get_resource_type($inputFile) === 'stream') { - $content = stream_get_contents($inputFile); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_string($inputFile) && file_exists($inputFile)) { - $content = file_get_contents($inputFile); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); + if (is_resource($inputFile)) { + $resourceType = get_resource_type($inputFile); + if ($resourceType === 'file') { + $content = fread($inputFile, fstat($inputFile)['size']); + } elseif ($resourceType === 'stream') { + $content = stream_get_contents($inputFile); + } else { + throw new MindeeException("Unsupported resource type.", ErrorCode::USER_INPUT_ERROR); + } } elseif (is_string($inputFile)) { - $strStripped = str_replace(["\r", "\n"], '', $inputFile); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_string($inputFile) || is_array($inputFile)) { - $strStripped = str_replace(["\r", "\n"], '', $inputFile); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); + if (file_exists($inputFile) && is_file($inputFile)) { + $content = file_get_contents($inputFile); + } else { + $content = $inputFile; + } + } elseif (is_array($inputFile)) { + $content = implode('', $inputFile); } else { - throw new MindeeException( - "Incompatible type for input.", - ErrorCode::USER_INPUT_ERROR - ); + throw new MindeeException("Incompatible type for input.", ErrorCode::USER_INPUT_ERROR); } + + $strStripped = str_replace(["\r", "\n"], '', (string) $content); + $this->file = fopen('php://memory', 'r+'); + fwrite($this->file, $strStripped); + rewind($this->file); } /** * @throws MindeeException Throws if the file contents cannot be converted to a valid array. + * @return array The file contents. */ public function toArray(): array { diff --git a/src/Input/PageOptions.php b/src/Input/PageOptions.php index b39a8412..999c6867 100644 --- a/src/Input/PageOptions.php +++ b/src/Input/PageOptions.php @@ -23,7 +23,7 @@ class PageOptions { /** - * @var array|null Indexes of the page to apply the transformations to. + * @var array|null Indexes of the page to apply the transformations to. */ public ?array $pageIndexes; /** @@ -36,7 +36,7 @@ class PageOptions public int $onMinPage; /** - * @param array|null $pageIndexes Indexes of the page. + * @param array|null $pageIndexes Indexes of the page. * @param string $operation Operation to apply. * @param integer $onMinPage Minimum page amount. */ diff --git a/src/PDF/CustomFPDI.php b/src/PDF/CustomFPDI.php index de9ffc07..b72e8645 100644 --- a/src/PDF/CustomFPDI.php +++ b/src/PDF/CustomFPDI.php @@ -19,7 +19,7 @@ class CustomFPDI extends Fpdi /** * @var integer Angle for the rotation. */ - protected $angle = 0; + protected int $angle = 0; /** * Rotates the current drawing context. @@ -30,10 +30,10 @@ class CustomFPDI extends Fpdi */ public function rotate(float $angle, float $x = -1, float $y = -1): void { - if ($x === -1) { + if ((int) $x === -1) { $x = $this->x; } - if ($y === -1) { + if ((int) $y === -1) { $y = $this->y; } @@ -64,7 +64,7 @@ public function rotate(float $angle, float $x = -1, float $y = -1): void * Ends the page, resetting any rotation. * */ - protected function _endpage(): void //phpcs:ignore + protected function _endpage(): void { if ($this->angle !== 0) { $this->angle = 0; @@ -72,6 +72,7 @@ protected function _endpage(): void //phpcs:ignore } parent::_endpage(); } + /** * Starts a new transformation. * @@ -80,6 +81,7 @@ public function startTransform(): void { $this->_out('q'); } + /** * Stops the current transformation. * diff --git a/src/PDF/PDFCompressor.php b/src/PDF/PDFCompressor.php index b244772a..a2681a6f 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/PDF/PDFCompressor.php @@ -11,14 +11,12 @@ use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; use Smalot\PdfParser\Config; -use Smalot\PdfParser\Document; use Smalot\PdfParser\Page; use Smalot\PdfParser\Parser; use CURLFile; use Exception; use Imagick; - -use function count; +use SplFileObject; /** * PDF compression class. @@ -28,7 +26,7 @@ class PDFCompressor /** * Compresses each page of a provided PDF stream. Skips if force_source_text isn't set and source text is detected. * - * @param mixed $input Path to the PDF file. + * @param resource|string|SplFileObject|CURLFile $input Path to the PDF file. * @param integer $quality Compression quality (70-100 for most JPG images in the test dataset). * @param boolean $forceSourceTextCompression If true, attempts to re-write detected text. * @param boolean $disableSourceText If true, doesn't re-apply source text to the original PDF. @@ -37,7 +35,7 @@ class PDFCompressor * @throws MindeeUnhandledException Throws if one of the dependencies isn't installed. */ public static function compress( - $input, + mixed $input, int $quality = 85, bool $forceSourceTextCompression = false, bool $disableSourceText = true @@ -118,7 +116,7 @@ public static function compress( * @param CustomFPDI $outputPdf Output PDF handle. * @throws MindeePDFException Throws if text can't be inserted into the page. */ - private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void + protected static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void { try { $textElements = PDFUtils::extractTextElements($inputPage); @@ -134,85 +132,16 @@ private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf } } - /** - * Creates the final output PDF, optionally injecting text from the original PDF. - * - * @param CustomFPDI $processedPdf The FPDI object containing the processed pages. - * @param boolean $disableSourceText Whether to disable source text injection. - * @param Document $originalPdf The original PDF document (used for text injection). - * @return string Path to the output PDF file - * @throws MindeePDFException If there's an error creating the output PDF. - */ - private static function createOutputPdf( - CustomFPDI $processedPdf, - bool $disableSourceText, - Document $originalPdf - ): string { - try { - if (!$disableSourceText) { - static::injectText($originalPdf, $processedPdf); - } - - $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; - $processedPdf->Output('F', $outputPath); - - return $outputPath; - } catch (Exception $e) { - throw new MindeePDFException( - "Couldn't create output PDF.", - ErrorCode::PDF_CANT_CREATE, - $e - ); - } - } - - - /** - * Extracts text from a source text PDF, and injects it into a newly-created one. - * - * @param Document $inputPdf Input PDF document. - * @param CustomFPDI $outputPdf The output PDF object. - * @throws MindeePDFException Throws if the text can't be injected. - */ - private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): void - { - try { - $pages = $inputPdf->getPages(); - $pageCount = count($pages); - - for ($i = 1; $i <= $pageCount; $i++) { - $textElements = PDFUtils::extractTextElements($pages[$i - 1]); - - if (!empty($textElements)) { - $tplIdx = $outputPdf->importPage($i); - $size = $outputPdf->getTemplateSize($tplIdx); - $outputPdf->AddPage($size['orientation'], [$size['width'], $size['height']]); - $outputPdf->useTemplate($tplIdx); - foreach ($textElements as $element) { - PDFUtils::addTextElement($outputPdf, $element); - } - } - } - } catch (Exception $e) { - throw new MindeePDFException( - "Couldn't inject text into the new file.", - ErrorCode::PDF_CANT_EDIT, - $e - ); - } - } - - /** * Processes a single PDF page, rasterizing it to a JPEG image. * * @param string $sourcePdfPath Path to the source PDF file. * @param integer $pageIndex The index of the page to process. * @param integer $imageQuality The quality setting for JPEG compression. - * @return array Path to the temporary JPEG file and orientation of the page. + * @return array{0: string, 1: string} Path to the temporary JPEG file and orientation of the page. * @throws MindeePDFException If there's an error processing the page. */ - private static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array + protected static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array { try { $singlePagePdf = new Fpdi(); diff --git a/src/PDF/PDFUtils.php b/src/PDF/PDFUtils.php index 686a88fa..1eb6718c 100644 --- a/src/PDF/PDFUtils.php +++ b/src/PDF/PDFUtils.php @@ -10,6 +10,7 @@ use Mindee\Error\MindeeImageException; use Mindee\Error\MindeePDFException; use Smalot\PdfParser\Config; +use Smalot\PdfParser\Font; use Smalot\PdfParser\Page; use Smalot\PdfParser\Parser; use Imagick; @@ -25,7 +26,7 @@ class PDFUtils { /** - * @param mixed $input Input file. Accepts SplFileObject, Imagick, Curl, resources & paths. + * @param SplFileObject|Imagick|CURLFile|string|resource $input Input file. Accepts SplFileObject, Imagick, Curl, resources & paths. * @return string Path of the file. * @throws MindeePDFException Throws if a path can't be extracted from the input. */ @@ -42,13 +43,18 @@ public static function extractFilePath(mixed $input): string } elseif ($input instanceof CURLFile) { return $input->getFilename(); } elseif (is_resource($input)) { - $imagickHandle = new Imagick(); - $imagickHandle->readImageBlob($input); + $metaData = stream_get_meta_data($input); + if (isset($metaData['uri']) && is_file($metaData['uri'])) { + return $metaData['uri']; + } + rewind($input); + $tempPath = tempnam(sys_get_temp_dir(), 'mindee_ext_') . '.pdf'; + file_put_contents($tempPath, stream_get_contents($input)); + + return $tempPath; } else { throw new MindeePDFException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); } - $imagickHandle->setImageFormat('jpeg'); - return $imagickHandle; } catch (MindeePDFException $e) { throw $e; } catch (Exception $e) { @@ -79,8 +85,8 @@ public static function hasSourceText(string $pdfPath): bool * Extracts text elements with their properties from all pages in a PDF. * * @param string $pdfPath Path to the PDF file. - * @return array An array of arrays, each containing text elements for a page. - * Each text element includes text content, position, font, size, and color. + * @return array A page-indexed array of text elements. + * Each text element includes text content, position, font, size, and color. * @throws MindeePDFException Throws if the PDF can't be parsed or text elements can't be extracted. */ public static function extractPagesTextElements(string $pdfPath): array @@ -122,7 +128,7 @@ public static function downgradePDFVersion(string $inputPath): string try { $outputPath = tempnam(sys_get_temp_dir(), 'downgrade_pdf_') . '.pdf'; $command = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET" - . " -dBATCH -sOutputFile={$outputPath} \"{$inputPath}\""; + . " -dBATCH -sOutputFile=$outputPath \"$inputPath\""; exec($command, $output, $returnCode); @@ -146,14 +152,15 @@ public static function downgradePDFVersion(string $inputPath): string * Extracts text elements with their properties from a PDF page. * * @param Page $page Page object. - * @return array An array of text elements, each containing text content, position, font, size, and color. + * @return array> An array of text elements, each containing text content, + * position, font, size, and color. * @throws MindeePDFException Throws if the text elements can't be extracted. */ public static function extractTextElements(Page $page): array { try { $dataTm = $page->getDataTm(); - } catch (Exception|TypeError $e) { + } catch (Exception|TypeError) { return []; } try { @@ -183,9 +190,9 @@ public static function extractTextElements(Page $page): array /** * @param string $fontName Name of the font/subfont. - * @return array The standard font & possible style. + * @return array{family: string, style: string} The standard font & possible style. */ - private static function standardizeFontName(string $fontName): array + protected static function standardizeFontName(string $fontName): array { $cleanName = preg_replace('/^.*?\+/', '', $fontName); $parts = explode('-', $cleanName, 2); @@ -197,7 +204,7 @@ private static function standardizeFontName(string $fontName): array $fontStyle = ''; } $fontStyle = str_replace(['Bold', 'Italic', 'Oblique'], ['B', 'I', 'I'], $fontStyle); - if (strpos($fontStyle, 'B') !== false && strpos($fontStyle, 'I') !== false) { + if (str_contains($fontStyle, 'B') && str_contains($fontStyle, 'I')) { $fontStyle = 'BI'; } @@ -211,7 +218,7 @@ private static function standardizeFontName(string $fontName): array * Adds a text element to the output PDF. * * @param CustomFPDI $pdf The output PDF object. - * @param array $element Text element array containing text, position, font, size, and color. + * @param array $element Text element array containing text, position, font, size, and color. */ public static function addTextElement(CustomFPDI $pdf, array $element): void { @@ -219,8 +226,8 @@ public static function addTextElement(CustomFPDI $pdf, array $element): void $pageHeight = $pdf->GetPageHeight(); $size = $element['size'] * 3; - $x = $element['x'] - $size / 10; - $y = $pageHeight - $element['y'] - $size / 10; + $x = $element['x'] - $size / 10; + $y = $pageHeight - $element['y'] - $size / 10; $pdf->SetFont($fontInfo['family'], $fontInfo['style'], $size); $pdf->SetTextColor(0, 0, 0); // No currently reliable nor easy way of retrieving text color. diff --git a/src/Parsing/SummaryHelper.php b/src/Parsing/SummaryHelper.php index 76b43d38..2d551ada 100644 --- a/src/Parsing/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -20,7 +20,7 @@ class SummaryHelper */ public static function formatFloat(?float $number): string { - if ($number === null) { + if (null === $number) { return ''; } $formatted = number_format($number, 5, '.', ''); @@ -54,7 +54,7 @@ public static function cleanOutString(string $inputString): string */ protected static function escapeSpecialChars(?string $string): ?string { - if ($string === null) { + if (null === $string) { return null; } $find = ["\n", "\t", "\r"]; @@ -77,7 +77,7 @@ public static function formatForDisplay($inputString = null, ?int $maxColSize = return 'False'; } $inputString = self::escapeSpecialChars($inputString); - if (!$inputString || mb_strlen($inputString, "UTF-8") === 0) { + if (!$inputString) { return ""; } if (!isset($maxColSize)) { diff --git a/src/V1/Client.php b/src/V1/Client.php index 5452fad7..b09ec526 100644 --- a/src/V1/Client.php +++ b/src/V1/Client.php @@ -155,7 +155,7 @@ private function constructEndpoint( string $endpointOwner, string $endpointVersion ): Endpoint { - $endpointVersion = $endpointVersion !== null && strlen($endpointVersion) > 0 ? $endpointVersion : '1'; + $endpointVersion = $endpointVersion !== '' ? $endpointVersion : '1'; $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); @@ -193,7 +193,8 @@ private function constructOTSEndpoint(string $product): Endpoint } catch (ReflectionException $e) { throw new MindeeApiException( "Unable to create custom product " . $product, - ErrorCode::INTERNAL_LIBRARY_ERROR + ErrorCode::INTERNAL_LIBRARY_ERROR, + previous: $e ); } if ($endpointName === 'custom') { @@ -224,7 +225,7 @@ public function createEndpoint(string $endpointName, string $accountName, ?strin ); } $accountName = $this->cleanAccountName($accountName); - if (!$version || $version === '') { + if (empty($version)) { error_log("Notice: no version provided for a custom build, will attempt to poll version 1 by default."); $version = "1"; } @@ -348,7 +349,8 @@ private function makeWorkflowExecutionRequest( } catch (Exception $e) { throw new MindeeApiException( "Unable to create workflow response for $predictionType", - ErrorCode::API_UNPROCESSABLE_ENTITY + ErrorCode::API_UNPROCESSABLE_ENTITY, + previous: $e ); } } @@ -405,7 +407,7 @@ public function parse( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): PredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { @@ -435,10 +437,10 @@ public function enqueueAndParse( ?PollingOptions $asyncOptions = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } - if ($asyncOptions === null) { + if (null === $asyncOptions) { $asyncOptions = new PollingOptions(); } @@ -490,7 +492,7 @@ public function enqueue( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { @@ -539,7 +541,8 @@ public function loadPrediction( } catch (Exception $e) { throw new MindeeException( "Local response is not a valid prediction.", - ErrorCode::USER_INPUT_ERROR + ErrorCode::USER_INPUT_ERROR, + previous: $e ); } } @@ -558,7 +561,7 @@ public function executeWorkflow( ?WorkflowOptions $options = null, ?PageOptions $pageOptions = null ): WorkflowResponse { - if ($options === null) { + if (null === $options) { $options = new WorkflowOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { diff --git a/src/V1/ClientOptions/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php index b4d6846b..531cbfbb 100644 --- a/src/V1/ClientOptions/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -27,9 +27,8 @@ public function __construct(bool $fullText = false) /** * @param boolean $fullText Whether to include the full text. - * @return $this */ - public function setFullText(bool $fullText): PredictOptions + public function setFullText(bool $fullText): static { $this->fullText = $fullText; return $this; diff --git a/src/V1/HTTP/BaseAPI.php b/src/V1/HTTP/BaseAPI.php index caf35150..457dca2e 100644 --- a/src/V1/HTTP/BaseAPI.php +++ b/src/V1/HTTP/BaseAPI.php @@ -90,15 +90,15 @@ protected function setBaseUrl(string $value): void /** * Sets the default timeout. * - * @param string $value Value for the CURL timeout. + * @param integer $value Value for the CURL timeout. */ - protected function setTimeout(string $value): void + protected function setTimeout(int $value): void { $this->requestTimeout = $value; } /** - * Sets values from environment, if needed. + * Sets values from the environment, if needed. * */ protected function setFromEnv(): void diff --git a/src/V1/HTTP/BaseEndpoint.php b/src/V1/HTTP/BaseEndpoint.php index 1c464083..4b2aba89 100644 --- a/src/V1/HTTP/BaseEndpoint.php +++ b/src/V1/HTTP/BaseEndpoint.php @@ -4,6 +4,8 @@ namespace Mindee\V1\HTTP; +use CurlHandle; + /** * Abstract class for endpoints. */ @@ -12,20 +14,21 @@ abstract class BaseEndpoint /** * @var MindeeAPI|MindeeWorkflowAPI Settings of the endpoint. */ - public $settings; + public mixed $settings; /** * @param MindeeAPI|MindeeWorkflowAPI $settings Input settings. */ - public function __construct($settings) + public function __construct(mixed $settings) { $this->settings = $settings; } /** - * Starts a CURL session, using GET. + * Starts a CURL session using GET. * * @param string $queueId ID of the queue to poll. + * @return array */ protected function initCurlSessionGet(string $queueId): array { @@ -56,13 +59,14 @@ protected function initCurlSessionGet(string $queueId): array } /** - * @param resource $ch Curl Channel. + * @param CurlHandle $ch Curl Channel. * @param string $suffix Optional suffix for the url call. - * @param array|null $postFields Post fields. + * @param array|null $postFields Post fields. * @param string|null $workflowId Optional ID of the workflow. + * @return array Final response. */ public function setFinalCurlOpts( - $ch, + CurlHandle $ch, string $suffix, ?array $postFields, ?string $workflowId = null diff --git a/src/V1/HTTP/Endpoint.php b/src/V1/HTTP/Endpoint.php index 9c25913a..a90344ca 100644 --- a/src/V1/HTTP/Endpoint.php +++ b/src/V1/HTTP/Endpoint.php @@ -4,6 +4,7 @@ namespace Mindee\V1\HTTP; +use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\URLInputSource; @@ -49,6 +50,7 @@ public function __construct( * Retrieves a document from its queue ID. * * @param string $queueId ID of the queue to poll. + * @return array Final response. */ public function documentQueueReqGet(string $queueId): array { @@ -60,6 +62,7 @@ public function documentQueueReqGet(string $queueId): array * * @param InputSource $fileCurl File to upload. * @param PredictMethodOptions $options Prediction Options. + * @return array Final response. */ public function predictRequestPost( InputSource $fileCurl, @@ -73,6 +76,7 @@ public function predictRequestPost( * * @param InputSource $fileCurl File to upload. * @param PredictMethodOptions $options Prediction Options. + * @return array Final response. */ public function predictAsyncRequestPost( InputSource $fileCurl, @@ -87,11 +91,13 @@ public function predictAsyncRequestPost( /** - * Starts a CURL session, using POST. + * Starts a CURL session using POST. * * @param InputSource $inputSource File to upload. * @param PredictMethodOptions $options Prediction Options. * @param boolean $async Whether to use the async endpoint. + * @return array Final response. + * @throws MindeeException Throws if the CURL session couldn't be initialized. */ private function initCurlSessionPost( InputSource $inputSource, @@ -138,6 +144,10 @@ private function initCurlSessionPost( if (!empty($params)) { $suffix .= '?' . http_build_query($params); } + + if (!$ch) { + throw new MindeeException("Curl session initialization failed."); + } return $this->setFinalCurlOpts($ch, $suffix, $postFields, $options->workflowId); } } diff --git a/src/V1/HTTP/MindeeAPI.php b/src/V1/HTTP/MindeeAPI.php index 05ea91e2..89f14fa9 100644 --- a/src/V1/HTTP/MindeeAPI.php +++ b/src/V1/HTTP/MindeeAPI.php @@ -44,7 +44,7 @@ public function __construct( ?string $version = "1" ) { parent::__construct($apiKey); - if (!$this->apiKey || $this->apiKey === '') { + if (empty($this->apiKey)) { throw new MindeeException( "Missing API key for '$endpointName v$version' (belonging to $accountName)," . " check your Client configuration.You can set this using the " diff --git a/src/V1/HTTP/MindeeWorkflowAPI.php b/src/V1/HTTP/MindeeWorkflowAPI.php index 0603dd8e..3f5af199 100644 --- a/src/V1/HTTP/MindeeWorkflowAPI.php +++ b/src/V1/HTTP/MindeeWorkflowAPI.php @@ -30,7 +30,7 @@ public function __construct( string $workflowId ) { parent::__construct($apiKey); - if (!$this->apiKey || $this->apiKey === '') { + if (empty($this->apiKey)) { throw new MindeeException( "Missing API key. Please check your Client configuration.You can set this using the " . API_KEY_ENV_NAME . ' environment variable.', diff --git a/src/V1/HTTP/ResponseValidation.php b/src/V1/HTTP/ResponseValidation.php index 9d1838e7..f6e4b790 100644 --- a/src/V1/HTTP/ResponseValidation.php +++ b/src/V1/HTTP/ResponseValidation.php @@ -19,7 +19,7 @@ class ResponseValidation /** * Checks if the synchronous response is valid. Returns True if the response is valid. * - * @param array $response A response object. + * @param array $response A response object. * @return boolean */ public static function isValidSyncResponse(array $response): bool @@ -40,7 +40,7 @@ public static function isValidSyncResponse(array $response): bool * Checks if the workflow response is valid. Also checks if it is a valid synchronous response. * Returns True if the response is valid. * - * @param array $response A response array. + * @param array $response A response array. * @return boolean */ public static function isValidWorkflowResponse(array $response): bool @@ -65,7 +65,7 @@ public static function isValidWorkflowResponse(array $response): bool * Checks if the asynchronous response is valid. Also checks if it is a valid synchronous response. * Returns True if the response is valid. * - * @param array $response A response array. + * @param array $response A response array. * @return boolean */ public static function isValidAsyncResponse(array $response): bool @@ -89,7 +89,8 @@ public static function isValidAsyncResponse(array $response): bool /** * Checks and corrects the response object depending on the possible kinds of returns. * - * @param array $response An endpoint response array. + * @param array $response An endpoint response array. + * @return array A cleaned response array. */ public static function cleanRequestData(array $response): array { diff --git a/src/V1/HTTP/WorkflowEndpoint.php b/src/V1/HTTP/WorkflowEndpoint.php index 71513783..446354fe 100644 --- a/src/V1/HTTP/WorkflowEndpoint.php +++ b/src/V1/HTTP/WorkflowEndpoint.php @@ -4,6 +4,7 @@ namespace Mindee\V1\HTTP; +use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\URLInputSource; @@ -28,6 +29,7 @@ public function __construct( * * @param InputSource $fileCurl File to upload. * @param WorkflowOptions $workflowOptions Workflow options. + * @return array Final response. */ public function executeWorkflowRequestPost( InputSource $fileCurl, @@ -42,6 +44,7 @@ public function executeWorkflowRequestPost( * * @param InputSource $fileCurl File to upload. * @param WorkflowOptions $workflowOptions Workflow options. + * @return array Final response. */ private function initCurlSessionPost( InputSource $fileCurl, @@ -88,6 +91,9 @@ private function initCurlSessionPost( if (!empty($params)) { $suffix .= '?' . http_build_query($params); } + if (!$ch) { + throw new MindeeException("Curl session initialization failed."); + } return $this->setFinalCurlOpts($ch, $suffix, $postFields); } } diff --git a/src/V1/Parsing/Common/ApiRequest.php b/src/V1/Parsing/Common/ApiRequest.php index 44a5729e..f33fef37 100644 --- a/src/V1/Parsing/Common/ApiRequest.php +++ b/src/V1/Parsing/Common/ApiRequest.php @@ -10,28 +10,28 @@ class ApiRequest { /** - * @var array|mixed Error content, if any. + * @var array|string|null Error content, if any. */ - public array $error; + public mixed $error; /** - * @var array|mixed Information on the target resources + * @var array|string|null Information on the target resources */ - public array $resources; + public mixed $resources; /** - * @var string|mixed Status as sent back by the API. + * @var array|string Status as sent back by the API. */ - public string $status; + public mixed $status; /** - * @var integer|mixed HTTP status code. + * @var integer HTTP status code. */ public int $statusCode; /** - * @var string|mixed + * @var string|null URL of the request. */ - public string $url; + public ?string $url; /** - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/ApiResponse.php b/src/V1/Parsing/Common/ApiResponse.php index f5d12c66..fd380a14 100644 --- a/src/V1/Parsing/Common/ApiResponse.php +++ b/src/V1/Parsing/Common/ApiResponse.php @@ -14,12 +14,12 @@ abstract class ApiResponse */ public ApiRequest $apiRequest; /** - * @var array Raw http result. Used for debugging purposes. + * @var array Raw http result. Used for debugging purposes. */ private array $rawHttp; /** - * @param array $rawResponse Raw prediction array. + * @param array $rawResponse Raw prediction array. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/AsyncPredictResponse.php b/src/V1/Parsing/Common/AsyncPredictResponse.php index ec2e870e..3df49b68 100644 --- a/src/V1/Parsing/Common/AsyncPredictResponse.php +++ b/src/V1/Parsing/Common/AsyncPredictResponse.php @@ -25,7 +25,7 @@ class AsyncPredictResponse extends ApiResponse /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/V1/Parsing/Common/Document.php b/src/V1/Parsing/Common/Document.php index e2a2da70..33f07873 100644 --- a/src/V1/Parsing/Common/Document.php +++ b/src/V1/Parsing/Common/Document.php @@ -19,19 +19,19 @@ class Document { /** - * @var string|mixed Name of the input document. + * @var string Name of the input document. */ public string $filename; /** * @var Inference|object|string Result of the base inference. */ - public Inference $inference; + public mixed $inference; /** - * @var string|mixed ID of the document as sent back by the server. + * @var string ID of the document as sent back by the server. */ public string $id; /** - * @var integer|mixed Amount of pages in the document + * @var integer Amount of pages in the document */ public int $nPages; /** @@ -45,7 +45,7 @@ class Document /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. * @throws MindeeApiException Throws if the prediction type isn't recognized. */ public function __construct(string $predictionType, array $rawResponse) @@ -69,7 +69,7 @@ public function __construct(string $predictionType, array $rawResponse) if (array_key_exists("extras", $rawResponse['inference']) && $rawResponse['inference']['extras']) { $this->extras = new Extras($rawResponse['inference']['extras']); } - $this->injectFullTextOcr($rawResponse); + $this->injectFullTextOCR($rawResponse); } /** @@ -89,9 +89,9 @@ public function __toString(): string /** * Injects the results from pages' "full_text_ocr", if present. * - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. */ - private function injectFullTextOcr(array $rawResponse): void + private function injectFullTextOCR(array $rawResponse): void { $pages = $rawResponse['inference']['pages'] ?? []; diff --git a/src/V1/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php index d90e7841..cec6bab9 100644 --- a/src/V1/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -85,7 +85,7 @@ class Execution /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw execution array. + * @param array $rawResponse Raw execution array. * @throws Exception|MindeeApiException Throws if one of the objects can't properly be created. */ public function __construct(string $predictionType, array $rawResponse) diff --git a/src/V1/Parsing/Common/ExecutionFile.php b/src/V1/Parsing/Common/ExecutionFile.php index cccbf777..e83ce665 100644 --- a/src/V1/Parsing/Common/ExecutionFile.php +++ b/src/V1/Parsing/Common/ExecutionFile.php @@ -20,7 +20,7 @@ class ExecutionFile public ?string $alias; /** - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/Extras/CropperExtra.php b/src/V1/Parsing/Common/Extras/CropperExtra.php index bf674868..e176e129 100644 --- a/src/V1/Parsing/Common/Extras/CropperExtra.php +++ b/src/V1/Parsing/Common/Extras/CropperExtra.php @@ -14,12 +14,12 @@ class CropperExtra { /** - * @var array List of all croppings coordiantes. + * @var array List of all croppings coordiantes. */ public array $croppings; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Parsing/Common/Extras/Extras.php b/src/V1/Parsing/Common/Extras/Extras.php index 2533115b..c39d28b6 100644 --- a/src/V1/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -4,7 +4,7 @@ namespace Mindee\V1\Parsing\Common\Extras; -use function PHPUnit\Framework\isEmpty; +use function is_scalar; /** * Extras collection wrapper class. @@ -18,15 +18,15 @@ class Extras */ public ?CropperExtra $cropper; /** - * @var FullTextOcrExtra|null Full text OCR extra. + * @var FullTextOCRExtra|null Full text OCR extra. */ - public ?FullTextOcrExtra $fullTextOcr; + public ?FullTextOCRExtra $fullTextOcr; /** - * @var RagExtra|null Rag Extra. + * @var RAGExtra|null Rag Extra. */ - public ?RagExtra $rag; + public ?RAGExtra $rag; /** - * @var array Other extras. + * @var array Other extras. */ private array $data; @@ -42,7 +42,7 @@ public function __set(string $varName, mixed $value): void } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -50,8 +50,8 @@ public function __construct(array $rawPrediction) if ($key === 'cropper' && isset($rawPrediction['cropper'])) { $this->cropper = new CropperExtra($rawPrediction['cropper']); } elseif ($key === 'full_text_ocr' && isset($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); - } elseif ($key = 'rag' && isset($rawPrediction['rag'])) { + $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); + } elseif ($key === 'rag' && isset($rawPrediction['rag'])) { $this->rag = new RAGExtra($rawPrediction['rag']); } else { $this->__set($key, $extra); @@ -63,12 +63,12 @@ public function __construct(array $rawPrediction) * Adds artificial extra data for reconstructed extras. * Currently only used for full_text_ocr. * - * @param array $rawPrediction Raw HTTP response. + * @param array $rawPrediction Raw HTTP response. */ public function addArtificialExtra(array $rawPrediction): void { - if (isset($rawPrediction["full_text_ocr"]) && !isEmpty($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); + if (!empty($rawPrediction['full_text_ocr'])) { + $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); } } @@ -79,8 +79,8 @@ public function __toString() { $resStr = ''; foreach ($this->data as $key => $extra) { - $resStr .= $key . ': ' . $extra; - $resStr .= "\n"; + $safeExtra = is_scalar($extra) ? $extra : json_encode($extra); + $resStr .= $key . ': ' . $safeExtra . "\n"; } if ($this->cropper) { $resStr .= ":cropper:" . $this->cropper . "\n"; diff --git a/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php b/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php similarity index 89% rename from src/V1/Parsing/Common/Extras/FullTextOcrExtra.php rename to src/V1/Parsing/Common/Extras/FullTextOCRExtra.php index 8ac7d292..8e32e643 100644 --- a/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php @@ -7,7 +7,7 @@ /** * Full Text OCR result. */ -class FullTextOcrExtra +class FullTextOCRExtra { /** * @var string|null Text content of the full text ocr reading. @@ -21,7 +21,7 @@ class FullTextOcrExtra public ?string $language; /** - * @param array $rawPrediction Raw HTTP response. + * @param array $rawPrediction Raw HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/Extras/RAGExtra.php b/src/V1/Parsing/Common/Extras/RAGExtra.php index 53b4dc7e..2f68af5e 100644 --- a/src/V1/Parsing/Common/Extras/RAGExtra.php +++ b/src/V1/Parsing/Common/Extras/RAGExtra.php @@ -15,7 +15,7 @@ class RAGExtra public ?string $matchingDocumentId; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/Inference.php b/src/V1/Parsing/Common/Inference.php index 768e8d8b..90f0ef95 100644 --- a/src/V1/Parsing/Common/Inference.php +++ b/src/V1/Parsing/Common/Inference.php @@ -31,7 +31,7 @@ abstract class Inference */ public Prediction $prediction; /** - * @var array A document's pages. + * @var array A document's pages. */ public array $pages; /** @@ -49,21 +49,21 @@ abstract class Inference /** - * @param array $rawInference Raw inference array. + * @param array $rawResponse Raw inference array. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawInference, ?int $pageId = null) + public function __construct(array $rawResponse, ?int $pageId = null) { $this->isRotationApplied = null; - if (array_key_exists('is_rotation_applied', $rawInference)) { - $this->isRotationApplied = $rawInference['is_rotation_applied']; + if (array_key_exists('is_rotation_applied', $rawResponse)) { + $this->isRotationApplied = $rawResponse['is_rotation_applied']; } - $this->product = new Product($rawInference['product']); + $this->product = new Product($rawResponse['product']); if (isset($pageId)) { $this->pageId = $pageId; } - if (array_key_exists('extras', $rawInference)) { - $this->extras = new Extras($rawInference['extras']); + if (array_key_exists('extras', $rawResponse)) { + $this->extras = new Extras($rawResponse['extras']); } } diff --git a/src/V1/Parsing/Common/Job.php b/src/V1/Parsing/Common/Job.php index fbe468d5..db45ed30 100644 --- a/src/V1/Parsing/Common/Job.php +++ b/src/V1/Parsing/Common/Job.php @@ -39,26 +39,30 @@ class Job */ public ?int $millisecsTaken; /** - * @var array|null Information about an error that occurred during the job processing. + * @var array|null Information about an error that occurred during the job processing. */ public ?array $error; /** - * @param array $rawResponse Raw prediction array. + * @param array $rawResponse Raw prediction array. * @throws MindeeApiException Throws if a date is faulty. */ public function __construct(array $rawResponse) { try { $this->issuedAt = new DateTimeImmutable($rawResponse['issued_at']); - } catch (Exception $e) { + } catch (Exception) { try { - $this->issuedAt = new DateTimeImmutable(strtotime($rawResponse['issued_at'])); - } catch (Exception $e2) { + $timestamp = strtotime($rawResponse['issued_at']); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->issuedAt = new DateTimeImmutable('@' . $timestamp); + } catch (Exception $e) { throw new MindeeApiException( "Could not create date from " . $rawResponse['issued_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, - $e2 + previous: $e ); } } @@ -72,7 +76,11 @@ public function __construct(array $rawResponse) $this->availableAt = new DateTimeImmutable($rawResponse['available_at']); } catch (Exception $e) { try { - $this->availableAt = new DateTimeImmutable(strtotime($rawResponse['available_at'])); + $timestamp = strtotime($rawResponse['available_at']); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->availableAt = new DateTimeImmutable('@' . $timestamp); } catch (Exception $e2) { throw new MindeeApiException( "Could not create date from " . $rawResponse['available_at'], diff --git a/src/V1/Parsing/Common/OCR/MVisionV1.php b/src/V1/Parsing/Common/OCR/MVisionV1.php index cab967ec..b009b171 100644 --- a/src/V1/Parsing/Common/OCR/MVisionV1.php +++ b/src/V1/Parsing/Common/OCR/MVisionV1.php @@ -10,12 +10,12 @@ class MVisionV1 { /** - * @var array List of pages. + * @var array List of pages. */ public array $pages; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OCR/OCR.php b/src/V1/Parsing/Common/OCR/OCR.php index 12df313d..771ec600 100644 --- a/src/V1/Parsing/Common/OCR/OCR.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -18,7 +18,7 @@ class OCR public MVisionV1 $mvisionV1; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -36,7 +36,7 @@ public function __toString(): string * Finds all lines matching the given regex in the OCR data, indexed by their page. * * @param string $regex The regular expression to match against. - * @return array All lines that match the regex, indexed by their page. + * @return array> All lines that match the regex, indexed by their page. */ public function findLineByRegex(string $regex): array { diff --git a/src/V1/Parsing/Common/OCR/OCRLine.php b/src/V1/Parsing/Common/OCR/OCRLine.php index 29873168..68480840 100644 --- a/src/V1/Parsing/Common/OCR/OCRLine.php +++ b/src/V1/Parsing/Common/OCR/OCRLine.php @@ -12,12 +12,12 @@ class OCRLine { /** - * @var array Words in the line. + * @var array Words in the line. */ private array $words; /** - * @param array $words Words to insert in the line. + * @param array $words Words to insert in the line. */ public function __construct(array $words = []) { diff --git a/src/V1/Parsing/Common/OCR/OCRPage.php b/src/V1/Parsing/Common/OCR/OCRPage.php index efaf492a..95200314 100644 --- a/src/V1/Parsing/Common/OCR/OCRPage.php +++ b/src/V1/Parsing/Common/OCR/OCRPage.php @@ -13,11 +13,11 @@ class OCRPage { /** - * @var array List of all words. + * @var array List of all words. */ private array $allWords; /** - * @var array List of lines. + * @var array List of lines. */ private array $lines; @@ -71,19 +71,19 @@ public static function getMinMaxY(OCRWord $word1, OCRWord $word2): int /** * Puts all words on the page into an array of lines. - * + * @return array */ private function toLines(): array { $current = null; $indexes = []; $lines = []; - foreach ($this->allWords as $w) { + foreach ($this->allWords as $_) { $line = new OCRLine(); for ($idx = 0; $idx < count($this->allWords); $idx++) { $word = $this->allWords[$idx]; if (!in_array($idx, $indexes, true)) { - if ($current === null) { + if (null === $current) { $current = $word; $indexes[] = $idx; $line = new OCRLine(); @@ -107,7 +107,7 @@ private function toLines(): array /** * Retrieves all lines on the page. - * + * @return array */ public function getAllLines(): array { @@ -119,7 +119,7 @@ public function getAllLines(): array /** * Retrieves all words on the page. - * + * @return array */ public function getAllWords(): array { @@ -127,7 +127,7 @@ public function getAllWords(): array } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OCR/OCRWord.php b/src/V1/Parsing/Common/OCR/OCRWord.php index 24cc03d4..14ad11a1 100644 --- a/src/V1/Parsing/Common/OCR/OCRWord.php +++ b/src/V1/Parsing/Common/OCR/OCRWord.php @@ -14,18 +14,18 @@ class OCRWord use FieldPositionMixin; /** - * @var float|mixed The confidence score. + * @var float The confidence score. */ public float $confidence; /** - * @var string|mixed The extracted text. + * @var string The extracted text. */ public string $text; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OrientationField.php b/src/V1/Parsing/Common/OrientationField.php index 9a8e5a55..e75816eb 100644 --- a/src/V1/Parsing/Common/OrientationField.php +++ b/src/V1/Parsing/Common/OrientationField.php @@ -11,16 +11,12 @@ /** * The clockwise rotation to apply (in degrees) to make the image upright. + * @extends BaseField */ class OrientationField extends BaseField { /** - * @var integer Degrees as an integer. - */ - public $value; - - /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -34,7 +30,7 @@ public function __construct( parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); $this->value = 0; if (array_key_exists($valueKey, $rawPrediction) && is_numeric($rawPrediction[$valueKey])) { - $this->value = (float) ($rawPrediction[$valueKey]); + $this->value = (int) ($rawPrediction[$valueKey]); if (!in_array($this->value, [0, 90, 180, 270], true)) { $this->value = 0; } diff --git a/src/V1/Parsing/Common/Page.php b/src/V1/Parsing/Common/Page.php index d2aa4626..453669c4 100644 --- a/src/V1/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -6,6 +6,7 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; +use Mindee\Error\MindeeUnsetException; use Mindee\V1\Parsing\Common\Extras\Extras; use ReflectionClass; use ReflectionException; @@ -18,7 +19,7 @@ class Page { /** - * @var integer|mixed ID of the current page. + * @var integer ID of the current page. */ public int $id; /** @@ -28,7 +29,7 @@ class Page /** * @var Prediction|object Type of Page prediction. */ - public Prediction $prediction; + public mixed $prediction; /** * @var Extras Potential Extras fields sent back along with the prediction. */ @@ -36,8 +37,10 @@ class Page /** * @param string $predictionType Type of prediction. - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @throws MindeeApiException Throws if the prediction type isn't recognized. + * @throws MindeeUnsetException Throws if a field doesn't appear in the response, through the reflected document + * class. */ public function __construct(string $predictionType, array $rawPrediction) { diff --git a/src/V1/Parsing/Common/PredictResponse.php b/src/V1/Parsing/Common/PredictResponse.php index a2459ba0..2af01dfc 100644 --- a/src/V1/Parsing/Common/PredictResponse.php +++ b/src/V1/Parsing/Common/PredictResponse.php @@ -18,7 +18,7 @@ class PredictResponse extends ApiResponse /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/V1/Parsing/Common/Product.php b/src/V1/Parsing/Common/Product.php index 6c130246..011fbb8f 100644 --- a/src/V1/Parsing/Common/Product.php +++ b/src/V1/Parsing/Common/Product.php @@ -10,16 +10,16 @@ class Product { /** - * @var string|mixed Product's name. + * @var string Product's name. */ public string $name; /** - * @var string|mixed Product's versions. + * @var string Product's versions. */ public string $version; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/WorkflowResponse.php b/src/V1/Parsing/Common/WorkflowResponse.php index d48543b0..e4d9579e 100644 --- a/src/V1/Parsing/Common/WorkflowResponse.php +++ b/src/V1/Parsing/Common/WorkflowResponse.php @@ -19,7 +19,7 @@ class WorkflowResponse extends ApiResponse /** * @param string|null $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array $rawResponse Raw HTTP response. * @throws Exception Throws if the prediction type isn't recognized or if a field can't be deserialized. */ public function __construct(?string $predictionType, array $rawResponse) diff --git a/src/V1/Parsing/Generated/GeneratedListField.php b/src/V1/Parsing/Generated/GeneratedListField.php index d86609b2..41d030b6 100644 --- a/src/V1/Parsing/Generated/GeneratedListField.php +++ b/src/V1/Parsing/Generated/GeneratedListField.php @@ -17,13 +17,13 @@ class GeneratedListField /** @var integer|null ID of the page the object was found on */ public ?int $pageId; - /** @var array List of values */ + /** @var array List of values */ public array $values = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. + * @param list $rawPrediction Array containing the list elements. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -57,11 +57,11 @@ public function __construct(array $rawPrediction, ?int $pageId = null) /** * Get a list of contents. * - * @return array List of contents. + * @return array List of contents. */ public function getContentsList(): array { - return array_map(static fn($v) => (string) ($v ?: ""), $this->values); + return array_map(static fn($v) => (string) $v, $this->values); } /** diff --git a/src/V1/Parsing/Generated/GeneratedObjectField.php b/src/V1/Parsing/Generated/GeneratedObjectField.php index cdff6a03..65cf369a 100644 --- a/src/V1/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -13,6 +13,10 @@ /** * A JSON-like object, with miscellaneous values. + * @property PositionField|null $bounding_box + * @property PositionField|null $polygon + * @property PositionField|null $quadrangle + * @property PositionField|null $rectangle */ class GeneratedObjectField { @@ -25,13 +29,15 @@ class GeneratedObjectField /** @var string|null Raw unprocessed value, as it was sent by the server */ private ?string $rawValue; - /** @var array List of all printable field names */ + /** @var array List of all printable field names */ private array $printableValues; + /** @var array Storage for dynamically generated properties */ + private array $dynamicProperties = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. + * @param array $rawPrediction Raw prediction data. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -69,6 +75,39 @@ public function __construct(array $rawPrediction, ?int $pageId = null) } } + /** + * Magic getter for dynamic properties. + * + * @param string $name Property name. + * @return mixed + */ + public function __get(string $name) + { + return $this->dynamicProperties[$name] ?? null; + } + + /** + * Magic setter for dynamic properties. + * + * @param string $name Property name. + * @param mixed $value Property value. + */ + public function __set(string $name, mixed $value): void + { + $this->dynamicProperties[$name] = $value; + } + + /** + * Magic isset for dynamic properties. + * + * @param string $name Property name. + * @return boolean + */ + public function __isset(string $name): bool + { + return isset($this->dynamicProperties[$name]); + } + /** * Get a string representation of the object. * @@ -94,7 +133,7 @@ public function strLevel(int $level = 0): string foreach ($this->printableValues as $attr) { $value = $this->{$attr}; $strValue = $value !== null ? (string) $value : ""; - $outStr .= "\n{$indent}:{$attr}: {$strValue}"; + $outStr .= "\n$indent:$attr: $strValue"; } return "\n" . $indent . trim($outStr); } @@ -102,7 +141,7 @@ public function strLevel(int $level = 0): string /** * Checks whether a field is a custom object or not. * - * @param array $strDict Input dictionary to check. + * @param array $strDict Input dictionary to check. * @return boolean Whether the field is a custom object. */ public static function isGeneratedObject(array $strDict): bool diff --git a/src/V1/Parsing/Standard/AddressField.php b/src/V1/Parsing/Standard/AddressField.php index 1825ba4e..52836ffb 100644 --- a/src/V1/Parsing/Standard/AddressField.php +++ b/src/V1/Parsing/Standard/AddressField.php @@ -27,7 +27,7 @@ class AddressField extends StringField public ?string $country; /** - * @param array $rawPrediction Raw prediction array as returned by the Mindee API. + * @param array $rawPrediction Raw prediction array as returned by the Mindee API. * @param integer|null $pageId Page number for multi-page documents. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the full address value. diff --git a/src/V1/Parsing/Standard/AmountField.php b/src/V1/Parsing/Standard/AmountField.php index 481f8655..7fbf222c 100644 --- a/src/V1/Parsing/Standard/AmountField.php +++ b/src/V1/Parsing/Standard/AmountField.php @@ -8,6 +8,7 @@ /** * A field containing an amount value. + * @extends BaseField */ class AmountField extends BaseField { @@ -15,13 +16,7 @@ class AmountField extends BaseField use FieldPositionMixin; /** - * @var float|null The amount value as a float. - */ - public $value; - - - /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. */ diff --git a/src/V1/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php index d8701c90..686f510b 100644 --- a/src/V1/Parsing/Standard/BaseField.php +++ b/src/V1/Parsing/Standard/BaseField.php @@ -8,26 +8,27 @@ /** * Base class for most fields. + * @template T Generic typing for value type handling. */ abstract class BaseField { use FieldConfidenceMixin; /** - * @var mixed|null Raw field value. + * @var T|null Raw field value. */ - public $value; + public mixed $value; /** * @var boolean Whether the field was reconstructed from other fields. */ public bool $reconstructed; /** - * @var integer|mixed|null The document page on which the information was found. + * @var integer|null The document page on which the information was found. */ public ?int $pageId; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -55,7 +56,7 @@ public function __construct( /** * Compares with the value of another field. * - * @param BaseField $obj Field to compare. + * @param BaseField $obj Field to compare. * @return boolean */ public function __compare(self $obj): bool diff --git a/src/V1/Parsing/Standard/BooleanField.php b/src/V1/Parsing/Standard/BooleanField.php index 2784b79b..c89acebe 100644 --- a/src/V1/Parsing/Standard/BooleanField.php +++ b/src/V1/Parsing/Standard/BooleanField.php @@ -8,6 +8,7 @@ /** * A field containing a boolean value. + * @extends BaseField */ class BooleanField extends BaseField { @@ -15,13 +16,7 @@ class BooleanField extends BaseField use FieldPositionMixin; /** - * @var boolean|null Value as string. - */ - public $value; - - - /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/ClassificationField.php b/src/V1/Parsing/Standard/ClassificationField.php index 6b8c25bb..d23ddb47 100644 --- a/src/V1/Parsing/Standard/ClassificationField.php +++ b/src/V1/Parsing/Standard/ClassificationField.php @@ -6,20 +6,17 @@ /** * Represents a classifier value. + * @extends BaseField */ class ClassificationField extends BaseField { /** - * @var string|mixed|null The classification value. - */ - public $value; - /** - * @var float|mixed The confidence score. + * @var float The confidence score. */ public float $confidence; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/CompanyRegistrationField.php b/src/V1/Parsing/Standard/CompanyRegistrationField.php index 7ebacb0b..1e4db69e 100644 --- a/src/V1/Parsing/Standard/CompanyRegistrationField.php +++ b/src/V1/Parsing/Standard/CompanyRegistrationField.php @@ -10,19 +10,20 @@ /** * A company registration item. + * @extends BaseField */ class CompanyRegistrationField extends BaseField { use FieldPositionMixin; /** - * @var string|mixed The type of registration. + * @var string The type of registration. */ public string $type; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -60,7 +61,7 @@ public function __toString(): string /** * Returns an array of proper values for the formatting. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Parsing/Standard/DateField.php b/src/V1/Parsing/Standard/DateField.php index f44afa8b..c066c916 100644 --- a/src/V1/Parsing/Standard/DateField.php +++ b/src/V1/Parsing/Standard/DateField.php @@ -12,6 +12,7 @@ /** * A field containing a date value. + * @extends BaseField */ class DateField extends BaseField { @@ -23,11 +24,6 @@ class DateField extends BaseField */ public ?DateTimeImmutable $dateObject; - /** - * @var string|null The raw field value. - */ - public $value; - /** * @var boolean|null Whether the field was computed or retrieved directly from the document. */ @@ -35,7 +31,7 @@ class DateField extends BaseField /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -57,10 +53,14 @@ public function __construct( if ($this->value) { try { $this->dateObject = new DateTimeImmutable($this->value, new DateTimeZone('UTC')); - } catch (Exception $e) { + } catch (Exception) { try { - $this->dateObject = new DateTimeImmutable(strtotime($this->value), new DateTimeZone('UTC')); - } catch (Exception $e2) { + $timestamp = strtotime($this->value); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->dateObject = new DateTimeImmutable('@' . $timestamp); + } catch (Exception $e) { throw new MindeeApiException( "Couldn't create date field from value '" . $this->value . "'", ErrorCode::API_UNPROCESSABLE_ENTITY, diff --git a/src/V1/Parsing/Standard/FieldConfidenceMixin.php b/src/V1/Parsing/Standard/FieldConfidenceMixin.php index 1c8f465a..ce2d1cfd 100644 --- a/src/V1/Parsing/Standard/FieldConfidenceMixin.php +++ b/src/V1/Parsing/Standard/FieldConfidenceMixin.php @@ -19,7 +19,7 @@ trait FieldConfidenceMixin /** * Sets the confidence score. * - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ protected function setConfidence(array $rawPrediction): void { diff --git a/src/V1/Parsing/Standard/FieldPositionMixin.php b/src/V1/Parsing/Standard/FieldPositionMixin.php index 5105cbbe..d081b1e0 100644 --- a/src/V1/Parsing/Standard/FieldPositionMixin.php +++ b/src/V1/Parsing/Standard/FieldPositionMixin.php @@ -26,7 +26,7 @@ trait FieldPositionMixin /** * Sets the position of a field. * - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ protected function setPosition(array $rawPrediction): void { diff --git a/src/V1/Parsing/Standard/LocaleField.php b/src/V1/Parsing/Standard/LocaleField.php index eddd61db..933fb6dd 100644 --- a/src/V1/Parsing/Standard/LocaleField.php +++ b/src/V1/Parsing/Standard/LocaleField.php @@ -8,6 +8,7 @@ /** * The locale detected on the document. + * @extends BaseField */ class LocaleField extends BaseField { @@ -25,7 +26,7 @@ class LocaleField extends BaseField public ?string $currency; /** - * @param array $localePrediction Raw locale prediction. + * @param array $localePrediction Raw locale prediction. * @param string $key Name of the prediction key. */ private static function getValue(array $localePrediction, string $key): ?string @@ -38,7 +39,7 @@ private static function getValue(array $localePrediction, string $key): ?string } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. */ diff --git a/src/V1/Parsing/Standard/PaymentDetailsField.php b/src/V1/Parsing/Standard/PaymentDetailsField.php index d8be70aa..0a91b062 100644 --- a/src/V1/Parsing/Standard/PaymentDetailsField.php +++ b/src/V1/Parsing/Standard/PaymentDetailsField.php @@ -9,6 +9,7 @@ /** * Information on a single payment. + * @extends BaseField */ class PaymentDetailsField extends BaseField { @@ -34,7 +35,7 @@ class PaymentDetailsField extends BaseField /** * Gets the value of any given key. * - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param string $key Key to get the value of. */ private function getValue(array $rawPrediction, string $key): ?string @@ -55,7 +56,7 @@ private function getValue(array $rawPrediction, string $key): ?string } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/PositionField.php b/src/V1/Parsing/Standard/PositionField.php index 22998b46..ab0d3c5e 100644 --- a/src/V1/Parsing/Standard/PositionField.php +++ b/src/V1/Parsing/Standard/PositionField.php @@ -12,13 +12,10 @@ /** * A field indicating a position or area on the document. + * @extends BaseField */ class PositionField extends BaseField { - /** - * @var Polygon|null Polygon of cropped area, identical to the `polygon` property. - */ - public $value; /** * @var Polygon|null Polygon of cropped area. */ @@ -39,16 +36,12 @@ class PositionField extends BaseField /** * Retrieves the quadrilateral of a prediction. * - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param string $key Key to use for the value. */ private static function getQuadrilateral(array $rawPrediction, string $key): ?Polygon { - if ( - !array_key_exists($key, $rawPrediction) - || $rawPrediction[$key] === null - || $rawPrediction[$key] === [] - ) { + if (empty($rawPrediction[$key])) { return null; } @@ -58,20 +51,20 @@ private static function getQuadrilateral(array $rawPrediction, string $key): ?Po /** * Retrieves the polygon of a prediction. * - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param string $key Key to use for the value. */ private static function getPolygon(array $rawPrediction, string $key): ?Polygon { - if (array_key_exists($key, $rawPrediction)) { - return new Polygon($rawPrediction[$key]); + if (!array_key_exists($key, $rawPrediction)) { + return null; } - return null; + return new Polygon($rawPrediction[$key]); } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page id. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/StringField.php b/src/V1/Parsing/Standard/StringField.php index e16b872f..60dfd56f 100644 --- a/src/V1/Parsing/Standard/StringField.php +++ b/src/V1/Parsing/Standard/StringField.php @@ -8,16 +8,13 @@ /** * A field containing a text value. + * @extends BaseField */ class StringField extends BaseField { use FieldConfidenceMixin; use FieldPositionMixin; - /** - * @var string|null Value as string. - */ - public $value; /** * @var string|null The value as it appears on the document. */ @@ -25,7 +22,7 @@ class StringField extends BaseField /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/TaxField.php b/src/V1/Parsing/Standard/TaxField.php index 00aa323e..b71d1988 100644 --- a/src/V1/Parsing/Standard/TaxField.php +++ b/src/V1/Parsing/Standard/TaxField.php @@ -9,15 +9,11 @@ /** * Tax line information. + * @extends BaseField */ class TaxField extends BaseField { use FieldPositionMixin; - - /** - * @var float|null The amount of the tax line. - */ - public $value; /** * @var float|null The tax rate. */ @@ -32,7 +28,7 @@ class TaxField extends BaseField public ?float $basis; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field has been reconstructed. * @param string $valueKey Key to use for the value. @@ -75,7 +71,7 @@ public function __construct( /** * Returns an array of immediately printable values. * - * @return array Array of printable values. + * @return array Array of printable values. */ private function printableValues(): array { diff --git a/src/V1/Parsing/Standard/Taxes.php b/src/V1/Parsing/Standard/Taxes.php index 935bff89..391e3dec 100644 --- a/src/V1/Parsing/Standard/Taxes.php +++ b/src/V1/Parsing/Standard/Taxes.php @@ -8,11 +8,12 @@ /** * List of tax lines information. + * @extends ArrayObject */ class Taxes extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) diff --git a/src/V1/Product/BarcodeReader/BarcodeReaderV1.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php index d1fbf6ab..86a24630 100644 --- a/src/V1/Product/BarcodeReader/BarcodeReaderV1.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php @@ -25,7 +25,7 @@ class BarcodeReaderV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php index dfe635b7..12cfa61e 100644 --- a/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php @@ -22,8 +22,9 @@ class BarcodeReaderV1Document extends Prediction * @var StringField[] List of decoded 2D barcodes. */ public array $codes2D; + /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -32,14 +33,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["codes_1d"])) { throw new MindeeUnsetException(); } - $this->codes1D = $rawPrediction["codes_1d"] === null ? [] : array_map( + $this->codes1D = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_1d"] ); if (!isset($rawPrediction["codes_2d"])) { throw new MindeeUnsetException(); } - $this->codes2D = $rawPrediction["codes_2d"] === null ? [] : array_map( + $this->codes2D = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_2d"] ); diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1.php b/src/V1/Product/BillOfLading/BillOfLadingV1.php index f5c5ce7c..26a92b9d 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1.php @@ -25,7 +25,7 @@ class BillOfLadingV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php index 41e6fb38..af0afd3e 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php @@ -28,9 +28,13 @@ class BillOfLadingV1Carrier * @var string|null The Standard Carrier Alpha Code (SCAC) of the carrier. */ public ?string $scac; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->name = $rawPrediction["name"] ?? null; $this->professionalNumber = $rawPrediction["professional_number"] ?? null; $this->scac = $rawPrediction["scac"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php index 6cb3fe62..da568e6d 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php @@ -40,9 +40,13 @@ class BillOfLadingV1CarrierItem * @var string|null The unit of measurement for weights. */ public ?string $weightUnit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -58,11 +62,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; $this->weightUnit = $rawPrediction["weight_unit"] ?? null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index fdaeb392..96e0e2c4 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -8,11 +8,12 @@ /** * The goods being shipped. + * @extends ArrayObject */ class BillOfLadingV1CarrierItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php index 1f9cac83..035c6065 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php @@ -32,9 +32,13 @@ class BillOfLadingV1Consignee * @var string|null The phone number of the consignee. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { @@ -76,7 +67,6 @@ private function printableValues(): array } /** * Output in a format suitable for inclusion in a field list. - * */ public function toFieldList(): string { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php index 591e0709..e1797d6d 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php @@ -60,7 +60,7 @@ class BillOfLadingV1Document extends Prediction */ public BillOfLadingV1Shipper $shipper; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -150,10 +150,10 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $shipperToFieldList = $this->shipper !== null ? $this->shipper->toFieldList() : ""; - $consigneeToFieldList = $this->consignee !== null ? $this->consignee->toFieldList() : ""; - $notifyPartyToFieldList = $this->notifyParty !== null ? $this->notifyParty->toFieldList() : ""; - $carrierToFieldList = $this->carrier !== null ? $this->carrier->toFieldList() : ""; + $shipperToFieldList = $this->shipper->toFieldList(); + $consigneeToFieldList = $this->consignee->toFieldList(); + $notifyPartyToFieldList = $this->notifyParty->toFieldList(); + $carrierToFieldList = $this->carrier->toFieldList(); $carrierItemsSummary = (string) ($this->carrierItems); $outStr = ":Bill of Lading Number: $this->billOfLadingNumber diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index 0ad3fd4b..6424e314 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -32,9 +32,13 @@ class BillOfLadingV1NotifyParty * @var string|null The phone number of the notify party. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php index bd1aa623..a82122d4 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php @@ -32,9 +32,13 @@ class BillOfLadingV1Shipper * @var string|null The phone number of the shipper. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BusinessCard/BusinessCardV1.php b/src/V1/Product/BusinessCard/BusinessCardV1.php index ece609a6..a55d7b4f 100644 --- a/src/V1/Product/BusinessCard/BusinessCardV1.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1.php @@ -25,7 +25,7 @@ class BusinessCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BusinessCard/BusinessCardV1Document.php b/src/V1/Product/BusinessCard/BusinessCardV1Document.php index 605a7556..35d67592 100644 --- a/src/V1/Product/BusinessCard/BusinessCardV1Document.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1Document.php @@ -59,7 +59,7 @@ class BusinessCardV1Document extends Prediction */ public StringField $website; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -131,7 +131,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["social_media"])) { throw new MindeeUnsetException(); } - $this->socialMedia = $rawPrediction["social_media"] === null ? [] : array_map( + $this->socialMedia = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["social_media"] ); diff --git a/src/V1/Product/Cropper/CropperV1.php b/src/V1/Product/Cropper/CropperV1.php index 536e8032..7e098130 100644 --- a/src/V1/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -25,12 +25,12 @@ class CropperV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { parent::__construct($rawPrediction); - $this->prediction = new CropperV1Document($rawPrediction['prediction']); + $this->prediction = new CropperV1Document(); $this->pages = []; foreach ($rawPrediction['pages'] as $page) { try { diff --git a/src/V1/Product/Cropper/CropperV1Document.php b/src/V1/Product/Cropper/CropperV1Document.php index d59ac678..684c422e 100644 --- a/src/V1/Product/Cropper/CropperV1Document.php +++ b/src/V1/Product/Cropper/CropperV1Document.php @@ -11,6 +11,11 @@ */ class CropperV1Document extends Prediction { + /** + * Constructor for CropperV1Document. + */ + public function __construct() {} + /** * @return string String representation. */ diff --git a/src/V1/Product/Cropper/CropperV1Page.php b/src/V1/Product/Cropper/CropperV1Page.php index 6fd3297a..d59d99a9 100644 --- a/src/V1/Product/Cropper/CropperV1Page.php +++ b/src/V1/Product/Cropper/CropperV1Page.php @@ -17,12 +17,12 @@ class CropperV1Page extends CropperV1Document */ public array $cropping; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { - $this->cropping = $rawPrediction["cropping"] === null ? [] : array_map( + $this->cropping = null === $rawPrediction["cropping"] ? [] : array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["cropping"] ); diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php index cde32f1b..a6a051bf 100644 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php @@ -25,7 +25,7 @@ class DeliveryNoteV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php index be6e9440..4c7ed9f7 100644 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php @@ -45,7 +45,7 @@ class DeliveryNoteV1Document extends Prediction */ public AmountField $totalAmount; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/DriverLicense/DriverLicenseV1.php b/src/V1/Product/DriverLicense/DriverLicenseV1.php index d78cc2f7..a28bb976 100644 --- a/src/V1/Product/DriverLicense/DriverLicenseV1.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1.php @@ -25,7 +25,7 @@ class DriverLicenseV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/DriverLicense/DriverLicenseV1Document.php b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php index b0a40d36..aa870fcd 100644 --- a/src/V1/Product/DriverLicense/DriverLicenseV1Document.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php @@ -68,7 +68,7 @@ class DriverLicenseV1Document extends Prediction */ public StringField $state; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php index 8290f702..3483760f 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php @@ -25,7 +25,7 @@ class FinancialDocumentV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php index 1a153aad..093d80c9 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php @@ -156,7 +156,7 @@ class FinancialDocumentV1Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -186,7 +186,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["customer_company_registrations"])) { throw new MindeeUnsetException(); } - $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : array_map( + $this->customerCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); @@ -284,7 +284,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] === null ? [] : array_map( + $this->referenceNumbers = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); @@ -312,7 +312,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); @@ -333,7 +333,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_payment_details"])) { throw new MindeeUnsetException(); } - $this->supplierPaymentDetails = $rawPrediction["supplier_payment_details"] === null ? [] : array_map( + $this->supplierPaymentDetails = array_map( static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php index 04377842..9de32437 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -48,9 +48,13 @@ class FinancialDocumentV1LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -70,11 +74,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -90,23 +95,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index cdfb1ce1..cbb7bfea 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -8,11 +8,12 @@ /** * List of line item present on the document. + * @extends ArrayObject */ class FinancialDocumentV1LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php index 38a02046..24f49825 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php @@ -25,7 +25,7 @@ class BankAccountDetailsV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php index ca8e3105..c41cb938 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php @@ -27,7 +27,7 @@ class BankAccountDetailsV1Document extends Prediction */ public StringField $swift; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php index 7fa92f54..f91a2409 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php @@ -25,7 +25,7 @@ class BankAccountDetailsV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index a94f77c0..e35b76b9 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -32,9 +32,13 @@ class BankAccountDetailsV2Bban * @var string|null The BBAN Account number outputted as a string. */ public ?string $bbanNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bbanBranchCode = $rawPrediction["bban_branch_code"] ?? null; $this->bbanKey = $rawPrediction["bban_key"] ?? null; $this->bbanNumber = $rawPrediction["bban_number"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bbanBankCode"] = SummaryHelperV1::formatForDisplay($this->bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelperV1::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelperV1::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelperV1::formatForDisplay($this->bbanNumber); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php index 056a1bab..1cac3486 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php @@ -31,7 +31,7 @@ class BankAccountDetailsV2Document extends Prediction */ public StringField $swiftCode; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -72,7 +72,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $bbanToFieldList = $this->bban !== null ? $this->bban->toFieldList() : ""; + $bbanToFieldList = $this->bban->toFieldList(); $outStr = ":Account Holder's Names: $this->accountHoldersNames :Basic Bank Account Number: $bbanToFieldList diff --git a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index 0715991a..1b07628b 100644 --- a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -25,7 +25,7 @@ class CarteGriseV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php index e3e204a6..c9e2a11a 100644 --- a/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php @@ -180,7 +180,7 @@ class CarteGriseV1Document extends Prediction */ public StringField $y6; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php index deffd538..c5139e22 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php @@ -25,7 +25,7 @@ class EnergyBillV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php index 64cd5e06..96d2270f 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php @@ -74,7 +74,7 @@ class EnergyBillV1Document extends Prediction */ public AmountField $totalTaxes; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -185,12 +185,12 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $energySupplierToFieldList = $this->energySupplier !== null ? $this->energySupplier->toFieldList() : ""; - $energyConsumerToFieldList = $this->energyConsumer !== null ? $this->energyConsumer->toFieldList() : ""; + $energySupplierToFieldList = $this->energySupplier->toFieldList(); + $energyConsumerToFieldList = $this->energyConsumer->toFieldList(); $subscriptionSummary = (string) ($this->subscription); $energyUsageSummary = (string) ($this->energyUsage); $taxesAndContributionsSummary = (string) ($this->taxesAndContributions); - $meterDetailsToFieldList = $this->meterDetails !== null ? $this->meterDetails->toFieldList() : ""; + $meterDetailsToFieldList = $this->meterDetails->toFieldList(); $outStr = ":Invoice Number: $this->invoiceNumber :Contract ID: $this->contractId diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php index b7bc5164..a93b147f 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php @@ -24,9 +24,13 @@ class EnergyBillV1EnergyConsumer * @var string|null The name of the energy consumer. */ public ?string $name; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -35,23 +39,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php index 67c60e04..44d91bbe 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php @@ -24,9 +24,13 @@ class EnergyBillV1EnergySupplier * @var string|null The name of the energy supplier. */ public ?string $name; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -35,23 +39,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php index cce84b0c..cf5e7c55 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php @@ -48,9 +48,13 @@ class EnergyBillV1EnergyUsage * @var float|null The price per unit of energy consumed. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -62,6 +66,7 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; + $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) @@ -73,7 +78,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -89,23 +94,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 9c782786..f772b7f8 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -8,11 +8,12 @@ /** * Details of energy consumption. + * @extends ArrayObject */ class EnergyBillV1EnergyUsages extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php index 8fcf7d01..60aadfc7 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php @@ -28,9 +28,13 @@ class EnergyBillV1MeterDetail * @var string|null The unit of power for energy consumption. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->meterNumber = $rawPrediction["meter_number"] ?? null; $this->meterType = $rawPrediction["meter_type"] ?? null; $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php index eb5e4839..a6e0cba3 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php @@ -40,9 +40,13 @@ class EnergyBillV1Subscription * @var float|null The price per unit of subscription. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -58,11 +62,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total"]) : null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index 1f2c2416..fe9e17b0 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -8,11 +8,12 @@ /** * The subscription details fee for the energy service. + * @extends ArrayObject */ class EnergyBillV1Subscriptions extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php index bbd02fc9..7cbdd739 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php @@ -40,9 +40,13 @@ class EnergyBillV1TaxesAndContribution * @var float|null The price per unit of Taxes and Contributions. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -52,6 +56,7 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; + $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) @@ -62,7 +67,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 2a0a3e95..07351838 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php @@ -8,11 +8,12 @@ /** * Details of Taxes and Contributions. + * @extends ArrayObject */ class EnergyBillV1TaxesAndContributions extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1.php b/src/V1/Product/Fr/HealthCard/HealthCardV1.php index c691a051..d73c3cc1 100644 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1.php @@ -25,7 +25,7 @@ class HealthCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php index 92cfc1c6..53bb683c 100644 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php @@ -32,7 +32,7 @@ class HealthCardV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -41,7 +41,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV1.php b/src/V1/Product/Fr/IdCard/IdCardV1.php index 9d53b4e3..38225bdb 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -25,7 +25,7 @@ class IdCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV1Document.php b/src/V1/Product/Fr/IdCard/IdCardV1Document.php index 928097a0..0ab03da7 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Document.php @@ -55,8 +55,9 @@ class IdCardV1Document extends Prediction * @var StringField The surname of the card holder. */ public StringField $surname; + /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -100,7 +101,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV1Page.php b/src/V1/Product/Fr/IdCard/IdCardV1Page.php index 96024e7b..bb5a1499 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -17,7 +17,7 @@ class IdCardV1Page extends IdCardV1Document */ public ClassificationField $documentSide; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/IdCard/IdCardV2.php b/src/V1/Product/Fr/IdCard/IdCardV2.php index 690dfa37..a773f4c2 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2.php @@ -25,7 +25,7 @@ class IdCardV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV2Document.php b/src/V1/Product/Fr/IdCard/IdCardV2Document.php index 32c60cea..419fc9c2 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Document.php @@ -76,7 +76,7 @@ class IdCardV2Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -141,7 +141,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV2Page.php b/src/V1/Product/Fr/IdCard/IdCardV2Page.php index 92824cab..fa77b552 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -21,7 +21,7 @@ class IdCardV2Page extends IdCardV2Document */ public ClassificationField $documentType; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/Payslip/PayslipV3.php b/src/V1/Product/Fr/Payslip/PayslipV3.php index ea597350..cbe8ea45 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3.php @@ -25,7 +25,7 @@ class PayslipV3 extends Inference public static string $endpointVersion = "3"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php index 6532cb1a..262310ab 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php @@ -28,9 +28,13 @@ class PayslipV3BankAccountDetail * @var string|null The SWIFT code of the bank. */ public ?string $swift; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bankName = $rawPrediction["bank_name"] ?? null; $this->iban = $rawPrediction["iban"] ?? null; $this->swift = $rawPrediction["swift"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Document.php b/src/V1/Product/Fr/Payslip/PayslipV3Document.php index 5ad88e01..2e48a34e 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Document.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Document.php @@ -46,7 +46,7 @@ class PayslipV3Document extends Prediction */ public PayslipV3SalaryDetails $salaryDetails; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -115,14 +115,13 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $payPeriodToFieldList = $this->payPeriod !== null ? $this->payPeriod->toFieldList() : ""; - $employeeToFieldList = $this->employee !== null ? $this->employee->toFieldList() : ""; - $employerToFieldList = $this->employer !== null ? $this->employer->toFieldList() : ""; - $bankAccountDetailsToFieldList = $this->bankAccountDetails !== null - ? $this->bankAccountDetails->toFieldList() : ""; - $employmentToFieldList = $this->employment !== null ? $this->employment->toFieldList() : ""; + $payPeriodToFieldList = $this->payPeriod->toFieldList(); + $employeeToFieldList = $this->employee->toFieldList(); + $employerToFieldList = $this->employer->toFieldList(); + $bankAccountDetailsToFieldList = $this->bankAccountDetails->toFieldList(); + $employmentToFieldList = $this->employment->toFieldList(); $salaryDetailsSummary = (string) ($this->salaryDetails); - $payDetailToFieldList = $this->payDetail !== null ? $this->payDetail->toFieldList() : ""; + $payDetailToFieldList = $this->payDetail->toFieldList(); $paidTimeOffSummary = (string) ($this->paidTimeOff); $outStr = ":Pay Period: $payPeriodToFieldList diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php index c1d0d17a..7158c859 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php @@ -44,9 +44,13 @@ class PayslipV3Employee * @var string|null The social security number of the employee. */ public ?string $socialSecurityNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -57,31 +61,15 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->dateOfBirth = $rawPrediction["date_of_birth"] ?? null; $this->firstName = $rawPrediction["first_name"] ?? null; $this->lastName = $rawPrediction["last_name"] ?? null; + $this->pageId = $pageId; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->registrationNumber = $rawPrediction["registration_number"] ?? null; $this->socialSecurityNumber = $rawPrediction["social_security_number"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php index d3fb3b48..56339db2 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php @@ -44,9 +44,13 @@ class PayslipV3Employer * @var string|null The URSSAF number of the employer. */ public ?string $urssafNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -60,28 +64,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->name = $rawPrediction["name"] ?? null; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->urssafNumber = $rawPrediction["urssaf_number"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php index 975ffed6..e9a712a5 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php @@ -44,9 +44,13 @@ class PayslipV3Employment * @var string|null The start date of the employment. */ public ?string $startDate; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -60,28 +64,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->positionLevel = $rawPrediction["position_level"] ?? null; $this->seniorityDate = $rawPrediction["seniority_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php index 33af14ac..f74c3be2 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php @@ -36,9 +36,13 @@ class PayslipV3PaidTimeOff * @var float|null The amount of paid time off used in the period. */ public ?float $used; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -53,11 +57,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["remaining"]) : null; $this->used = isset($rawPrediction["used"]) ? (float) ($rawPrediction["used"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -70,20 +75,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); - $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period); - $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType); - $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); - $outArr["used"] = SummaryHelperV1::formatFloat($this->used); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index c6ae3cfe..e77a1f3b 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php @@ -8,11 +8,12 @@ /** * Information about paid time off. + * @extends ArrayObject */ class PayslipV3PaidTimeOffs extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php index ef3f8f45..0dca548f 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php @@ -56,9 +56,13 @@ class PayslipV3PayDetail * @var float|null The total taxes and deductions of the employee. */ public ?float $totalTaxesAndDeductions; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -85,31 +89,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total_cost_employer"]) : null; $this->totalTaxesAndDeductions = isset($rawPrediction["total_taxes_and_deductions"]) ? (float) ($rawPrediction["total_taxes_and_deductions"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index bb824668..c4142ea0 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -36,9 +36,13 @@ class PayslipV3PayPeriod * @var string|null The year of the pay period. */ public ?string $year; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -50,26 +54,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->paymentDate = $rawPrediction["payment_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; $this->year = $rawPrediction["year"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php index a3c1ec22..63cde6c5 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php @@ -36,9 +36,13 @@ class PayslipV3SalaryDetail * @var float|null The rate of the earning. */ public ?float $rate; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -54,11 +58,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["number"]) : null; $this->rate = isset($rawPrediction["rate"]) ? (float) ($rawPrediction["rate"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -71,20 +76,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["base"] = SummaryHelperV1::formatFloat($this->base); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["number"] = SummaryHelperV1::formatFloat($this->number); - $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index b8534e43..dc182732 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php @@ -8,11 +8,12 @@ /** * Detailed information about the earnings. + * @extends ArrayObject */ class PayslipV3SalaryDetails extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Generated/GeneratedV1.php b/src/V1/Product/Generated/GeneratedV1.php index 66c8492e..c86449cd 100644 --- a/src/V1/Product/Generated/GeneratedV1.php +++ b/src/V1/Product/Generated/GeneratedV1.php @@ -26,7 +26,7 @@ class GeneratedV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Generated/GeneratedV1Document.php b/src/V1/Product/Generated/GeneratedV1Document.php index 93804e73..efe8135d 100644 --- a/src/V1/Product/Generated/GeneratedV1Document.php +++ b/src/V1/Product/Generated/GeneratedV1Document.php @@ -17,17 +17,16 @@ */ class GeneratedV1Document extends GeneratedV1Prediction { - /** @var array Dictionary of all fields in the document. */ + /** @var array Dictionary of all fields in the document. */ public array $fields; /** * GeneratedV1Document constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. + * @param array $rawPrediction Dictionary containing the JSON document response. */ public function __construct(array $rawPrediction) { - parent::__construct($rawPrediction); - $this->fields = []; + parent::__construct(); foreach ($rawPrediction as $fieldName => $fieldContents) { if (is_array($fieldContents) && array_values($fieldContents) === $fieldContents) { $this->fields[$fieldName] = new GeneratedListField($fieldContents); diff --git a/src/V1/Product/Generated/GeneratedV1Page.php b/src/V1/Product/Generated/GeneratedV1Page.php index a5ec62e1..197f480a 100644 --- a/src/V1/Product/Generated/GeneratedV1Page.php +++ b/src/V1/Product/Generated/GeneratedV1Page.php @@ -17,17 +17,19 @@ */ class GeneratedV1Page extends GeneratedV1Prediction { - /** @var array Dictionary of all fields in the document */ + /** + * @var array Dictionary of all fields in the document. + */ public array $fields; /** * GeneratedV1Page constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. + * @param array $rawPrediction Dictionary containing the JSON document response. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) { - parent::__construct($rawPrediction); + parent::__construct(); $this->fields = []; foreach ($rawPrediction as $fieldName => $fieldContents) { if (is_array($fieldContents) && array_values($fieldContents) === $fieldContents) { diff --git a/src/V1/Product/Generated/GeneratedV1Prediction.php b/src/V1/Product/Generated/GeneratedV1Prediction.php index 36381bfd..5b4680bf 100644 --- a/src/V1/Product/Generated/GeneratedV1Prediction.php +++ b/src/V1/Product/Generated/GeneratedV1Prediction.php @@ -26,9 +26,8 @@ class GeneratedV1Prediction extends Prediction /** * GeneratedV1Prediction constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. */ - public function __construct(array $rawPrediction) + public function __construct() { $this->fields = []; } diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php index b28bbcfd..ec3f5e2f 100644 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php @@ -25,7 +25,7 @@ class IndianPassportV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php index bee6ada5..9c18d6d8 100644 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php @@ -109,7 +109,7 @@ class IndianPassportV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/InternationalId/InternationalIdV2.php b/src/V1/Product/InternationalId/InternationalIdV2.php index faf9401b..ae5b8456 100644 --- a/src/V1/Product/InternationalId/InternationalIdV2.php +++ b/src/V1/Product/InternationalId/InternationalIdV2.php @@ -25,7 +25,7 @@ class InternationalIdV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/InternationalId/InternationalIdV2Document.php b/src/V1/Product/InternationalId/InternationalIdV2Document.php index 9286248c..1dbab8e8 100644 --- a/src/V1/Product/InternationalId/InternationalIdV2Document.php +++ b/src/V1/Product/InternationalId/InternationalIdV2Document.php @@ -85,7 +85,7 @@ class InternationalIdV2Document extends Prediction */ public array $surnames; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -143,7 +143,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); @@ -206,7 +206,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["surnames"])) { throw new MindeeUnsetException(); } - $this->surnames = $rawPrediction["surnames"] === null ? [] : array_map( + $this->surnames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); diff --git a/src/V1/Product/Invoice/InvoiceV4.php b/src/V1/Product/Invoice/InvoiceV4.php index 52d05382..6c42a166 100644 --- a/src/V1/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -25,7 +25,7 @@ class InvoiceV4 extends Inference public static string $endpointVersion = "4"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Invoice/InvoiceV4Document.php b/src/V1/Product/Invoice/InvoiceV4Document.php index 6e6ef5b3..90e9e01c 100644 --- a/src/V1/Product/Invoice/InvoiceV4Document.php +++ b/src/V1/Product/Invoice/InvoiceV4Document.php @@ -139,7 +139,7 @@ class InvoiceV4Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -169,7 +169,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["customer_company_registrations"])) { throw new MindeeUnsetException(); } - $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : array_map( + $this->customerCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); @@ -253,7 +253,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] === null ? [] : array_map( + $this->referenceNumbers = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); @@ -281,7 +281,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); @@ -302,7 +302,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_payment_details"])) { throw new MindeeUnsetException(); } - $this->supplierPaymentDetails = $rawPrediction["supplier_payment_details"] === null ? [] : array_map( + $this->supplierPaymentDetails = array_map( static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); diff --git a/src/V1/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php index 016a73e3..ab8f38a6 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItem.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -48,9 +48,13 @@ class InvoiceV4LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -70,11 +74,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -90,23 +95,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php index 2cd8f84e..3872ce76 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -8,11 +8,12 @@ /** * List of all the line items present on the invoice. + * @extends ArrayObject */ class InvoiceV4LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php index aa16bfb9..7395698a 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php @@ -25,7 +25,7 @@ class InvoiceSplitterV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php index 9b4b8e36..eddfeaad 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php @@ -19,7 +19,7 @@ class InvoiceSplitterV1Document extends Prediction */ public InvoiceSplitterV1InvoicePageGroups $invoicePageGroups; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index 58ca99fe..485b586b 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -20,9 +20,13 @@ class InvoiceSplitterV1InvoicePageGroup * @var int[] List of page indexes that belong to the same invoice (group). */ public array $pageIndexes; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -30,11 +34,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->pageIndexes = $rawPrediction["page_indexes"] ?? []; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -43,16 +48,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["pageIndexes"] = implode(", ", $this->pageIndexes); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index e45521c7..8a7ed60b 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -8,11 +8,12 @@ /** * List of page groups. Each group represents a single invoice within a multi-invoice document. + * @extends ArrayObject */ class InvoiceSplitterV1InvoicePageGroups extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php index 5a6c6180..4eb92a87 100644 --- a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php @@ -25,7 +25,7 @@ class MultiReceiptsDetectorV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php index 3ecb87d6..9ea3cb6c 100644 --- a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php @@ -19,7 +19,7 @@ class MultiReceiptsDetectorV1Document extends Prediction */ public array $receipts; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -28,7 +28,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["receipts"])) { throw new MindeeUnsetException(); } - $this->receipts = $rawPrediction["receipts"] === null ? [] : array_map( + $this->receipts = array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["receipts"] ); diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php index f966c8cc..58992769 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php @@ -25,7 +25,7 @@ class NutritionFactsLabelV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php index ebd7881d..99a1685a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php @@ -28,9 +28,13 @@ class NutritionFactsLabelV1AddedSugar * @var float|null The amount of added sugars per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -43,24 +47,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index 25e3f0f5..bd50febe 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -28,9 +28,13 @@ class NutritionFactsLabelV1Calorie * @var float|null The amount of calories per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -43,24 +47,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 65d6f30f..4ad158a9 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1Cholesterol * @var float|null The amount of cholesterol per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index 89cfbe7b..8fc17960 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1DietaryFiber * @var float|null The amount of dietary fiber per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php index 27f8f65b..b2864001 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php @@ -71,7 +71,7 @@ class NutritionFactsLabelV1Document extends Prediction */ public NutritionFactsLabelV1TransFat $transFat; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -182,18 +182,18 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $servingSizeToFieldList = $this->servingSize !== null ? $this->servingSize->toFieldList() : ""; - $caloriesToFieldList = $this->calories !== null ? $this->calories->toFieldList() : ""; - $totalFatToFieldList = $this->totalFat !== null ? $this->totalFat->toFieldList() : ""; - $saturatedFatToFieldList = $this->saturatedFat !== null ? $this->saturatedFat->toFieldList() : ""; - $transFatToFieldList = $this->transFat !== null ? $this->transFat->toFieldList() : ""; - $cholesterolToFieldList = $this->cholesterol !== null ? $this->cholesterol->toFieldList() : ""; - $totalCarbohydrateToFieldList = $this->totalCarbohydrate !== null ? $this->totalCarbohydrate->toFieldList() : ""; - $dietaryFiberToFieldList = $this->dietaryFiber !== null ? $this->dietaryFiber->toFieldList() : ""; - $totalSugarsToFieldList = $this->totalSugars !== null ? $this->totalSugars->toFieldList() : ""; - $addedSugarsToFieldList = $this->addedSugars !== null ? $this->addedSugars->toFieldList() : ""; - $proteinToFieldList = $this->protein !== null ? $this->protein->toFieldList() : ""; - $sodiumToFieldList = $this->sodium !== null ? $this->sodium->toFieldList() : ""; + $servingSizeToFieldList = $this->servingSize->toFieldList(); + $caloriesToFieldList = $this->calories->toFieldList(); + $totalFatToFieldList = $this->totalFat->toFieldList(); + $saturatedFatToFieldList = $this->saturatedFat->toFieldList(); + $transFatToFieldList = $this->transFat->toFieldList(); + $cholesterolToFieldList = $this->cholesterol->toFieldList(); + $totalCarbohydrateToFieldList = $this->totalCarbohydrate->toFieldList(); + $dietaryFiberToFieldList = $this->dietaryFiber->toFieldList(); + $totalSugarsToFieldList = $this->totalSugars->toFieldList(); + $addedSugarsToFieldList = $this->addedSugars->toFieldList(); + $proteinToFieldList = $this->protein->toFieldList(); + $sodiumToFieldList = $this->sodium->toFieldList(); $nutrientsSummary = (string) ($this->nutrients); $outStr = ":Serving per Box: $this->servingPerBox diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php index 4eee0bf5..0844de18 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php @@ -36,15 +36,20 @@ class NutritionFactsLabelV1Nutrient * @var string|null The unit of measurement for the amount of nutrients. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->name = $rawPrediction["name"] ?? null; @@ -57,7 +62,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -70,20 +75,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 17cf7bb1..f953250a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php @@ -8,11 +8,12 @@ /** * The amount of nutrients in the product. + * @extends ArrayObject */ class NutritionFactsLabelV1Nutrients extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php index 0bb17e53..b2f9ee77 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1Protein * @var float|null The amount of protein per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index e2b4411c..ef66b756 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1SaturatedFat * @var float|null The amount of saturated fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index a3330f4d..175f9d3f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -24,9 +24,13 @@ class NutritionFactsLabelV1ServingSize * @var string|null The unit for the amount of a single serving. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -36,23 +40,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->amount = isset($rawPrediction["amount"]) ? (float) ($rawPrediction["amount"]) : null; $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index 9a3732d6..0a0c434f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -32,15 +32,20 @@ class NutritionFactsLabelV1Sodium * @var string|null The unit of measurement for the amount of sodium. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -50,23 +55,9 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unit = $rawPrediction["unit"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index 3f19e755..9d6535e9 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalCarbohydrate * @var float|null The amount of total carbohydrates per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index d6a9722b..d16ec158 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalFat * @var float|null The amount of total fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index 12efdc4d..56c7290f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalSugar * @var float|null The amount of total sugars per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { @@ -70,6 +62,7 @@ private function printableValues(): array $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } + /** * Output in a format suitable for inclusion in a field list. * diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index a62150fa..6155f811 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TransFat * @var float|null The amount of trans fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php index a0341058..0613fb95 100644 --- a/src/V1/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -25,7 +25,7 @@ class PassportV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Passport/PassportV1Document.php b/src/V1/Product/Passport/PassportV1Document.php index 455a9b65..a560bb14 100644 --- a/src/V1/Product/Passport/PassportV1Document.php +++ b/src/V1/Product/Passport/PassportV1Document.php @@ -60,7 +60,7 @@ class PassportV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -104,7 +104,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Receipt/ReceiptV5.php b/src/V1/Product/Receipt/ReceiptV5.php index 9eb95949..0bdb1df2 100644 --- a/src/V1/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -25,7 +25,7 @@ class ReceiptV5 extends Inference public static string $endpointVersion = "5"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Receipt/ReceiptV5Document.php b/src/V1/Product/Receipt/ReceiptV5Document.php index 475fac30..ebd43027 100644 --- a/src/V1/Product/Receipt/ReceiptV5Document.php +++ b/src/V1/Product/Receipt/ReceiptV5Document.php @@ -89,7 +89,7 @@ class ReceiptV5Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -154,7 +154,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); diff --git a/src/V1/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php index c20758fc..f2a3c2ac 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItem.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -32,15 +32,20 @@ class ReceiptV5LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->description = $rawPrediction["description"] ?? null; $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; @@ -52,7 +57,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -64,19 +69,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php index 0f2a2ecc..c63326cf 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -8,11 +8,12 @@ /** * List of all line items on the receipt. + * @extends ArrayObject */ class ReceiptV5LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1.php b/src/V1/Product/Resume/ResumeV1.php index 7d13f62f..a00b073a 100644 --- a/src/V1/Product/Resume/ResumeV1.php +++ b/src/V1/Product/Resume/ResumeV1.php @@ -25,7 +25,7 @@ class ResumeV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php index e581be91..9fb9d6ea 100644 --- a/src/V1/Product/Resume/ResumeV1Certificate.php +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -32,15 +32,20 @@ class ResumeV1Certificate * @var string|null The year when a certificate was issued or received. */ public ?string $year; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->grade = $rawPrediction["grade"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->provider = $rawPrediction["provider"] ?? null; @@ -49,7 +54,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -61,19 +66,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider); - $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php index 07c2c7c3..cc99b87b 100644 --- a/src/V1/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -8,11 +8,12 @@ /** * The list of certificates obtained by the candidate. + * @extends ArrayObject */ class ResumeV1Certificates extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1Document.php b/src/V1/Product/Resume/ResumeV1Document.php index 5ae78d24..187e74ae 100644 --- a/src/V1/Product/Resume/ResumeV1Document.php +++ b/src/V1/Product/Resume/ResumeV1Document.php @@ -84,7 +84,7 @@ class ResumeV1Document extends Prediction */ public array $surnames; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -135,14 +135,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["hard_skills"])) { throw new MindeeUnsetException(); } - $this->hardSkills = $rawPrediction["hard_skills"] === null ? [] : array_map( + $this->hardSkills = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["hard_skills"] ); @@ -198,14 +198,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["soft_skills"])) { throw new MindeeUnsetException(); } - $this->softSkills = $rawPrediction["soft_skills"] === null ? [] : array_map( + $this->softSkills = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["soft_skills"] ); if (!isset($rawPrediction["surnames"])) { throw new MindeeUnsetException(); } - $this->surnames = $rawPrediction["surnames"] === null ? [] : array_map( + $this->surnames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); diff --git a/src/V1/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php index 811f24ed..afaffba3 100644 --- a/src/V1/Product/Resume/ResumeV1Education.php +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -44,15 +44,20 @@ class ResumeV1Education * @var string|null The year when the education program or course began. */ public ?string $startYear; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->degreeDomain = $rawPrediction["degree_domain"] ?? null; $this->degreeType = $rawPrediction["degree_type"] ?? null; $this->endMonth = $rawPrediction["end_month"] ?? null; @@ -64,7 +69,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -79,22 +84,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain); - $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType); - $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school); - $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php index 7848a327..464e5b77 100644 --- a/src/V1/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -8,11 +8,12 @@ /** * The list of the candidate's educational background. + * @extends ArrayObject */ class ResumeV1Educations extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1Language.php b/src/V1/Product/Resume/ResumeV1Language.php index 4a603d66..70846b48 100644 --- a/src/V1/Product/Resume/ResumeV1Language.php +++ b/src/V1/Product/Resume/ResumeV1Language.php @@ -24,22 +24,27 @@ class ResumeV1Language * @var string|null The candidate's level for the language. */ public ?string $level; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->language = $rawPrediction["language"] ?? null; $this->level = $rawPrediction["level"] ?? null; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -49,17 +54,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); - $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php index 8587e2b4..04926c22 100644 --- a/src/V1/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -8,11 +8,12 @@ /** * The list of languages that the candidate is proficient in. + * @extends ArrayObject */ class ResumeV1Languages extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php index 62f3b232..4a36558b 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php @@ -52,15 +52,20 @@ class ResumeV1ProfessionalExperience * @var string|null The year when the professional experience began. */ public ?string $startYear; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->contractType = $rawPrediction["contract_type"] ?? null; $this->department = $rawPrediction["department"] ?? null; $this->description = $rawPrediction["description"] ?? null; @@ -74,7 +79,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -91,24 +96,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType); - $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer); - $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role); - $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index c1509b4c..eacb47c6 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -8,11 +8,12 @@ /** * The list of the candidate's professional experiences. + * @extends ArrayObject */ class ResumeV1ProfessionalExperiences extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php index 57c91536..83544ef1 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php @@ -24,22 +24,27 @@ class ResumeV1SocialNetworksUrl * @var string|null The URL of the social network. */ public ?string $url; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->name = $rawPrediction["name"] ?? null; $this->url = $rawPrediction["url"] ?? null; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -49,17 +54,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index 162c7eb1..fe48fc16 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -8,11 +8,12 @@ /** * The list of social network profiles of the candidate. + * @extends ArrayObject */ class ResumeV1SocialNetworksUrls extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1.php b/src/V1/Product/Us/BankCheck/BankCheckV1.php index 6cc17656..fca87b42 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1.php @@ -25,7 +25,7 @@ class BankCheckV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1Document.php b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php index cfbae322..5dba7666 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1Document.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php @@ -41,7 +41,7 @@ class BankCheckV1Document extends Prediction */ public StringField $routingNumber; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -78,7 +78,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["payees"])) { throw new MindeeUnsetException(); } - $this->payees = $rawPrediction["payees"] === null ? [] : array_map( + $this->payees = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["payees"] ); diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 32a80475..7609ba44 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -21,7 +21,7 @@ class BankCheckV1Page extends BankCheckV1Document */ public array $signaturesPositions; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -31,7 +31,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $rawPrediction["check_position"], $pageId ); - $this->signaturesPositions = $rawPrediction["signatures_positions"] === null ? [] : array_map( + $this->signaturesPositions = array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["signatures_positions"] ); diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php index 16f992b8..c3f947bf 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php @@ -25,7 +25,7 @@ class HealthcareCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php index 8d451fb0..3f2b8328 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php @@ -24,15 +24,20 @@ class HealthcareCardV1Copay * @var string|null The name of the service. */ public ?string $serviceName; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->serviceFees = isset($rawPrediction["service_fees"]) ? (float) ($rawPrediction["service_fees"]) : null; $this->serviceName = $rawPrediction["service_name"] ?? null; @@ -40,7 +45,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -50,17 +55,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index 880a53e5..a49f1ac1 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php @@ -8,11 +8,12 @@ /** * Copayments for covered services. + * @extends ArrayObject */ class HealthcareCardV1Copays extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php index 20fb58bd..8dfe0b6e 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php @@ -72,7 +72,7 @@ class HealthcareCardV1Document extends Prediction */ public StringField $rxPcn; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -95,7 +95,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["dependents"])) { throw new MindeeUnsetException(); } - $this->dependents = $rawPrediction["dependents"] === null ? [] : array_map( + $this->dependents = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["dependents"] ); diff --git a/src/V1/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php index 2a151540..cd726bf0 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3.php +++ b/src/V1/Product/Us/UsMail/UsMailV3.php @@ -25,7 +25,7 @@ class UsMailV3 extends Inference public static string $endpointVersion = "3"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/UsMail/UsMailV3Document.php b/src/V1/Product/Us/UsMail/UsMailV3Document.php index 58095f7d..83cf6922 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3Document.php +++ b/src/V1/Product/Us/UsMail/UsMailV3Document.php @@ -36,7 +36,7 @@ class UsMailV3Document extends Prediction */ public StringField $senderName; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -59,7 +59,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["recipient_names"])) { throw new MindeeUnsetException(); } - $this->recipientNames = $rawPrediction["recipient_names"] === null ? [] : array_map( + $this->recipientNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["recipient_names"] ); @@ -84,7 +84,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $senderAddressToFieldList = $this->senderAddress !== null ? $this->senderAddress->toFieldList() : ""; + $senderAddressToFieldList = $this->senderAddress->toFieldList(); $recipientNames = implode( "\n ", $this->recipientNames diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index ccfcbf6c..42834357 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -48,15 +48,20 @@ class UsMailV3RecipientAddress * @var string|null The unit number of the recipient's address. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->isAddressChange = $rawPrediction["is_address_change"] ?? null; @@ -69,7 +74,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -85,23 +90,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); - $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php index 28362408..a307436f 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php @@ -8,11 +8,12 @@ /** * The addresses of the recipients. + * @extends ArrayObject */ class UsMailV3RecipientAddresses extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php index deba2f0c..20091d0a 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php @@ -36,15 +36,20 @@ class UsMailV3SenderAddress * @var string|null The street of the sender's address. */ public ?string $street; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->postalCode = $rawPrediction["postal_code"] ?? null; @@ -52,24 +57,9 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->street = $rawPrediction["street"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index c54c6b33..796a19d1 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -26,6 +26,11 @@ abstract class BaseParameters */ public array $webhooksIds; + /** + * @var string Slug of the endpoint. + */ + public static string $slug; + /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. @@ -46,7 +51,7 @@ public function __construct(string $modelId, ?string $alias, ?array $webhooksIds } /** - * @return array Hash representation. + * @return array Hash representation. */ public function asHash(): array { @@ -56,7 +61,7 @@ public function asHash(): array } - if (isset($this->webhooksIds) && count($this->webhooksIds) > 0) { + if (!empty($this->webhooksIds)) { $outHash['webhook_ids'] = implode(',', $this->webhooksIds); } return $outHash; diff --git a/src/V2/FileOperations/CropFiles.php b/src/V2/FileOperations/CropFiles.php index 01ad0eee..9f522535 100644 --- a/src/V2/FileOperations/CropFiles.php +++ b/src/V2/FileOperations/CropFiles.php @@ -13,8 +13,7 @@ /** * Cropped files collection wrapper. - * - * * @extends ArrayObject + * @extends ArrayObject */ class CropFiles extends ArrayObject { @@ -44,7 +43,6 @@ public function saveAllToDisk( ?string $fileFormat = null, int $quality = 100 ): void { - $format ??= $fileFormat; $idx = 1; foreach ($this as $crop) { @@ -53,7 +51,7 @@ public function saveAllToDisk( $crop->filename = $filename; try { - $crop->writeToFile($path, $format, $quality); + $crop->writeToFile($path, $fileFormat, $quality); } catch (ImagickException $e) { throw new MindeeException('Failed to save crop to disk.', 0, $e); } diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index 50b11f49..9b9fd0cf 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -16,7 +16,7 @@ /** * Split files collection wrapper. * - * * @extends ArrayObject + * @extends ArrayObject */ class SplitFiles extends ArrayObject { @@ -56,7 +56,7 @@ public function saveAllToDisk(string $path, string $prefix = 'split'): void try { $split->writeToFile($filePath); } catch (Exception $e) { - throw new MindeeException('Failed to save split to disk.', 0, $e->getMessage()); + throw new MindeeException('Failed to save split to disk.', 0, previous: $e); } ++$idx; diff --git a/src/V2/HTTP/MindeeAPIV2.php b/src/V2/HTTP/MindeeAPIV2.php index eba9adf8..eccf53fa 100644 --- a/src/V2/HTTP/MindeeAPIV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -22,7 +22,6 @@ use Mindee\V2\Parsing\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\JobResponse; -use Mindee\V2\Product\Extraction\ExtractionResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; @@ -103,7 +102,7 @@ public function __construct(?string $apiKey) $this->baseUrl = API_V2_BASE_URL_DEFAULT; $this->requestTimeout = API_V2_TIMEOUT_DEFAULT; $this->setFromEnv(); - if (!$this->apiKey || $this->apiKey === '') { + if ($this->apiKey === '') { throw new MindeeException( "Missing API key for call," . " check your Client configuration.You can set this using the " @@ -181,7 +180,7 @@ public function reqPostEnqueue(InputSource $inputDoc, BaseParameters $params): J * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array $result Raw HTTP response array with 'data' and 'code' keys. * @return T A response containing parsing results. * @throws MindeeException Throws if HTTP status indicates an error or deserialization fails. */ @@ -210,7 +209,7 @@ private function processResponse( /** * Process the HTTP response and return the appropriate response object. * - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array $result Raw HTTP response array with 'data' and 'code' keys. * @return JobResponse The processed response object. * @throws MindeeException Throws if HTTP status indicates an error or deserialization fails. * @throws MindeeApiException Throws if the response type is not recognized. @@ -242,11 +241,8 @@ private function processJobResponse(array $result): JobResponse */ public function reqGetJob(string $jobId): JobResponse { - if (!isset($jobId)) { - throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } $response = $this->sendGetRequest($this->baseUrl . "/jobs/$jobId"); - return $this->processJobResponse($response, JobResponse::class); + return $this->processJobResponse($response); } @@ -263,10 +259,6 @@ public function reqGetResult( string $responseClass, string $resultId ): BaseResponse { - if (!isset($responseClass) || !isset($resultId)) { - throw new MindeeException("Response class and job ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } - try { $slugProperty = new ReflectionProperty($responseClass, 'slug'); } catch (ReflectionException $e) { @@ -293,18 +285,15 @@ public function reqGetResultFromUrl( string $responseClass, string $resultUrl ): BaseResponse { - if (!isset($responseClass) || !isset($resultUrl)) { - throw new MindeeException("Response class and result URL must be provided.", ErrorCode::USER_INPUT_ERROR); - } $response = $this->sendGetRequest($resultUrl); return $this->processResponse($responseClass, $response); } /** * Init a CURL channel with common params. - * @return false|resource Returns a valid CURL channel. + * @return boolean|CurlHandle Returns a valid CURL channel. */ - private function initChannel() + private function initChannel(): bool|CurlHandle { $ch = curl_init(); curl_setopt( @@ -326,7 +315,7 @@ private function initChannel() /** * Makes a GET call to retrieve a job. * @param string $url URL of the job. - * @return array Server response. + * @return array Server response. */ private function sendGetRequest(string $url): array { @@ -347,13 +336,13 @@ private function sendGetRequest(string $url): array * * @param InputSource $inputSource File to upload. * @param BaseParameters $params Parameters. + * @return array Server response. * @throws MindeeException Throws if the cURL operation doesn't go succeed. */ private function documentEnqueuePost( InputSource $inputSource, BaseParameters $params ): array { - /** @var CurlHandle $ch */ $ch = $this->initChannel(); $postFields = $params->asHash(); @@ -380,7 +369,7 @@ private function documentEnqueuePost( } /** - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array $result Raw HTTP response array with 'data' and 'code' keys. * @throws MindeeV2HttpException Throws if the HTTP status indicates an error. * @throws MindeeV2HttpUnknownException Throws if the server sends an unexpected reply. */ diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/BaseInference.php index d25df119..acf73bd3 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -35,7 +35,7 @@ abstract class BaseInference public InferenceJob $job; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/ErrorItem.php b/src/V2/Parsing/ErrorItem.php index 75bc17d8..25878920 100644 --- a/src/V2/Parsing/ErrorItem.php +++ b/src/V2/Parsing/ErrorItem.php @@ -19,7 +19,7 @@ class ErrorItem public string $detail; /** - * @param array $rawResponse Raw error response from the API. + * @param array $rawResponse Raw error response from the API. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/ErrorResponse.php b/src/V2/Parsing/ErrorResponse.php index a4be31a1..c7164c45 100644 --- a/src/V2/Parsing/ErrorResponse.php +++ b/src/V2/Parsing/ErrorResponse.php @@ -30,21 +30,21 @@ class ErrorResponse */ public ?string $code; /** - * @var array|mixed|null A list of explicit error details. + * @var array|null A list of explicit error details. */ public ?array $errors; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->status = $serverResponse['status']; - $this->detail = $serverResponse['detail']; - $this->title = $serverResponse['title'] ?? null; - $this->code = $serverResponse['code'] ?? null; - if (isset($serverResponse['errors']) && is_array($serverResponse['errors'])) { - $this->errors = array_map(static fn($error) => new ErrorItem($error), $serverResponse['errors']); + $this->status = $rawResponse['status']; + $this->detail = $rawResponse['detail']; + $this->title = $rawResponse['title'] ?? null; + $this->code = $rawResponse['code'] ?? null; + if (isset($rawResponse['errors']) && is_array($rawResponse['errors'])) { + $this->errors = array_map(static fn($error) => new ErrorItem($error), $rawResponse['errors']); } else { $this->errors = []; } diff --git a/src/V2/Parsing/Inference/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php index 5ec3ab3e..b4c45cbd 100644 --- a/src/V2/Parsing/Inference/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -10,12 +10,12 @@ abstract class BaseResponse { /** - * @var array Raw HTTP response from the server. + * @var array Raw HTTP response from the server. */ private array $rawHttp; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ protected function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/Inference/Field/BaseField.php b/src/V2/Parsing/Inference/Field/BaseField.php index 39e7a5a4..7f8f2d37 100644 --- a/src/V2/Parsing/Inference/Field/BaseField.php +++ b/src/V2/Parsing/Inference/Field/BaseField.php @@ -29,7 +29,7 @@ abstract class BaseField public ?FieldConfidence $confidence; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer $indentLevel Level of indentation for rst display. */ public function __construct(array $rawPrediction, int $indentLevel = 0) @@ -47,7 +47,7 @@ public function __construct(array $rawPrediction, int $indentLevel = 0) } /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. * @param integer $indentLevel Level of indentation for rst display. * @throws MindeeApiException Throws if the field type isn't recognized. */ @@ -66,4 +66,13 @@ public static function createField(array $rawPrediction, int $indentLevel = 0): sprintf('Unrecognized field format in %s.', json_encode($rawPrediction)) ); } + + /** + * Base str-rep. Do not use. + * @throws MindeeApiException + */ + public function __toString(): string + { + throw new MindeeApiException('Not implemented'); + } } diff --git a/src/V2/Parsing/Inference/Field/FieldLocation.php b/src/V2/Parsing/Inference/Field/FieldLocation.php index ea39cda2..29f8fbcb 100644 --- a/src/V2/Parsing/Inference/Field/FieldLocation.php +++ b/src/V2/Parsing/Inference/Field/FieldLocation.php @@ -27,13 +27,13 @@ class FieldLocation public ?int $page; /** - * @param array $serverResponse Raw server response. + * @param array $rawResponse Raw server response. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->polygon = isset($serverResponse['polygon']) ? new Polygon($serverResponse['polygon']) : null; - $this->page = isset($serverResponse['page']) && is_int($serverResponse['page']) - ? $serverResponse['page'] + $this->polygon = isset($rawResponse['polygon']) ? new Polygon($rawResponse['polygon']) : null; + $this->page = isset($rawResponse['page']) && is_int($rawResponse['page']) + ? $rawResponse['page'] : null; } diff --git a/src/V2/Parsing/Inference/Field/InferenceFields.php b/src/V2/Parsing/Inference/Field/InferenceFields.php index 871d25ef..c7a90878 100644 --- a/src/V2/Parsing/Inference/Field/InferenceFields.php +++ b/src/V2/Parsing/Inference/Field/InferenceFields.php @@ -11,6 +11,7 @@ /** * Collection of inference fields. + * @extends ArrayObject */ class InferenceFields extends ArrayObject { @@ -25,14 +26,14 @@ class InferenceFields extends ArrayObject private int $indentLevel; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { $this->indentLevel = $indentLevel; - foreach ($serverResponse as $key => $value) { + foreach ($rawResponse as $key => $value) { $this->fields[$key] = BaseField::createField($value, 1); } parent::__construct($this->fields); @@ -42,16 +43,11 @@ public function __construct(array $serverResponse, int $indentLevel = 0) * Get a field by key. * * @param string $fieldName Field key to retrieve. - * @return SimpleField|ObjectField|ListField * @throws InvalidArgumentException When the field does not exist. */ - public function get(string $fieldName) + public function get(string $fieldName): SimpleField|ObjectField|ListField { - $field = $this->fields[$fieldName]; - if ($field === null) { - throw new InvalidArgumentException("Field $fieldName does not exist."); - } - return $field; + return $this->fields[$fieldName] ?? throw new InvalidArgumentException("Field $fieldName does not exist."); } /** diff --git a/src/V2/Parsing/Inference/Field/ListField.php b/src/V2/Parsing/Inference/Field/ListField.php index 5fb69016..94086bab 100644 --- a/src/V2/Parsing/Inference/Field/ListField.php +++ b/src/V2/Parsing/Inference/Field/ListField.php @@ -16,29 +16,27 @@ class ListField extends BaseField { /** - * Items contained in the list. - * - * @var ObjectField + * @var array Items contained in the list. */ public array $items; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. * @throws MindeeApiException Throws if deserialization fails. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); + parent::__construct($rawResponse, $indentLevel); - if (!array_key_exists('items', $serverResponse) || !is_array($serverResponse['items'])) { + if (!array_key_exists('items', $rawResponse) || !is_array($rawResponse['items'])) { throw new MindeeApiException( - sprintf('Expected "items" to be an array in %s.', json_encode($serverResponse)) + sprintf('Expected "items" to be an array in %s.', json_encode($rawResponse)) ); } $this->items = []; - foreach ($serverResponse['items'] as $item) { + foreach ($rawResponse['items'] as $item) { $this->items[] = BaseField::createField($item, $indentLevel + 1); } } @@ -53,7 +51,7 @@ public function __toString(): string $parts = ['']; foreach ($this->items as $item) { - if ($item === null) { + if (null === $item) { continue; } diff --git a/src/V2/Parsing/Inference/Field/ObjectField.php b/src/V2/Parsing/Inference/Field/ObjectField.php index 48425d68..0f54bd5f 100644 --- a/src/V2/Parsing/Inference/Field/ObjectField.php +++ b/src/V2/Parsing/Inference/Field/ObjectField.php @@ -16,15 +16,15 @@ class ObjectField extends BaseField public InferenceFields $fields; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); + parent::__construct($rawResponse, $indentLevel); $this->fields = new InferenceFields( - $serverResponse['fields'], + $rawResponse['fields'], $this->indentLevel + 1 ); } diff --git a/src/V2/Parsing/Inference/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php index be162ce7..cf424d84 100644 --- a/src/V2/Parsing/Inference/Field/SimpleField.php +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -19,13 +19,13 @@ class SimpleField extends BaseField public $value; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); - $this->value = array_key_exists('value', $serverResponse) ? $serverResponse['value'] : null; + parent::__construct($rawResponse, $indentLevel); + $this->value = array_key_exists('value', $rawResponse) ? $rawResponse['value'] : null; if (is_int($this->value)) { $this->value = (float) $this->value; } diff --git a/src/V2/Parsing/Inference/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php index edb8ce8d..b1b03053 100644 --- a/src/V2/Parsing/Inference/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -50,16 +50,16 @@ class InferenceActiveOptions public DataSchemaActiveOption $dataSchema; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->rag = $serverResponse['rag']; - $this->rawText = $serverResponse['raw_text']; - $this->polygon = $serverResponse['polygon']; - $this->confidence = $serverResponse['confidence']; - $this->textContext = $serverResponse['text_context']; - $this->dataSchema = new DataSchemaActiveOption($serverResponse['data_schema']); + $this->rag = $rawResponse['rag']; + $this->rawText = $rawResponse['raw_text']; + $this->polygon = $rawResponse['polygon']; + $this->confidence = $rawResponse['confidence']; + $this->textContext = $rawResponse['text_context']; + $this->dataSchema = new DataSchemaActiveOption($rawResponse['data_schema']); } /** diff --git a/src/V2/Parsing/Inference/InferenceFile.php b/src/V2/Parsing/Inference/InferenceFile.php index f9ed9674..a50b97fc 100644 --- a/src/V2/Parsing/Inference/InferenceFile.php +++ b/src/V2/Parsing/Inference/InferenceFile.php @@ -30,14 +30,14 @@ class InferenceFile public string $mimeType; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->name = $serverResponse['name']; - $this->alias = $serverResponse['alias']; - $this->pageCount = $serverResponse['page_count']; - $this->mimeType = $serverResponse['mime_type']; + $this->name = $rawResponse['name']; + $this->alias = $rawResponse['alias']; + $this->pageCount = $rawResponse['page_count']; + $this->mimeType = $rawResponse['mime_type']; } /** diff --git a/src/V2/Parsing/Inference/InferenceJob.php b/src/V2/Parsing/Inference/InferenceJob.php index 4ec2303f..92aadfc6 100644 --- a/src/V2/Parsing/Inference/InferenceJob.php +++ b/src/V2/Parsing/Inference/InferenceJob.php @@ -15,11 +15,11 @@ class InferenceJob public string $id; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; } /** diff --git a/src/V2/Parsing/Inference/InferenceModel.php b/src/V2/Parsing/Inference/InferenceModel.php index 390dfc75..a3e5aac2 100644 --- a/src/V2/Parsing/Inference/InferenceModel.php +++ b/src/V2/Parsing/Inference/InferenceModel.php @@ -15,11 +15,11 @@ class InferenceModel public string $id; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; } /** diff --git a/src/V2/Parsing/Inference/RAGMetadata.php b/src/V2/Parsing/Inference/RAGMetadata.php index b96a07a9..5a5ed492 100644 --- a/src/V2/Parsing/Inference/RAGMetadata.php +++ b/src/V2/Parsing/Inference/RAGMetadata.php @@ -15,7 +15,7 @@ class RAGMetadata public ?string $retrievedDocumentId; /** - * @param array $rawResponse Raw response from the server. + * @param array $rawResponse Raw response from the server. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/Inference/RawText.php b/src/V2/Parsing/Inference/RawText.php index 1afb247f..4e2b94f2 100644 --- a/src/V2/Parsing/Inference/RawText.php +++ b/src/V2/Parsing/Inference/RawText.php @@ -17,12 +17,12 @@ class RawText public array $pages; /** - * @param array $serverResponse JSON response from the server. + * @param array $rawResponse JSON response from the server. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - if (array_key_exists('pages', $serverResponse)) { - foreach ($serverResponse['pages'] as $page) { + if (array_key_exists('pages', $rawResponse)) { + foreach ($rawResponse['pages'] as $page) { $this->pages[] = new RawTextPage($page); } } else { diff --git a/src/V2/Parsing/Inference/RawTextPage.php b/src/V2/Parsing/Inference/RawTextPage.php index 60db7c3c..bb5476ae 100644 --- a/src/V2/Parsing/Inference/RawTextPage.php +++ b/src/V2/Parsing/Inference/RawTextPage.php @@ -11,16 +11,15 @@ class RawTextPage { /** * Page content as a single string. - * */ - public string $content; + public ?string $content; /** - * @param array $serverResponse JSON response from the server. + * @param array $rawResponse JSON response from the server. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->content = $serverResponse['content']; + $this->content = $rawResponse['content']; } /** diff --git a/src/V2/Parsing/Job.php b/src/V2/Parsing/Job.php index 59e2d61b..e7a39058 100644 --- a/src/V2/Parsing/Job.php +++ b/src/V2/Parsing/Job.php @@ -70,34 +70,34 @@ class Job public array $webhooks; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; - $this->status = $serverResponse['status']; + $this->status = $rawResponse['status']; $this->error = null; if ( - !empty($serverResponse['error']) + !empty($rawResponse['error']) ) { - $this->error = new ErrorResponse($serverResponse['error']); + $this->error = new ErrorResponse($rawResponse['error']); } - $this->createdAt = $this->parseDate($serverResponse['created_at']); - $this->completedAt = isset($serverResponse['completed_at']) - ? $this->parseDate($serverResponse['completed_at']) + $this->createdAt = $this->parseDate($rawResponse['created_at']); + $this->completedAt = isset($rawResponse['completed_at']) + ? $this->parseDate($rawResponse['completed_at']) : null; - $this->modelId = $serverResponse['model_id']; - $this->pollingUrl = $serverResponse['polling_url']; - $this->filename = $serverResponse['filename']; - $this->resultUrl = $serverResponse['result_url'] ?? null; - $this->alias = $serverResponse['alias']; + $this->modelId = $rawResponse['model_id']; + $this->pollingUrl = $rawResponse['polling_url']; + $this->filename = $rawResponse['filename']; + $this->resultUrl = $rawResponse['result_url'] ?? null; + $this->alias = $rawResponse['alias']; $this->webhooks = []; - if (array_key_exists("webhooks", $serverResponse)) { - foreach ($serverResponse['webhooks'] as $webhook) { + if (array_key_exists("webhooks", $rawResponse)) { + foreach ($rawResponse['webhooks'] as $webhook) { $this->webhooks[] = new JobWebhook($webhook); } } @@ -110,7 +110,7 @@ public function __construct(array $serverResponse) */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } diff --git a/src/V2/Parsing/JobResponse.php b/src/V2/Parsing/JobResponse.php index c0afcee6..7891d070 100644 --- a/src/V2/Parsing/JobResponse.php +++ b/src/V2/Parsing/JobResponse.php @@ -17,7 +17,7 @@ class JobResponse extends BaseResponse public Job $job; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/JobWebhook.php b/src/V2/Parsing/JobWebhook.php index 5be52b05..7d851d1a 100644 --- a/src/V2/Parsing/JobWebhook.php +++ b/src/V2/Parsing/JobWebhook.php @@ -33,17 +33,17 @@ class JobWebhook public ?ErrorResponse $error; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; - $this->createdAt = isset($serverResponse['created_at']) - ? $this->parseDate($serverResponse['created_at']) + $this->id = $rawResponse['id']; + $this->createdAt = isset($rawResponse['created_at']) + ? $this->parseDate($rawResponse['created_at']) : null; - $this->status = $serverResponse['status']; - $this->error = isset($serverResponse['error']) - ? new ErrorResponse($serverResponse['error']) + $this->status = $rawResponse['status']; + $this->error = isset($rawResponse['error']) + ? new ErrorResponse($rawResponse['error']) : null; } @@ -54,7 +54,7 @@ public function __construct(array $serverResponse) */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } diff --git a/src/V2/Product/Classification/ClassificationClassifier.php b/src/V2/Product/Classification/ClassificationClassifier.php index ecbbc029..56a36a3b 100644 --- a/src/V2/Product/Classification/ClassificationClassifier.php +++ b/src/V2/Product/Classification/ClassificationClassifier.php @@ -22,7 +22,7 @@ class ClassificationClassifier public ?ExtractionResponse $extractionResponse; /** - * @param array $rawPrediction Raw prediction array. + * @param array $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V2/Product/Classification/ClassificationInference.php b/src/V2/Product/Classification/ClassificationInference.php index 5ee94dab..452f7d54 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.php @@ -18,7 +18,7 @@ class ClassificationInference extends BaseInference public ClassificationResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Classification/ClassificationResponse.php b/src/V2/Product/Classification/ClassificationResponse.php index f4598522..4033ef89 100644 --- a/src/V2/Product/Classification/ClassificationResponse.php +++ b/src/V2/Product/Classification/ClassificationResponse.php @@ -22,7 +22,7 @@ class ClassificationResponse extends BaseResponse public static string $slug = "classification"; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Classification/ClassificationResult.php b/src/V2/Product/Classification/ClassificationResult.php index e83dfc3a..5a5f88c9 100644 --- a/src/V2/Product/Classification/ClassificationResult.php +++ b/src/V2/Product/Classification/ClassificationResult.php @@ -15,7 +15,7 @@ class ClassificationResult public ClassificationClassifier $classification; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropInference.php b/src/V2/Product/Crop/CropInference.php index cdecf2c8..f2c352b1 100644 --- a/src/V2/Product/Crop/CropInference.php +++ b/src/V2/Product/Crop/CropInference.php @@ -17,7 +17,7 @@ class CropInference extends BaseInference public CropResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropItem.php b/src/V2/Product/Crop/CropItem.php index 54e786ba..ea3963f4 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -27,7 +27,7 @@ class CropItem */ public ?ExtractionResponse $extractionResponse; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropResponse.php b/src/V2/Product/Crop/CropResponse.php index f0a08c62..fb2f3ca8 100644 --- a/src/V2/Product/Crop/CropResponse.php +++ b/src/V2/Product/Crop/CropResponse.php @@ -22,7 +22,7 @@ class CropResponse extends BaseResponse public static string $slug = "crop"; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropResult.php b/src/V2/Product/Crop/CropResult.php index b88b008f..2ee8e3bf 100644 --- a/src/V2/Product/Crop/CropResult.php +++ b/src/V2/Product/Crop/CropResult.php @@ -15,7 +15,7 @@ class CropResult public array $crops; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionInference.php b/src/V2/Product/Extraction/ExtractionInference.php index 83027850..2db9b309 100644 --- a/src/V2/Product/Extraction/ExtractionInference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -24,7 +24,7 @@ class ExtractionInference extends BaseInference public ExtractionResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionResponse.php b/src/V2/Product/Extraction/ExtractionResponse.php index 10037ad0..aaa71e2d 100644 --- a/src/V2/Product/Extraction/ExtractionResponse.php +++ b/src/V2/Product/Extraction/ExtractionResponse.php @@ -22,7 +22,7 @@ class ExtractionResponse extends BaseResponse public static string $slug = "extraction"; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionResult.php b/src/V2/Product/Extraction/ExtractionResult.php index 9d91bbf4..2b26a0bc 100644 --- a/src/V2/Product/Extraction/ExtractionResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -29,17 +29,17 @@ class ExtractionResult public ?RAGMetadata $rag; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->fields = new InferenceFields($serverResponse['fields']); - $this->rawText = isset($serverResponse['raw_text']) - ? new RawText($serverResponse['raw_text']) + $this->fields = new InferenceFields($rawResponse['fields']); + $this->rawText = isset($rawResponse['raw_text']) + ? new RawText($rawResponse['raw_text']) : null; $this->rag = isset( - $serverResponse['rag'] - ) ? new RAGMetadata($serverResponse['rag']) : null; + $rawResponse['rag'] + ) ? new RAGMetadata($rawResponse['rag']) : null; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchema.php b/src/V2/Product/Extraction/Params/DataSchema.php index 54f6de67..bf67ce0b 100644 --- a/src/V2/Product/Extraction/Params/DataSchema.php +++ b/src/V2/Product/Extraction/Params/DataSchema.php @@ -20,7 +20,7 @@ class DataSchema public ?DataSchemaReplace $replace; /** - * @param array|string|DataSchema $dataSchema Raw server response array. + * @param array|string|DataSchema $dataSchema Raw server response array. * @throws InvalidArgumentException Throws if the data schema is invalid. */ public function __construct(self|array|string $dataSchema) @@ -40,7 +40,7 @@ public function __construct(self|array|string $dataSchema) } /** - * @return array JSON representation. + * @return array JSON representation. */ public function toJson(): array { @@ -76,7 +76,7 @@ private function toJsonStringProperSpacing(): string { $jsonStr = json_encode($this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $lines = explode("\n", $jsonStr); - return implode("\n", array_map('self::fixLineSpaces', $lines)) . "\n"; + return implode("\n", array_map(static fn($line) => self::fixLineSpaces($line), $lines)) . "\n"; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index 5003ab40..b8961f3b 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -15,11 +15,11 @@ class DataSchemaActiveOption public bool $replace; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->replace = $serverResponse['replace']; + $this->replace = $rawResponse['replace']; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchemaField.php b/src/V2/Product/Extraction/Params/DataSchemaField.php index 1679db9f..a3d68bec 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaField.php +++ b/src/V2/Product/Extraction/Params/DataSchemaField.php @@ -38,38 +38,38 @@ class DataSchemaField */ public ?bool $uniqueValues; /** - * @var array|null Subfields when type is `nested_object`. Leave empty for other types. + * @var array|null Subfields when type is `nested_object`. Leave empty for other types. */ public ?array $nestedFields; /** - * @var array|null Allowed values when type is `classification`. Leave empty for other types. + * @var array|null Allowed values when type is `classification`. Leave empty for other types. */ public ?array $classificationValues; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->name = $serverResponse['name']; - $this->title = $serverResponse['title']; - $this->isArray = $serverResponse['is_array']; - $this->type = $serverResponse['type']; - $this->description = $serverResponse['description']; - $this->guidelines = $serverResponse['guidelines']; - if (isset($serverResponse['unique_values'])) { - $this->uniqueValues = $serverResponse['unique_values']; + $this->name = $rawResponse['name']; + $this->title = $rawResponse['title']; + $this->isArray = $rawResponse['is_array']; + $this->type = $rawResponse['type']; + $this->description = $rawResponse['description']; + $this->guidelines = $rawResponse['guidelines']; + if (isset($rawResponse['unique_values'])) { + $this->uniqueValues = $rawResponse['unique_values']; } - if (isset($serverResponse['nested_fields'])) { - $this->nestedFields = $serverResponse['nested_fields']; + if (isset($rawResponse['nested_fields'])) { + $this->nestedFields = $rawResponse['nested_fields']; } - if (isset($serverResponse['classification_values'])) { - $this->classificationValues = $serverResponse['classification_values']; + if (isset($rawResponse['classification_values'])) { + $this->classificationValues = $rawResponse['classification_values']; } } /** - * @return array JSON representation. + * @return array JSON representation. */ public function toJson(): array { diff --git a/src/V2/Product/Extraction/Params/DataSchemaReplace.php b/src/V2/Product/Extraction/Params/DataSchemaReplace.php index f9223438..eb6dc9c8 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaReplace.php +++ b/src/V2/Product/Extraction/Params/DataSchemaReplace.php @@ -20,23 +20,23 @@ class DataSchemaReplace public array $fields; /** - * @param array $serverResponse Raw server response array. + * @param array $rawResponse Raw server response array. * @throws InvalidArgumentException Throws if the fields array is empty or the Data schema is incorrect. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { if ( - !isset($serverResponse['fields']) - || !is_array($serverResponse['fields']) - || count($serverResponse['fields']) === 0 + !isset($rawResponse['fields']) + || !is_array($rawResponse['fields']) + || count($rawResponse['fields']) === 0 ) { throw new InvalidArgumentException('Data Schema replacement fields cannot be empty.'); } - $this->fields = array_map(static fn($field) => new DataSchemaField($field), $serverResponse['fields']); + $this->fields = array_map(static fn($field) => new DataSchemaField($field), $rawResponse['fields']); } /** - * @return array JSON representation. + * @return array JSON representation. */ public function toJson(): array { diff --git a/src/V2/Product/Extraction/Params/ExtractionParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php index 16b635e8..fab90117 100644 --- a/src/V2/Product/Extraction/Params/ExtractionParameters.php +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -61,8 +61,8 @@ class ExtractionParameters extends BaseParameters * @param array|null $webhooksIds List of webhook IDs. * @param string|null $textContext Additional text context used by the model during * inference. - * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during - * inference. + * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during + * inference. */ public function __construct( string $modelId, @@ -90,7 +90,7 @@ public function __construct( } /** - * @return array Hash representation. + * @return array Hash representation. */ public function asHash(): array { diff --git a/src/V2/Product/Ocr/OcrInference.php b/src/V2/Product/OCR/OCRInference.php similarity index 60% rename from src/V2/Product/Ocr/OcrInference.php rename to src/V2/Product/OCR/OCRInference.php index 50dd3b97..e161e887 100644 --- a/src/V2/Product/Ocr/OcrInference.php +++ b/src/V2/Product/OCR/OCRInference.php @@ -2,27 +2,27 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\V2\Parsing\BaseInference; /** * Response for an OCR utility inference. */ -class OcrInference extends BaseInference +class OCRInference extends BaseInference { /** - * @var OcrResult Result of the inference. + * @var OCRResult Result of the inference. */ - public OcrResult $result; + public OCRResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->result = new OcrResult($rawResponse['result']); + $this->result = new OCRResult($rawResponse['result']); } /** diff --git a/src/V2/Product/Ocr/OcrPage.php b/src/V2/Product/OCR/OCRPage.php similarity index 75% rename from src/V2/Product/Ocr/OcrPage.php rename to src/V2/Product/OCR/OCRPage.php index f440c7c2..fcc48cf5 100644 --- a/src/V2/Product/Ocr/OcrPage.php +++ b/src/V2/Product/OCR/OCRPage.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; /** * OCR result for a single page. */ -class OcrPage +class OCRPage { /** - * @var OcrWord[] OCR result for a single page. + * @var OCRWord[] OCR result for a single page. */ public array $words; @@ -20,11 +20,11 @@ class OcrPage public string $content; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->words = array_map(static fn($word) => new OcrWord($word), $rawResponse['words']); + $this->words = array_map(static fn($word) => new OCRWord($word), $rawResponse['words']); $this->content = $rawResponse['content']; } diff --git a/src/V2/Product/Ocr/OcrResponse.php b/src/V2/Product/OCR/OCRResponse.php similarity index 56% rename from src/V2/Product/Ocr/OcrResponse.php rename to src/V2/Product/OCR/OCRResponse.php index 9912da67..d59f2b0a 100644 --- a/src/V2/Product/Ocr/OcrResponse.php +++ b/src/V2/Product/OCR/OCRResponse.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\V2\Parsing\Inference\BaseResponse; /** * Response for an OCR utility inference. */ -class OcrResponse extends BaseResponse +class OCRResponse extends BaseResponse { /** - * @var OcrInference Result of an OCR inference. + * @var OCRInference Result of an OCR inference. */ - public OcrInference $inference; + public OCRInference $inference; /** * @var string Slug for the inference. @@ -22,11 +22,11 @@ class OcrResponse extends BaseResponse public static string $slug = "ocr"; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->inference = new OcrInference($rawResponse['inference']); + $this->inference = new OCRInference($rawResponse['inference']); } } diff --git a/src/V2/Product/Ocr/OcrResult.php b/src/V2/Product/OCR/OCRResult.php similarity index 75% rename from src/V2/Product/Ocr/OcrResult.php rename to src/V2/Product/OCR/OCRResult.php index 811cc10a..5f3d3d83 100644 --- a/src/V2/Product/Ocr/OcrResult.php +++ b/src/V2/Product/OCR/OCRResult.php @@ -2,26 +2,26 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use function strlen; /** * Result of the OCR utility inference. */ -class OcrResult +class OCRResult { /** - * @var OcrPage[] List of pages. + * @var OCRPage[] List of pages. */ public array $pages; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->pages = array_map(static fn($page) => new OcrPage($page), $rawResponse['pages']); + $this->pages = array_map(static fn($page) => new OCRPage($page), $rawResponse['pages']); } /** diff --git a/src/V2/Product/Ocr/OcrWord.php b/src/V2/Product/OCR/OCRWord.php similarity index 85% rename from src/V2/Product/Ocr/OcrWord.php rename to src/V2/Product/OCR/OCRWord.php index 4f4d8e68..fe197532 100644 --- a/src/V2/Product/Ocr/OcrWord.php +++ b/src/V2/Product/OCR/OCRWord.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\Geometry\Polygon; /** * OCR result for a single word extracted from the document page. */ -class OcrWord +class OCRWord { /** * @var string Content of the word. @@ -22,7 +22,7 @@ class OcrWord public Polygon $polygon; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Ocr/Params/OcrParameters.php b/src/V2/Product/OCR/Params/OCRParameters.php similarity index 88% rename from src/V2/Product/Ocr/Params/OcrParameters.php rename to src/V2/Product/OCR/Params/OCRParameters.php index f162d1ec..bb9a95dc 100644 --- a/src/V2/Product/Ocr/Params/OcrParameters.php +++ b/src/V2/Product/OCR/Params/OCRParameters.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr\Params; +namespace Mindee\V2\Product\OCR\Params; use Mindee\ClientOptions\PollingOptions; use Mindee\V2\ClientOptions\BaseParameters; @@ -10,7 +10,7 @@ /** * Parameters for an ocr utility inference. */ -class OcrParameters extends BaseParameters +class OCRParameters extends BaseParameters { /** * @var string Slug of the endpoint. diff --git a/src/V2/Product/Split/SplitInference.php b/src/V2/Product/Split/SplitInference.php index a601d3e2..acbc4420 100644 --- a/src/V2/Product/Split/SplitInference.php +++ b/src/V2/Product/Split/SplitInference.php @@ -17,7 +17,7 @@ class SplitInference extends BaseInference public SplitResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitRange.php b/src/V2/Product/Split/SplitRange.php index b8d2ad3f..b89e0264 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -29,7 +29,7 @@ class SplitRange /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitResponse.php b/src/V2/Product/Split/SplitResponse.php index d1ba75be..cd7326f6 100644 --- a/src/V2/Product/Split/SplitResponse.php +++ b/src/V2/Product/Split/SplitResponse.php @@ -22,7 +22,7 @@ class SplitResponse extends BaseResponse public static string $slug = "split"; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitResult.php b/src/V2/Product/Split/SplitResult.php index 45187f0d..35db87ec 100644 --- a/src/V2/Product/Split/SplitResult.php +++ b/src/V2/Product/Split/SplitResult.php @@ -15,7 +15,7 @@ class SplitResult public array $splits; /** - * @param array $rawResponse Raw server response array. + * @param array $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/CLI/MindeeCLICommandTestFunctional.php index b5d287f4..5dc870ea 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/CLI/MindeeCLICommandTestFunctional.php @@ -40,6 +40,7 @@ public static function provideProductCases(): iterable { $data = []; $data[] = ["generated", true, ["-a", "mindee", "-e", "invoice_splitter", "-d", "1"]]; + /** @phpstan-ignore-next-line */ foreach (MindeeCLIDocuments::getSpecs() as $productName => $productSpecs) { if ($productName !== "custom" && $productName !== "generated") { if ($productSpecs->isSync) { diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 3b93413f..1e96dbee 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -40,7 +40,7 @@ public function testShouldSendCropperExtra(): void self::assertGreaterThan(0, count($response->document->inference->pages[0]->extras->cropper->croppings)); } - public function testShouldSendFullTextOcrExtra(): void + public function testShouldSendFullTextOCRExtra(): void { $sample = $this->client->sourceFromPath( TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" diff --git a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php similarity index 95% rename from tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php rename to tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php index 90774d3d..eb90ab63 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -class FullTextOcrExtraTest extends TestCase +class FullTextOCRExtraTest extends TestCase { private $extrasDir; diff --git a/tests/V2/ClientOptions/BaseParametersTest.php b/tests/V2/ClientOptions/BaseParametersTest.php index 6d7cc135..6603b97b 100644 --- a/tests/V2/ClientOptions/BaseParametersTest.php +++ b/tests/V2/ClientOptions/BaseParametersTest.php @@ -11,7 +11,7 @@ class BaseParametersTest extends TestCase { public function testAsHashShouldSerializeMultipleWebhookIdsAsIndexedFields(): void { - $params = new class ('model-id', null, ['first-id', 'second-id'], null) extends BaseParameters { + $params = new class ('model-id', null, ['first-id', 'second-id']) extends BaseParameters { public static string $slug = 'test'; }; diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 7c49181e..6ff0e62a 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -153,7 +153,7 @@ public function testInvalidBaseUrlRaisesMindeeException(): void $params = new ExtractionParameters('dummy-model-id'); $client->enqueueAndGetResult(ExtractionResponse::class, $input, $params); } finally { - if ($original === null) { + if (null === $original) { putenv('MINDEE_V2_BASE_URL'); } else { putenv('MINDEE_V2_BASE_URL=' . $original); diff --git a/tests/V2/Parsing/ExtractionResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php index 30cae739..d80503a1 100644 --- a/tests/V2/Parsing/ExtractionResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -75,7 +75,7 @@ public function testAsyncPredictWhenEmptyMustHaveValidProperties(): void self::assertCount(9, $supplierAddress->fields); foreach ($fields as $fieldName => $field) { - if ($field === null) { + if (null === $field) { continue; } if ($field instanceof ListField) { diff --git a/tests/V2/Product/OcrFunctional.php b/tests/V2/Product/OCRFunctional.php similarity index 79% rename from tests/V2/Product/OcrFunctional.php rename to tests/V2/Product/OCRFunctional.php index 974d29e7..25517311 100644 --- a/tests/V2/Product/OcrFunctional.php +++ b/tests/V2/Product/OCRFunctional.php @@ -6,14 +6,14 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; -use Mindee\V2\Product\Ocr\OcrResponse; -use Mindee\V2\Product\Ocr\Params\OcrParameters; +use Mindee\V2\Product\OCR\OCRResponse; +use Mindee\V2\Product\OCR\Params\OCRParameters; use PHPUnit\Framework\TestCase; use TestingUtilities; require_once(__DIR__ . "/../../TestingUtilities.php"); -class OcrFunctional extends TestCase +class OCRFunctional extends TestCase { private Client $client; private string $ocrModelId; @@ -30,14 +30,14 @@ protected function setUp(): void * Tests the success of the OCR process using a default sample file. * */ - public function testOcrDefaultSampleMustSucceed(): void + public function testOCRDefaultSampleMustSucceed(): void { $inputSource = new PathInput( TestingUtilities::getV2ProductDir() . '/ocr/default_sample.jpg' ); - $productParams = new OcrParameters($this->ocrModelId); - $response = $this->client->enqueueAndGetResult(OcrResponse::class, $inputSource, $productParams); + $productParams = new OCRParameters($this->ocrModelId); + $response = $this->client->enqueueAndGetResult(OCRResponse::class, $inputSource, $productParams); self::assertNotNull($response); self::assertNotNull($response->inference); diff --git a/tests/V2/Product/OcrTest.php b/tests/V2/Product/OCRTest.php similarity index 91% rename from tests/V2/Product/OcrTest.php rename to tests/V2/Product/OCRTest.php index 784dd7fb..3ff0a7ff 100644 --- a/tests/V2/Product/OcrTest.php +++ b/tests/V2/Product/OCRTest.php @@ -6,14 +6,14 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -use Mindee\V2\Product\Ocr\OcrResponse; +use Mindee\V2\Product\OCR\OCRResponse; require_once(__DIR__ . "/../../TestingUtilities.php"); /** * OCR unit tests. */ -class OcrTest extends TestCase +class OCRTest extends TestCase { /** * Load a JSON sample and return its decoded contents. @@ -43,10 +43,10 @@ private function assertInferenceResponse(mixed $response): void /** * Should correctly map properties when reading a single OCR JSON. */ - public function testOcrWhenSingleMustHaveValidProperties(): void + public function testOCRWhenSingleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_single.json"); - $response = new OcrResponse($jsonSample); + $response = new OCRResponse($jsonSample); $this->assertInferenceResponse($response); @@ -78,10 +78,10 @@ public function testOcrWhenSingleMustHaveValidProperties(): void /** * Should correctly map properties when reading a multiple OCR JSON. */ - public function testOcrWhenMultipleMustHaveValidProperties(): void + public function testOCRWhenMultipleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_multiple.json"); - $response = new OcrResponse($jsonSample); + $response = new OCRResponse($jsonSample); $this->assertInferenceResponse($response);