diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 5a72d400..3058f84a 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -31,14 +31,6 @@ jobs: run: | composer install - - name: Run CS Fixer + - name: Run lint run: | - ./vendor/bin/php-cs-fixer check ./src - - - name: Setup Code Sniffer - run: | - ./vendor/bin/phpcs --config-set default_standard PSR12 - - - name: Run Code Sniffer - run: | - ./vendor/bin/phpcs -n ./src/ + composer lint diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..c8550714 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,47 @@ +in([ + __DIR__ . '/src', + __DIR__ . '/tests', + __DIR__ . '/bin', + ]) + ->append([ + __DIR__ . '/mindee', + ]); + +return (new Config()) + ->setRiskyAllowed(true) + ->setRules([ + '@auto' => true, + '@auto:risky' => true, + '@PhpCsFixer:risky' => true, + + 'fully_qualified_strict_types' => [ + 'import_symbols' => true, + 'leading_backslash_in_global_namespace' => false, + ], + 'global_namespace_import' => [ + 'import_classes' => true, + 'import_constants' => true, + 'import_functions' => true, + ], + 'no_superfluous_phpdoc_tags' => [ + 'allow_mixed' => true, + 'allow_unused_params' => false, + ], + 'phpdoc_align' => [ + 'align' => 'left', + ], + 'concat_space' => [ + 'spacing' => 'one', + ], + 'yoda_style' => false, + 'php_unit_strict' => false, + ]) + ->setFinder($finder); diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d9b1131..9003c542 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Mindee PHP API Library Changelog +## v3.0.0-alpha1 - 2026-05-11 +### ¡Breaking Changes! +* +### Changes +* :sparkles: add support for extraction in crop, split, and classification +### Fixes +* + + ## v2.9.0 - 2026-05-07 ### Changes * :sparkles: add support for extraction in crop, split, and classification diff --git a/bin/DocumentCommandConfig.php b/bin/DocumentCommandConfig.php index 5c5db2e1..1ec30794 100644 --- a/bin/DocumentCommandConfig.php +++ b/bin/DocumentCommandConfig.php @@ -1,6 +1,8 @@ new DocumentCommandConfig( - "Custom document type from docTI", - \Mindee\Product\Generated\GeneratedV1::class, - false, - true - ), - "barcode-reader" => new DocumentCommandConfig( - "Barcode Reader", - \Mindee\Product\BarcodeReader\BarcodeReaderV1::class, - true, - false - ), - "bill-of-lading" => new DocumentCommandConfig( - "Bill of Lading", - \Mindee\Product\BillOfLading\BillOfLadingV1::class, - false, - true - ), - "business-card" => new DocumentCommandConfig( - "Business Card", - \Mindee\Product\BusinessCard\BusinessCardV1::class, - false, - true - ), - "cropper" => new DocumentCommandConfig( - "Cropper", - \Mindee\Product\Cropper\CropperV1::class, - true, - false - ), - "delivery-note" => new DocumentCommandConfig( - "Delivery note", - \Mindee\Product\DeliveryNote\DeliveryNoteV1::class, - false, - true - ), - "driver-license" => new DocumentCommandConfig( - "Driver License", - \Mindee\Product\DriverLicense\DriverLicenseV1::class, - false, - true - ), - "financial-document" => new DocumentCommandConfig( - "Financial Document", - \Mindee\Product\FinancialDocument\FinancialDocumentV1::class, - true, - true - ), - "fr-bank-account-details" => new DocumentCommandConfig( - "FR Bank Account Details", - \Mindee\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, - true, - false - ), - "fr-carte-grise" => new DocumentCommandConfig( - "FR Carte Grise", - \Mindee\Product\Fr\CarteGrise\CarteGriseV1::class, - true, - false - ), - "fr-energy-bill" => new DocumentCommandConfig( - "FR Energy Bill", - \Mindee\Product\Fr\EnergyBill\EnergyBillV1::class, - false, - true - ), - "fr-health-card" => new DocumentCommandConfig( - "FR Health Card", - \Mindee\Product\Fr\HealthCard\HealthCardV1::class, - false, - true - ), - "fr-carte-nationale-d-identite" => new DocumentCommandConfig( - "FR Carte Nationale d'Identité", - \Mindee\Product\Fr\IdCard\IdCardV2::class, - true, - false - ), - "fr-payslip" => new DocumentCommandConfig( - "FR Payslip", - \Mindee\Product\Fr\Payslip\PayslipV3::class, - false, - true - ), - "ind-passport-india" => new DocumentCommandConfig( - "IND Passport - India", - \Mindee\Product\Ind\IndianPassport\IndianPassportV1::class, - false, - true - ), - "international-id" => new DocumentCommandConfig( - "International ID", - \Mindee\Product\InternationalId\InternationalIdV2::class, - false, - true - ), - "invoice" => new DocumentCommandConfig( - "Invoice", - \Mindee\Product\Invoice\InvoiceV4::class, - true, - true - ), - "invoice-splitter" => new DocumentCommandConfig( - "Invoice Splitter", - \Mindee\Product\InvoiceSplitter\InvoiceSplitterV1::class, - false, - true - ), - "multi-receipts-detector" => new DocumentCommandConfig( - "Multi Receipts Detector", - \Mindee\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, - true, - false - ), - "nutrition-facts-label" => new DocumentCommandConfig( - "Nutrition Facts Label", - \Mindee\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, - false, - true - ), - "passport" => new DocumentCommandConfig( - "Passport", - \Mindee\Product\Passport\PassportV1::class, - true, - false - ), - "receipt" => new DocumentCommandConfig( - "Receipt", - \Mindee\Product\Receipt\ReceiptV5::class, - true, - true - ), - "resume" => new DocumentCommandConfig( - "Resume", - \Mindee\Product\Resume\ResumeV1::class, - false, - true - ), - "us-bank-check" => new DocumentCommandConfig( - "US Bank Check", - \Mindee\Product\Us\BankCheck\BankCheckV1::class, - true, - false - ), - "us-healthcare-card" => new DocumentCommandConfig( - "US Healthcare Card", - \Mindee\Product\Us\HealthcareCard\HealthcareCardV1::class, - false, - true - ), - "us-us-mail" => new DocumentCommandConfig( - "US US Mail", - \Mindee\Product\Us\UsMail\UsMailV3::class, - false, - true - ), - ]; - } -} diff --git a/bin/MindeeCLICommand.php b/bin/MindeeCliCommand.php similarity index 81% rename from bin/MindeeCLICommand.php rename to bin/MindeeCliCommand.php index c7334193..772f9758 100644 --- a/bin/MindeeCLICommand.php +++ b/bin/MindeeCliCommand.php @@ -1,23 +1,29 @@ setName('mindee') @@ -107,7 +112,7 @@ protected function configure() /** * @return void Sets main properties regarding polling/parsing. */ - private function configureMainOptions() + private function configureMainOptions(): void { $this->addOption( 'async', @@ -172,7 +177,7 @@ private function configureMainOptions() /** * @return void Sets custom options. */ - private function configureCustomOptions() + private function configureCustomOptions(): void { $this ->addOption( @@ -198,11 +203,10 @@ private function configureCustomOptions() /** * Initializes the CLI runner, writes the help section if no argument nor option is given. * - * @param InputInterface $input Input interface given to the CLI. + * @param InputInterface $input Input interface given to the CLI. * @param OutputInterface $output Output interface. - * @return void */ - protected function initialize(InputInterface $input, OutputInterface $output) + protected function initialize(InputInterface $input, OutputInterface $output): void { $args = $input->getArguments(); $opts = $input->getOptions(); @@ -216,7 +220,7 @@ protected function initialize(InputInterface $input, OutputInterface $output) /** * Runs a command (overload). * - * @param InputInterface $input Input interface given to the CLI. + * @param InputInterface $input Input interface given to the CLI. * @param OutputInterface $output Output interface. * @return integer Command execution code return. */ @@ -249,7 +253,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $filePathOrUrl = $input->getArgument('file_path_or_url'); - $file = $this->getFileSource($filePathOrUrl, $client, $output); + $file = $this->getFileSource($filePathOrUrl, $output); if (!$file) { return Command::FAILURE; } @@ -277,7 +281,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int /** * Checks whether the version was requested. * - * @param InputInterface $input Input interface of the CLI. + * @param InputInterface $input Input interface of the CLI. * @param OutputInterface $output Output interface of the CLI. * @return boolean True if options are valid. */ @@ -293,16 +297,16 @@ private function handleVersionOption(InputInterface $input, OutputInterface $out /** * Checks whether a given product is valid for CLI use. * - * @param string $product Product class used. - * @param OutputInterface $output Output interface of the CLI. + * @param string $product Product class used. + * @param OutputInterface $output Output interface of the CLI. * @return boolean True if a product is valid. */ private function isValidProduct(string $product, OutputInterface $output): bool { - if (!in_array($product, $this->acceptableDocuments)) { + if (!in_array($product, $this->acceptableDocuments, true)) { $output->writeln("Invalid product: $product"); - $output->writeln('Available products are: ' . - implode(', ', $this->acceptableDocuments) . ''); + $output->writeln('Available products are: ' + . implode(', ', $this->acceptableDocuments) . ''); return false; } return true; @@ -311,9 +315,9 @@ private function isValidProduct(string $product, OutputInterface $output): bool /** * Checks whether a polling method is valid for the current poll. * - * @param string $product Product class used. - * @param boolean $isAsync Whether the polling will be asynchronous. - * @param OutputInterface $output Output interface of the CLI. + * @param string $product Product class used. + * @param boolean $isAsync Whether the polling will be asynchronous. + * @param OutputInterface $output Output interface of the CLI. * @return boolean True if the polling method exists for a given product. */ private function isValidPollingMethod(string $product, bool $isAsync, OutputInterface $output): bool @@ -334,7 +338,7 @@ private function isValidPollingMethod(string $product, bool $isAsync, OutputInte /** * Checks whether PageOptions for the current polling are possible. * - * @param InputInterface $input Input interface of the CLI. + * @param InputInterface $input Input interface of the CLI. * @param OutputInterface $output Output interface of the CLI. * @return boolean True if the operations are possible. */ @@ -343,7 +347,7 @@ private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputI $pagesRemove = $input->getOption('pages_remove'); $pagesKeep = $input->getOption('pages_keep'); if ($pagesKeep && $pagesRemove) { - $output->writeln("Page cut & page keep operations are mutually exclusive."); + $output->writeln("Page cut and page keep operations are mutually exclusive."); return true; } return false; @@ -352,22 +356,21 @@ private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputI /** * Retrieves a source file from a URL or a path. * - * @param string $filePathOrUrl Path of the file, or URL if it's remote. - * @param Client $client Mindee Client. - * @param OutputInterface $output Output interface of the CLI. - * @return PathInput|URLInputSource|null A valid InputSource. + * @param string $filePathOrUrl Path of the file, or URL if it's remote. + * @param OutputInterface $output Output interface of the CLI. + * @return PathInput|UrlInputSource|null A valid InputSource. */ - private function getFileSource(string $filePathOrUrl, Client $client, OutputInterface $output) + private function getFileSource(string $filePathOrUrl, OutputInterface $output): PathInput|UrlInputSource|null { - if (substr($filePathOrUrl, 0, 8) !== 'https://') { + if (!str_starts_with($filePathOrUrl, 'https://')) { if (@file_exists($filePathOrUrl) || @file_get_contents($filePathOrUrl)) { - return $client->sourceFromPath($filePathOrUrl); + return new PathInput($filePathOrUrl); } else { $output->writeln("Invalid path or url provided '$filePathOrUrl'."); return null; } } - return $client->sourceFromUrl($filePathOrUrl); + return new UrlInputSource($filePathOrUrl); } /** @@ -411,7 +414,7 @@ private function getPredictOptions(InputInterface $input): PredictOptions * Generates a valid PredictMethodOptions object for parsing. * * @param PredictOptions $predictOptions Valid PredictOptions. - * @param PageOptions $pageOptions Valid PageOptions. + * @param PageOptions $pageOptions Valid PageOptions. * @return PredictMethodOptions Valid PredictMethod Options. */ private function getPredictMethodOptions( @@ -427,11 +430,11 @@ private function getPredictMethodOptions( /** * Handles options specific to Custom & Generated Products. * - * @param InputInterface $input Input interface of the CLI. - * @param OutputInterface $output Output interface of the CLI. - * @param Client $client Mindee Client. + * @param InputInterface $input Input interface of the CLI. + * @param OutputInterface $output Output interface of the CLI. + * @param Client $client Mindee Client. * @param PredictMethodOptions $predictMethodOptions Valid PredictMethodOptions. - * @param string $product Product class used. + * @param string $product Product class used. * @return boolean Whether the setting of options for custom/generated are valid. */ private function handleCustomOrGeneratedProduct( @@ -441,7 +444,7 @@ private function handleCustomOrGeneratedProduct( PredictMethodOptions $predictMethodOptions, string $product ): bool { - if ($product == "generated") { + if ($product === "generated") { $accountName = $input->getOption('account_name'); $endpointName = $input->getOption('endpoint_name'); $endpointVersion = $input->getOption('endpoint_version') ?? '1'; @@ -466,14 +469,14 @@ private function handleCustomOrGeneratedProduct( } /** - * @param Client $client Mindee Client. - * @param string $product Product class used. - * @param InputSource $file Input File. + * @param Client $client Mindee Client. + * @param string $product Product class used. + * @param InputSource $file Input File. * @param PredictMethodOptions $predictMethodOptions Options for the polling. - * @param boolean $isAsync Whether the polling will be asynchronous. - * @param InputInterface $input Input interface of the CLI. - * @param OutputInterface $output Output interface of the CLI. - * @param string|null $outputType Type of output (raw, parsed or summary). + * @param boolean $isAsync Whether the polling will be asynchronous. + * @param InputInterface $input Input interface of the CLI. + * @param OutputInterface $output Output interface of the CLI. + * @param string|null $outputType Type of output (raw, parsed or summary). * @return integer Return code for the CLI */ private function executePrediction( @@ -489,10 +492,10 @@ private function executePrediction( $debug = $input->getOption('debug'); try { $result = $this->runClientPrediction($client, $product, $file, $predictMethodOptions, $isAsync, $debug); - } catch (MindeeHttpException $e) { + } catch (MindeeV1HttpException $e) { $output->writeln($e->getMessage()); return Command::FAILURE; - } catch (\Exception $e) { + } catch (Exception $e) { $output->writeln("Something went wrong, '" . $e->getMessage() . "' was raised."); return Command::FAILURE; } @@ -503,15 +506,15 @@ private function executePrediction( /** * Runs the prediction call. * - * @param Client $client Mindee client. - * @param string $product Product class used. - * @param InputSource $file Input File. + * @param Client $client Mindee client. + * @param string $product Product class used. + * @param InputSource $file Input File. * @param PredictMethodOptions $predictMethodOptions Prediction method options. - * @param boolean $isAsync Whether the polling is asynchronous. - * @param boolean $debug Whether the command is running in debug mode. + * @param boolean $isAsync Whether the polling is asynchronous. + * @param boolean $debug Whether the command is running in debug mode. * * @return AsyncPredictResponse|PredictResponse|string Either a valid prediction response, or a message if the - * command is in debug mode. + * command is in debug mode. */ private function runClientPrediction( Client $client, @@ -520,7 +523,7 @@ private function runClientPrediction( PredictMethodOptions $predictMethodOptions, bool $isAsync, bool $debug - ) { + ): AsyncPredictResponse|PredictResponse|string { if ($debug) { return "Command executed successfully."; } @@ -533,14 +536,14 @@ private function runClientPrediction( } /** - * @param PredictResponse|AsyncPredictResponse|string $result Result of the parsing (or message if in debug - * mode). - * @param string|null $outputType Type of output (raw, parsed or summary). - * @param OutputInterface $output Output interface for the CLI. + * @param PredictResponse|AsyncPredictResponse|string $result Result of the parsing (or message if in debug + * mode). + * @param string|null $outputType Type of output (raw, parsed or summary). + * @param OutputInterface $output Output interface for the CLI. * @return integer Command execution code return. */ private function outputResult( - $result, + PredictResponse|AsyncPredictResponse|string $result, ?string $outputType, OutputInterface $output ): int { diff --git a/bin/MindeeCliDocuments.php b/bin/MindeeCliDocuments.php new file mode 100644 index 00000000..08550a2c --- /dev/null +++ b/bin/MindeeCliDocuments.php @@ -0,0 +1,141 @@ + new DocumentCommandConfig( + "Custom document type from docTI", + GeneratedV1::class, + false, + true + ), + "barcode-reader" => new DocumentCommandConfig( + "Barcode Reader", + BarcodeReaderV1::class, + true, + false + ), + "business-card" => new DocumentCommandConfig( + "Business Card", + BusinessCardV1::class, + false, + true + ), + "cropper" => new DocumentCommandConfig( + "Cropper", + CropperV1::class, + true, + false + ), + "driver-license" => new DocumentCommandConfig( + "Driver License", + DriverLicenseV1::class, + false, + true + ), + "financial-document" => new DocumentCommandConfig( + "Financial Document", + FinancialDocumentV1::class, + true, + true + ), + "fr-bank-account-details" => new DocumentCommandConfig( + "FR Bank Account Details", + BankAccountDetailsV2::class, + true, + false + ), + "fr-carte-grise" => new DocumentCommandConfig( + "FR Carte Grise", + CarteGriseV1::class, + true, + false + ), + "fr-carte-nationale-d-identite" => new DocumentCommandConfig( + "FR Carte Nationale d'Identité", + IdCardV2::class, + true, + false + ), + "international-id" => new DocumentCommandConfig( + "International ID", + InternationalIdV2::class, + false, + true + ), + "invoice" => new DocumentCommandConfig( + "Invoice", + InvoiceV4::class, + true, + true + ), + "invoice-splitter" => new DocumentCommandConfig( + "Invoice Splitter", + InvoiceSplitterV1::class, + false, + true + ), + "multi-receipts-detector" => new DocumentCommandConfig( + "Multi Receipts Detector", + MultiReceiptsDetectorV1::class, + true, + false + ), + "passport" => new DocumentCommandConfig( + "Passport", + PassportV1::class, + true, + false + ), + "receipt" => new DocumentCommandConfig( + "Receipt", + ReceiptV5::class, + true, + true + ), + "resume" => new DocumentCommandConfig( + "Resume", + ResumeV1::class, + false, + true + ), + "us-bank-check" => new DocumentCommandConfig( + "US Bank Check", + BankCheckV1::class, + true, + false + ), + ]; + } +} diff --git a/bin/cli.php b/bin/cli.php index 976cc293..c64c6ea8 100755 --- a/bin/cli.php +++ b/bin/cli.php @@ -1,23 +1,24 @@ add($mindeeCommand); try { $cli->add($mindeeCommand); $cli->setDefaultCommand($mindeeCommand->getName(), true); $cli->run(); -} catch (\Exception $e) { +} catch (Exception $e) { error_log("Could not start the Mindee CLI, an exception was raised:"); error_log($e->getMessage()); } diff --git a/composer.json b/composer.json index b8f65a5a..6cdf6d7e 100644 --- a/composer.json +++ b/composer.json @@ -15,9 +15,12 @@ }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.38", - "squizlabs/php_codesniffer": "^3.7", "phpunit/phpunit": "^9.6", - "madewithlove/license-checker": "^v1.0" + "madewithlove/license-checker": "^v1.0", + "phpstan/phpstan": "^2.1", + "phpstan/phpstan-deprecation-rules": "^2.0", + "rector/rector": "^2.4", + "projektgopher/whisky": "^0.7.4" }, "suggest": { "ext-imagick": "Required for PDF rasterization and image processing features", @@ -31,5 +34,25 @@ "bin": [ "mindee", "bin/cli.php" - ] + ], + "scripts": { + "lint:cs-fixer": "php-cs-fixer fix --dry-run --diff", + "lint:rector": "rector process src tests --dry-run", + "lint:phpstan": "phpstan analyse", + "lint": [ + "@lint:phpstan", + "@lint:cs-fixer", + "@lint:rector" + ], + "format:cs-fixer": "php-cs-fixer fix", + "format:rector": "rector process src tests", + "format": [ + "@format:cs-fixer", + "@format:rector" + ], + "test:unit": "phpunit -c tests/phpunit.xml", + "test:functional": "phpunit -c tests/functional.xml", + "test:smoke:v1": "./tests/test_v1_code_samples.sh", + "test:smoke:v2": "./tests/test_v2_code_samples.sh" + } } diff --git a/docs/code_samples/bank_account_details_v1.txt b/docs/code_samples/bank_account_details_v1.txt index dfd63f64..eaf56aa0 100644 --- a/docs/code_samples/bank_account_details_v1.txt +++ b/docs/code_samples/bank_account_details_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankAccountDetailsV1::class, $inputSource); diff --git a/docs/code_samples/bank_account_details_v2.txt b/docs/code_samples/bank_account_details_v2.txt index 9ab6cfcc..b3f4ce74 100644 --- a/docs/code_samples/bank_account_details_v2.txt +++ b/docs/code_samples/bank_account_details_v2.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankAccountDetailsV2::class, $inputSource); diff --git a/docs/code_samples/bank_check_v1.txt b/docs/code_samples/bank_check_v1.txt index 929f8366..48c14547 100644 --- a/docs/code_samples/bank_check_v1.txt +++ b/docs/code_samples/bank_check_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankCheckV1::class, $inputSource); diff --git a/docs/code_samples/barcode_reader_v1.txt b/docs/code_samples/barcode_reader_v1.txt index 6380b653..2075e019 100644 --- a/docs/code_samples/barcode_reader_v1.txt +++ b/docs/code_samples/barcode_reader_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BarcodeReaderV1::class, $inputSource); diff --git a/docs/code_samples/bill_of_lading_v1_async.txt b/docs/code_samples/bill_of_lading_v1_async.txt deleted file mode 100644 index b3655ee9..00000000 --- a/docs/code_samples/bill_of_lading_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(BillOfLadingV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/business_card_v1_async.txt b/docs/code_samples/business_card_v1_async.txt index 7f9f12d7..bd9a62a5 100644 --- a/docs/code_samples/business_card_v1_async.txt +++ b/docs/code_samples/business_card_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(BusinessCardV1::class, $inputSource); diff --git a/docs/code_samples/carte_grise_v1.txt b/docs/code_samples/carte_grise_v1.txt index cda5bb60..585489aa 100644 --- a/docs/code_samples/carte_grise_v1.txt +++ b/docs/code_samples/carte_grise_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(CarteGriseV1::class, $inputSource); diff --git a/docs/code_samples/cropper_v1.txt b/docs/code_samples/cropper_v1.txt index 9b17f4e8..99fdf2bd 100644 --- a/docs/code_samples/cropper_v1.txt +++ b/docs/code_samples/cropper_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(CropperV1::class, $inputSource); diff --git a/docs/code_samples/custom_v1.txt b/docs/code_samples/custom_v1.txt index 3c06284f..3cacc1d4 100644 --- a/docs/code_samples/custom_v1.txt +++ b/docs/code_samples/custom_v1.txt @@ -6,15 +6,15 @@ // Use only with version 1.x of the library. // -use Mindee\Client; -use Mindee\Product\Custom\CustomV1; -use Mindee\Input\PredictMethodOptions; +use Mindee\V1\Client; +use Mindee\V1\Product\Custom\CustomV1; +use Mindee\V1\ClientOptions\PredictMethodOptions; // Init a new client $mindeeClient = new Client("my-api-key"); // Load a file from disk -$inputSource = $mindeeClient->sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/default.txt b/docs/code_samples/default.txt index 04fba6e4..b917270c 100644 --- a/docs/code_samples/default.txt +++ b/docs/code_samples/default.txt @@ -1,14 +1,15 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/default_async.txt b/docs/code_samples/default_async.txt index fe49d9b9..d05972b7 100644 --- a/docs/code_samples/default_async.txt +++ b/docs/code_samples/default_async.txt @@ -1,14 +1,15 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/delivery_notes_v1_async.txt b/docs/code_samples/delivery_notes_v1_async.txt deleted file mode 100644 index aedc963b..00000000 --- a/docs/code_samples/delivery_notes_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(DeliveryNoteV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/driver_license_v1_async.txt b/docs/code_samples/driver_license_v1_async.txt index e0d80165..126c06da 100644 --- a/docs/code_samples/driver_license_v1_async.txt +++ b/docs/code_samples/driver_license_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(DriverLicenseV1::class, $inputSource); diff --git a/docs/code_samples/energy_bill_fra_v1_async.txt b/docs/code_samples/energy_bill_fra_v1_async.txt deleted file mode 100644 index dd18b573..00000000 --- a/docs/code_samples/energy_bill_fra_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(EnergyBillV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/expense_receipts_v5.txt b/docs/code_samples/expense_receipts_v5.txt index 92a0af55..09c31587 100644 --- a/docs/code_samples/expense_receipts_v5.txt +++ b/docs/code_samples/expense_receipts_v5.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(ReceiptV5::class, $inputSource); diff --git a/docs/code_samples/expense_receipts_v5_async.txt b/docs/code_samples/expense_receipts_v5_async.txt index 8d996ce6..49254892 100644 --- a/docs/code_samples/expense_receipts_v5_async.txt +++ b/docs/code_samples/expense_receipts_v5_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(ReceiptV5::class, $inputSource); diff --git a/docs/code_samples/financial_document_v1.txt b/docs/code_samples/financial_document_v1.txt index 35999afc..71a2087d 100644 --- a/docs/code_samples/financial_document_v1.txt +++ b/docs/code_samples/financial_document_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(FinancialDocumentV1::class, $inputSource); diff --git a/docs/code_samples/financial_document_v1_async.txt b/docs/code_samples/financial_document_v1_async.txt index e8562430..045a5572 100644 --- a/docs/code_samples/financial_document_v1_async.txt +++ b/docs/code_samples/financial_document_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(FinancialDocumentV1::class, $inputSource); diff --git a/docs/code_samples/french_healthcard_v1_async.txt b/docs/code_samples/french_healthcard_v1_async.txt deleted file mode 100644 index 76781303..00000000 --- a/docs/code_samples/french_healthcard_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(HealthCardV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/idcard_fr_v1.txt b/docs/code_samples/idcard_fr_v1.txt index b0907c4c..574c3e21 100644 --- a/docs/code_samples/idcard_fr_v1.txt +++ b/docs/code_samples/idcard_fr_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(IdCardV1::class, $inputSource); diff --git a/docs/code_samples/idcard_fr_v2.txt b/docs/code_samples/idcard_fr_v2.txt index fd51cb43..19c20c15 100644 --- a/docs/code_samples/idcard_fr_v2.txt +++ b/docs/code_samples/idcard_fr_v2.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(IdCardV2::class, $inputSource); diff --git a/docs/code_samples/ind_passport_v1_async.txt b/docs/code_samples/ind_passport_v1_async.txt deleted file mode 100644 index 5ca76c07..00000000 --- a/docs/code_samples/ind_passport_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(IndianPassportV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/international_id_v2_async.txt b/docs/code_samples/international_id_v2_async.txt index 29735962..d3924b9f 100644 --- a/docs/code_samples/international_id_v2_async.txt +++ b/docs/code_samples/international_id_v2_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InternationalIdV2::class, $inputSource); diff --git a/docs/code_samples/invoice_splitter_v1_async.txt b/docs/code_samples/invoice_splitter_v1_async.txt index bf17adfb..0cca340d 100644 --- a/docs/code_samples/invoice_splitter_v1_async.txt +++ b/docs/code_samples/invoice_splitter_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InvoiceSplitterV1::class, $inputSource); diff --git a/docs/code_samples/invoices_v4.txt b/docs/code_samples/invoices_v4.txt index 6564cb33..ecb488a2 100644 --- a/docs/code_samples/invoices_v4.txt +++ b/docs/code_samples/invoices_v4.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(InvoiceV4::class, $inputSource); diff --git a/docs/code_samples/invoices_v4_async.txt b/docs/code_samples/invoices_v4_async.txt index 9ba2d571..b2d9d9bd 100644 --- a/docs/code_samples/invoices_v4_async.txt +++ b/docs/code_samples/invoices_v4_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InvoiceV4::class, $inputSource); diff --git a/docs/code_samples/multi_receipts_detector_v1.txt b/docs/code_samples/multi_receipts_detector_v1.txt index af2fbe16..31ba3e57 100644 --- a/docs/code_samples/multi_receipts_detector_v1.txt +++ b/docs/code_samples/multi_receipts_detector_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(MultiReceiptsDetectorV1::class, $inputSource); diff --git a/docs/code_samples/nutrition_facts_v1_async.txt b/docs/code_samples/nutrition_facts_v1_async.txt deleted file mode 100644 index c22d1d49..00000000 --- a/docs/code_samples/nutrition_facts_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(NutritionFactsLabelV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/passport_v1.txt b/docs/code_samples/passport_v1.txt index 923c53f2..24b47060 100644 --- a/docs/code_samples/passport_v1.txt +++ b/docs/code_samples/passport_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(PassportV1::class, $inputSource); diff --git a/docs/code_samples/payslip_fra_v3_async.txt b/docs/code_samples/payslip_fra_v3_async.txt deleted file mode 100644 index 9ec562bc..00000000 --- a/docs/code_samples/payslip_fra_v3_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(PayslipV3::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/resume_v1_async.txt b/docs/code_samples/resume_v1_async.txt index b6f3c5c0..5efcda28 100644 --- a/docs/code_samples/resume_v1_async.txt +++ b/docs/code_samples/resume_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(ResumeV1::class, $inputSource); diff --git a/docs/code_samples/us_healthcare_cards_v1_async.txt b/docs/code_samples/us_healthcare_cards_v1_async.txt deleted file mode 100644 index 96272c99..00000000 --- a/docs/code_samples/us_healthcare_cards_v1_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(HealthcareCardV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/us_mail_v3_async.txt b/docs/code_samples/us_mail_v3_async.txt deleted file mode 100644 index d8081a3f..00000000 --- a/docs/code_samples/us_mail_v3_async.txt +++ /dev/null @@ -1,15 +0,0 @@ -sourceFromPath("/path/to/the/file.ext"); - -// Parse the file asynchronously -$apiResponse = $mindeeClient->enqueueAndParse(UsMailV3::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/v2_classification.txt b/docs/code_samples/v2_classification.txt index 1995f910..8dd97a82 100644 --- a/docs/code_samples/v2_classification.txt +++ b/docs/code_samples/v2_classification.txt @@ -1,6 +1,6 @@ enqueueAndGetResult( - InferenceResponse::class, + ExtractionResponse::class, $inputSource, $inferenceParams ); diff --git a/docs/code_samples/v2_extraction_webhook.txt b/docs/code_samples/v2_extraction_webhook.txt index 32be0c69..28293a6b 100644 --- a/docs/code_samples/v2_extraction_webhook.txt +++ b/docs/code_samples/v2_extraction_webhook.txt @@ -1,7 +1,7 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Send the file to the workflow diff --git a/docs/code_samples/workflow_polling.txt b/docs/code_samples/workflow_polling.txt index 9dfe5b58..5b542eb2 100644 --- a/docs/code_samples/workflow_polling.txt +++ b/docs/code_samples/workflow_polling.txt @@ -1,9 +1,9 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); $customEndpoint = $mindeeClient->createEndpoint( "my-endpoint", diff --git a/examples/InvoiceSplitterAutoExtractionExample.php b/examples/InvoiceSplitterAutoExtractionExample.php deleted file mode 100644 index f9b61dce..00000000 --- a/examples/InvoiceSplitterAutoExtractionExample.php +++ /dev/null @@ -1,52 +0,0 @@ -isPdf() && $inputSource->getPageCount() > 1) { - parseMultiPage($inputSource, $mindeeClient); - } else { - parseSinglePage($inputSource, $mindeeClient); - } -} - -function parseSinglePage(PathInput $inputSource, Client $mindeeClient) -{ - $invoiceResult = $mindeeClient->parse(InvoiceV4::class, $inputSource); - echo $invoiceResult->document; -} - -function parseMultiPage(PathInput $inputSource, Client $mindeeClient) -{ - global $mindeeClient; - $pdfExtractor = new PdfExtractor($inputSource); - $invoiceSplitterResponse = $mindeeClient->enqueueAndParse( - InvoiceSplitterV1::class, - $inputSource - ); - $pageGroups = $invoiceSplitterResponse->document->inference->prediction->invoicePageGroups; - $extractedPdfs = $pdfExtractor->extractInvoices($pageGroups); - - foreach ($extractedPdfs as $extractedPdf) { - // Optional: Save the files locally - // $extractedPdf->writeToFile("output/path"); - - $invoiceResult = $mindeeClient->parse( - InvoiceV4::class, - $extractedPdf->asInputSource() - ); - echo $invoiceResult->document; - } -} - -$mindeeClient = new Client("my-api-key-here"); -// $mindeeClient = new Client(); // Optionally, use an environment variable. -$inputPath = "path/to/your/file.ext"; -parseInvoice($inputPath, $mindeeClient); diff --git a/examples/MultiReceiptsAutoExtractionExample.php b/examples/MultiReceiptsAutoExtractionExample.php deleted file mode 100644 index 05f07282..00000000 --- a/examples/MultiReceiptsAutoExtractionExample.php +++ /dev/null @@ -1,37 +0,0 @@ -parse(MultiReceiptsDetectorV1::class, $inputSource); - $pageCount = $inputSource->getPageCount(); - - $totalExtractedReceipts = []; - - for ($i = 0; $i < $pageCount; $i++) { - $receiptsPositions = $multiReceiptsResult->document->inference->pages[$i]->prediction->receipts; - $extractedReceipts = $imageExtractor->extractImagesFromPage($receiptsPositions, $i); - $totalExtractedReceipts = array_merge($totalExtractedReceipts, $extractedReceipts); - } - - foreach ($totalExtractedReceipts as $receipt) { - // Optional: save the extracted receipts to a file - // $receipt->writeToFile("output/path"); - - $result = $client->parse(ReceiptV5::class, $receipt->asInputSource()); - echo $result->document . "\n"; - } -} -processReceipts($mindeeClient, $inputPath); diff --git a/phpcs.xml b/phpcs.xml deleted file mode 100644 index 31de617e..00000000 --- a/phpcs.xml +++ /dev/null @@ -1,313 +0,0 @@ - - - The (mostly) PSR-12 coding standard. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - - - 0 - - - - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..6e451faa --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,4 @@ +parameters: + level: 6 + paths: + - src diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..e6995400 --- /dev/null +++ b/rector.php @@ -0,0 +1,15 @@ +withPaths([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->withPhpSets() + ->withTypeCoverageLevel(0) + ->withDeadCodeLevel(0) + ->withCodeQualityLevel(0); diff --git a/src/Input/PollingOptions.php b/src/ClientOptions/PollingOptions.php similarity index 90% rename from src/Input/PollingOptions.php rename to src/ClientOptions/PollingOptions.php index 60e2c3e3..a7ded11a 100644 --- a/src/Input/PollingOptions.php +++ b/src/ClientOptions/PollingOptions.php @@ -1,6 +1,8 @@ maxRetries = 80; diff --git a/src/CustomSleepMixin.php b/src/CustomSleepMixin.php index 614ed6f9..bb4203c8 100644 --- a/src/CustomSleepMixin.php +++ b/src/CustomSleepMixin.php @@ -1,5 +1,7 @@ readImage( - \TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg" + /** @phpstan-ignore-next-line */ + TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg" ); - } catch (\Exception $e) { + } catch (Exception) { throw new MindeeUnhandledException( - "To enable full support of PDF features, you need " . - "to enable ImageMagick on your PHP installation. Also, you " . - "should setup ImageMagick's policy to allow for PDF operations.", + "To enable full support of PDF features, you need " + . "to enable ImageMagick on your PHP installation. Also, you " + . "should setup ImageMagick's policy to allow for PDF operations.", ErrorCode::USER_MISSING_DEPENDENCY ); } diff --git a/src/Error/ErrorCode.php b/src/Error/ErrorCode.php index 599636d7..0a4ed812 100644 --- a/src/Error/ErrorCode.php +++ b/src/Error/ErrorCode.php @@ -1,5 +1,7 @@ minX = $minX; - $this->maxX = $maxX; - $this->minY = $minY; - $this->maxY = $maxY; - } + public function __construct(private float $minX, private float $maxX, private float $minY, private float $maxY) {} /** * Retrieves the minimum x coordinate. * - * @return float */ public function getMinX(): float { @@ -55,7 +29,6 @@ public function getMinX(): float /** * Retrieves the maximum x coordinate. * - * @return float */ public function getMaxX(): float { @@ -65,7 +38,6 @@ public function getMaxX(): float /** * Retrieves the minimum y coordinate. * - * @return float */ public function getMinY(): float { @@ -75,7 +47,6 @@ public function getMinY(): float /** * Retrieves the maximum y coordinate. * - * @return float */ public function getMaxY(): float { @@ -85,10 +56,9 @@ public function getMaxY(): float /** * Extends the BBox with the provided points. * - * @param array|Polygon $points Series of points to add to the BBox. - * @return void + * @param array|Polygon $points Series of points to add to the BBox. */ - public function extendWith(Polygon|array $points): void + public function extendWith(array|Polygon $points): void { if ($points instanceof Polygon) { $sequence = $points->getCoordinates(); diff --git a/src/Geometry/BBoxUtils.php b/src/Geometry/BBoxUtils.php index 81660a65..b089f996 100644 --- a/src/Geometry/BBoxUtils.php +++ b/src/Geometry/BBoxUtils.php @@ -1,5 +1,7 @@ $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. - * @return BBox|null + * @param array $bboxes BBoxes to merge. */ public static function mergeBBoxes(array $bboxes): ?BBox { @@ -80,6 +75,6 @@ public static function mergeBBoxes(array $bboxes): ?BBox $maxY = $bbox->getMaxY(); } } - return new BBox((float)$minX, (float)$maxX, (float)$minY, (float)$maxY); + return new BBox((float) $minX, (float) $maxX, (float) $minY, (float) $maxY); } } diff --git a/src/Geometry/MinMax.php b/src/Geometry/MinMax.php index 2e18b457..84787df3 100644 --- a/src/Geometry/MinMax.php +++ b/src/Geometry/MinMax.php @@ -1,5 +1,7 @@ min = $min; - $this->max = $max; - } + public function __construct(private readonly float $min, private readonly float $max) {} /** * @return float Retrieves the minimum. diff --git a/src/Geometry/MinMaxUtils.php b/src/Geometry/MinMaxUtils.php index 9ff86c79..1c1b9331 100644 --- a/src/Geometry/MinMaxUtils.php +++ b/src/Geometry/MinMaxUtils.php @@ -1,10 +1,14 @@ |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(array|Polygon $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.', @@ -35,12 +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. - * @return MinMax + * @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(array|Polygon $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 645f8d0e..f94ad890 100644 --- a/src/Geometry/Point.php +++ b/src/Geometry/Point.php @@ -1,38 +1,29 @@ */ class Point implements ArrayAccess { - /** - * @var float X coordinate. - */ - private float $x; - /** - * @var float Y coordinate. - */ - private float $y; - /** * @param float $x Input x coordinate. * @param float $y Input y coordinate. */ - public function __construct(float $x, float $y) - { - $this->x = $x; - $this->y = $y; - } + public function __construct(private float $x, private float $y) {} /** * Retrieves the x coordinate. * - * @return float */ public function getX(): float { @@ -42,7 +33,6 @@ public function getX(): float /** * Retrieves the y coordinate. * - * @return float */ public function getY(): float { @@ -65,7 +55,6 @@ public function offsetExists($offset): bool /** * Get an offset value. * @param integer|string $offset Use 0 or 1. - * @return float * @throws InvalidArgumentException If the offset is not 0 or 1. */ public function offsetGet($offset): float @@ -80,9 +69,8 @@ public function offsetGet($offset): float /** * Set an offset value. - * @param integer|string $offset Use 0 or 1. - * @param float|integer|string $value Coordinate value to set. - * @return void + * @param integer|string $offset Use 0 or 1. + * @param float|integer|string $value Coordinate value to set. * @throws InvalidArgumentException If the offset is not 0 or 1. */ public function offsetSet($offset, $value): void @@ -99,17 +87,10 @@ public function offsetSet($offset, $value): void /** * Get an offset value. * @param integer|string $offset Use 0 or 1. - * @return void * @throws InvalidArgumentException If the offset is not 0 or 1. */ public function offsetUnset($offset): void { - if ($offset === 0) { - unset($this->x); - } elseif ($offset === 1) { - unset($this->y); - } 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 339086d0..7db2bd3d 100644 --- a/src/Geometry/Polygon.php +++ b/src/Geometry/Polygon.php @@ -1,14 +1,20 @@ |null Vertices of the polygon. */ public ?array $coordinates; @@ -23,11 +29,11 @@ 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) { - if (!is_null($coordinates)) { + if (null !== $coordinates) { $this->coordinates = []; foreach ($coordinates as $point) { $this->coordinates[] = new Point($point[0], $point[1]); @@ -40,7 +46,6 @@ public function __construct(?array $coordinates = null) /** * Retrieves the centroid of the polygon. * - * @return Point */ public function getCentroid(): Point { @@ -50,7 +55,6 @@ public function getCentroid(): Point /** * Retrieves the upper and lower bounds of the y-axis. * - * @return MinMax */ public function getMinMaxY(): MinMax { @@ -63,7 +67,6 @@ public function getMinMaxY(): MinMax /** * Retrieves the upper and lower bounds of the x-axis. * - * @return MinMax */ public function getMinMaxX(): MinMax { @@ -100,7 +103,6 @@ public function isPointInX(Point $point): bool /** * Retrieves the minimum X coordinate. * - * @return float */ public function getMinX(): float { @@ -110,7 +112,6 @@ public function getMinX(): float /** * Retrieves the maximum X coordinate. * - * @return float */ public function getMaxX(): float { @@ -120,7 +121,6 @@ public function getMaxX(): float /** * Retrieves the minimum Y coordinate. * - * @return float */ public function getMinY(): float { @@ -130,7 +130,6 @@ public function getMinY(): float /** * Retrieves the maximum Y coordinate. * - * @return float */ public function getMaxY(): float { @@ -144,13 +143,12 @@ public function getMaxY(): float */ public function isEmpty(): bool { - return count($this->coordinates) == 0; + return count($this->coordinates) === 0; } /** * Retrieves the coordinates of the polygon. - * - * @return array|null + * @return array|null Coordinates of the polygon. */ public function getCoordinates(): ?array { @@ -162,7 +160,7 @@ public function getCoordinates(): ?array */ public function __toString(): string { - $formattedPoints = array_map(fn ($p) => "({$p->getX()},{$p->getY()})", $this->coordinates); + $formattedPoints = array_map(static fn($p) => "({$p->getX()},{$p->getY()})", $this->coordinates); $joinedPoints = implode(", ", $formattedPoints); return "($joinedPoints)"; diff --git a/src/Geometry/PolygonUtils.php b/src/Geometry/PolygonUtils.php index 4d808ae1..3668b3ec 100644 --- a/src/Geometry/PolygonUtils.php +++ b/src/Geometry/PolygonUtils.php @@ -1,10 +1,14 @@ |Polygon $vertices Array of points. */ - public static function getCentroid(array $vertices): Point + public static function getCentroid(array|Polygon $vertices): Point { + if ($vertices instanceof Polygon) { + $vertices = $vertices->getCoordinates(); + } $verticesSum = count($vertices); $xSum = 0.0; $ySum = 0.0; foreach ($vertices as $vertex) { - /* @var Point $vertex */ + /** @var Point $vertex */ $xSum += $vertex->getX(); $ySum += $vertex->getY(); } @@ -42,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; @@ -51,9 +57,8 @@ public static function compareOnY(Polygon $polygon1, Polygon $polygon2): int /** * Merges two polygons. * - * @param Polygon $base First polygon to merge. + * @param Polygon $base First polygon to merge. * @param Polygon $target Second polygon to merge. - * @return Polygon * @throws MindeeGeometryException Throws if both polygons are empty. */ public static function merge(Polygon $base, Polygon $target): Polygon @@ -78,14 +83,13 @@ public static function merge(Polygon $base, Polygon $target): Polygon /** * Creates a bounding box from one or two polygons. * - * @param Polygon $base First polygon. + * @param Polygon $base First polygon. * @param Polygon|null $target Second polygon. - * @return Polygon */ public static function createBoundingBoxFrom(Polygon $base, ?Polygon $target = null): Polygon { if ($target) { - $merged = PolygonUtils::merge($base, $target); + $merged = self::merge($base, $target); } else { $merged = $base; } @@ -105,24 +109,23 @@ public static function createBoundingBoxFrom(Polygon $base, ?Polygon $target = n /** * Generates a quadrilateral Polygon from a given prediction. * - * @param array $prediction Raw prediction array. - * @return Polygon + * @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); } /** * Checks whether a point is located within a coordinate range on the x-axis. * * @param Point $point Point to check. - * @param float $minX Lower bound. - * @param float $maxX Upper bound. + * @param float $minX Lower bound. + * @param float $maxX Upper bound. * @return boolean */ public static function isPointInX(Point $point, float $minX, float $maxX): bool @@ -134,8 +137,8 @@ public static function isPointInX(Point $point, float $minX, float $maxX): bool * Checks whether a point is located within a coordinate range on the y-axis. * * @param Point $point Point to check. - * @param float $minY Lower bound. - * @param float $maxY Upper bound. + * @param float $minY Lower bound. + * @param float $maxY Upper bound. * @return boolean */ public static function isPointInY(Point $point, float $minY, float $maxY): bool diff --git a/src/Extraction/ExtractedImage.php b/src/Image/ExtractedImage.php similarity index 53% rename from src/Extraction/ExtractedImage.php rename to src/Image/ExtractedImage.php index 51039fec..794cc2d7 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Image/ExtractedImage.php @@ -1,73 +1,50 @@ image = $image; - $this->filename = $filename; - $this->saveFormat = $saveFormat; - $this->pageId = $pageIndex; - $this->elementId = $index; } /** * Writes the image to a file. * Uses the default image format and filename. * - * @param string $outputPath The output directory (must exist). - * @param null|string $format The image format to use. Defaults to the save format if not provided. - * @param integer $quality Quality of the saved image. + * @param string $outputPath The output directory (must exist). + * @param null|string $format The image format to use. Defaults to the save format if not provided. + * @param integer $quality Quality of the saved image. * - * @return void - * @throws \ImagickException Throws if the image can't be processed. + * @throws ImagickException Throws if the image can't be processed. */ public function writeToFile(string $outputPath, ?string $format = null, int $quality = 100): void { @@ -78,9 +55,9 @@ 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); - } elseif (in_array($format, ['jpg', 'jpeg'])) { - $this->image->setImageCompression(\Imagick::COMPRESSION_JPEG); + $this->image->setOption('png:compression-level', (string) $finalQuality); + } elseif (in_array($format, ['jpg', 'jpeg'], true)) { + $this->image->setImageCompression(Imagick::COMPRESSION_JPEG); } $this->image->setImageCompressionQuality($quality); $this->image->writeImage($imagePath); @@ -91,7 +68,7 @@ public function writeToFile(string $outputPath, ?string $format = null, int $qua * * @return BytesInput Bytes input for the image. * - * @throws \ImagickException Throws if the image can't be processed. + * @throws ImagickException Throws if the image can't be processed. */ public function asInputSource(): BytesInput { diff --git a/src/Image/ImageCompressor.php b/src/Image/ImageCompressor.php index 0d339f2a..1c6b870f 100644 --- a/src/Image/ImageCompressor.php +++ b/src/Image/ImageCompressor.php @@ -1,11 +1,17 @@ saveFormat = $saveFormat; } - if ($this->inputSource->isPDF()) { - $this->pageImages = $this->pdfToImages($this->inputSource->readContents()[1]); + if ($this->inputSource->isPdf()) { + $this->pageImages = static::pdfToImages($this->inputSource->readContents()[1]); } else { try { - $image = new \Imagick(); + $image = new Imagick(); $image->readImageBlob($this->inputSource->readContents()[1]); - } catch (\ImagickException $e) { - throw new MindeePDFException( + } catch (ImagickException $e) { + throw new MindeePdfException( "Image couldn't be processed.", ErrorCode::IMAGE_CANT_PROCESS, $e @@ -84,7 +91,7 @@ public function __construct(LocalInputSource $localInput, ?string $saveFormat = * * @param string $fileBytes Input pdf. * - * @return \Imagick[] A list of pages. + * @return Imagick[] A list of pages. * * @throws MindeeImageException Throws if the image can't be handled. */ @@ -92,7 +99,7 @@ public static function pdfToImages(string $fileBytes): array { try { $images = []; - $imagick = new \Imagick(); + $imagick = new Imagick(); $imagick->readImageBlob($fileBytes); foreach ($imagick as $page) { @@ -101,7 +108,7 @@ public static function pdfToImages(string $fileBytes): array } return $images; - } catch (\ImagickException $e) { + } catch (ImagickException $e) { throw new MindeeImageException( "Couldn't convert PDF to images.", ErrorCode::FILE_OPERATION_ABORTED, @@ -119,30 +126,16 @@ public function getPageCount(): int return count($this->pageImages); } - /** - * Extract multiple images on a given page from a list of fields having position data. - * - * @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 - */ - public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array - { - $outputName ??= $this->filename; - return $this->extractFromPage($fields, $pageIndex, $outputName); - } /** * Extracts images from a page. * - * @param array $polygons List of polygons to extract. - * @param integer $pageIndex The page index to extract, begins at 0. + * @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. + * @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( @@ -166,7 +159,7 @@ public function extractPolygonsFromPage( $saveFormat ); } - } catch (\ImagickException $e) { + } catch (Exception $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } @@ -176,11 +169,11 @@ public function extractPolygonsFromPage( /** * Extracts a cropped portion from an image. * - * @param Polygon $polygon Polygon to extract. - * @param integer $pageIndex Page index to extract from. - * @param integer $index Index to use for naming the extracted image. - * @param null|string $filename Output filename. - * @param null|string $format Output format. + * @param Polygon $polygon Polygon to extract. + * @param integer $pageIndex Page index to extract from. + * @param integer $index Index to use for naming the extracted image. + * @param null|string $filename Output filename. + * @param null|string $format Output format. * * @return ExtractedImage Extracted image data. * @throws MindeeImageException Throws if the image can't be processed. @@ -195,103 +188,31 @@ public function extractPolygonFromPage( $bbox = BBoxUtils::generateBBoxFromPolygon($polygon); try { $extractedImageData = $this->extractImageFromBbox($bbox, $pageIndex); - } catch (\ImagickException $e) { + } 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 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. - * @param string $format The output format. - * - * @return null|ExtractedImage The extracted image, or null if the field does not have valid position data. - * - * @throws MindeeGeometryException Throws if a field does not contain positional data. - */ - public function extractImage( - BaseField $field, - int $pageIndex, - int $index, - string $filename, - string $format - ): ?ExtractedImage { - $polygon = null; - - if (!empty($field->polygon)) { - $polygon = $field->polygon; - } elseif (!empty($field->boundingBox)) { - $polygon = $field->boundingBox; - } elseif (!empty($field->quadrangle)) { - $polygon = $field->quadrangle; - } elseif (!empty($field->rectangle)) { - $polygon = $field->rectangle; - } - - if (null === $polygon) { - throw new MindeeGeometryException( - 'Provided field has no valid position data.', - ErrorCode::GEOMETRIC_OPERATION_FAILED - ); - } - - return $this->extractPolygonFromPage($polygon, $pageIndex, $index, $filename, $format); - } /** * Getter for the local input source. - * @return LocalInputSource */ public function getInputSource(): LocalInputSource { return $this->inputSource; } - /** - * Extracts images from a page. - * - * @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 - */ - protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array - { - $format ??= $this->saveFormat; - $extractedImages = []; - - $i = 0; - foreach ($fields as $field) { - $filename = sprintf('%s_page%d-%d.%s', $outputName, $pageIndex, $i, $format); - $extractedImage = $this->extractImage($field, $pageIndex, $i, $filename, $format); - if (null !== $extractedImage) { - $extractedImages[] = $extractedImage; - } - ++$i; - } - - return $extractedImages; - } - /** * Extracts an image from a set of coordinates. * - * @param BBox $bbox BBox coordinates. + * @param BBox $bbox BBox coordinates. * @param integer|float $pageIndex The page index to extract, begins at 0. - * @return \Imagick - * @throws \ImagickException Throws if the image can't be processed. + * @throws ImagickException Throws if the image can't be processed. */ - protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): \Imagick + protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): Imagick { $image = $this->pageImages[$pageIndex]->clone(); $width = $image->getImageWidth(); @@ -302,7 +223,7 @@ protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): \Imag $minY = round($bbox->getMinY() * $height); $maxY = round($bbox->getMaxY() * $height); - $image->cropImage((int)($maxX - $minX), (int)($maxY - $minY), (int)$minX, (int)$minY); + $image->cropImage((int) ($maxX - $minX), (int) ($maxY - $minY), (int) $minX, (int) $minY); return $image; } @@ -311,7 +232,7 @@ protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): \Imag * 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/Image/ImageUtils.php b/src/Image/ImageUtils.php index 45e15afa..43fb6837 100644 --- a/src/Image/ImageUtils.php +++ b/src/Image/ImageUtils.php @@ -1,9 +1,19 @@ setImageFormat('jpeg'); - } elseif ($image instanceof \SplFileObject) { - $imagickHandle = new \Imagick(); + } elseif ($image instanceof SplFileObject) { + $imagickHandle = new Imagick(); $imagickHandle->readImage($image->getRealPath()); - } elseif ($image instanceof \CURLFile) { - $imagickHandle = new \Imagick(); + } elseif ($image instanceof CURLFile) { + $imagickHandle = new Imagick(); $imagickHandle->readImage($image->getFilename()); } elseif (is_string($image) && file_exists($image) && is_file($image)) { - $imagickHandle = new \Imagick(); + $imagickHandle = new Imagick(); $imagickHandle->readImage($image); } elseif (is_resource($image)) { - $imagickHandle = new \Imagick(); - $imagickHandle->readImageBlob($image); + $imagickHandle = new Imagick(); + 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.' @@ -43,7 +59,7 @@ public static function toMagickImage(mixed $image): \Imagick return $imagickHandle; } catch (MindeeImageException $e) { throw $e; - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeeImageException( "Conversion to MagickImage failed.", ErrorCode::IMAGE_CANT_PROCESS, @@ -55,46 +71,43 @@ public static function toMagickImage(mixed $image): \Imagick /** * Resizes a provided MiniMagick Image with the given width & height, if present. * - * @param \Imagick $image Imagick image handle. - * @param integer|null $width Width to comply with. + * @param Imagick $image Imagick image handle. + * @param integer|null $width Width to comply with. * @param integer|null $height Height to comply with. - * @return void - * @throws \ImagickException Throws if resizing fails. + * @throws ImagickException Throws if resizing fails. */ - public static function resizeImage(\Imagick $image, ?int $width = null, int $height = null) + public static function resizeImage(Imagick $image, ?int $width = null, int $height = null): void { $width ??= $image->getImageWidth(); $height ??= $image->getImageHeight(); - $image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1); + $image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1); } /** * Compresses the quality of the provided MiniMagick image. - * @param \Imagick $image Imagick image handle. - * @param integer $quality Quality to apply to the image. This operation is independent of a JPG's base quality. - * @return void - * @throws \ImagickException Throws if compression fails. + * @param Imagick $image Imagick image handle. + * @param integer $quality Quality to apply to the image. This operation is independent of a JPG's base quality. + * @throws ImagickException Throws if compression fails. */ - public static function compressImageQuality(\Imagick $image, int $quality = 85) + public static function compressImageQuality(Imagick $image, int $quality = 85): void { $image->setImageCompressionQuality($quality); } /** * Converts an Imagick into a valid CURLFile handle. - * @param \Imagick $image Imagick image handle. - * @return \CURLFile + * @param Imagick $image Imagick image handle. * @throws MindeeImageException Throws if the image can't be converted back into a CURLFile. */ - public static function toCURLFile(\Imagick $image): \CURLFile + public static function toCURLFile(Imagick $image): CURLFile { try { $tempFile = tempnam(sys_get_temp_dir(), 'convert_image_'); file_put_contents($tempFile, $image->getImageBlob()); $filenameWithoutExtension = pathinfo($image->getFilename(), PATHINFO_FILENAME); - return new \CURLFile($tempFile, 'image/jpeg', $filenameWithoutExtension . '.jpg'); - } catch (\Exception $e) { + return new CURLFile($tempFile, 'image/jpeg', $filenameWithoutExtension . '.jpg'); + } catch (Exception $e) { throw new MindeeImageException( "Conversion to CURLFile failed.", ErrorCode::FILE_OPERATION_ABORTED, diff --git a/src/Input/Base64Input.php b/src/Input/Base64Input.php index 7972333e..cadbcbe3 100644 --- a/src/Input/Base64Input.php +++ b/src/Input/Base64Input.php @@ -1,7 +1,11 @@ tempFile = tempnam(sys_get_temp_dir(), 'b64_'); $this->fileName = $fileName; - file_put_contents($this->tempFile, base64_decode($strBase64)); + file_put_contents($this->tempFile, base64_decode($strBase64, true)); rename($this->tempFile, $this->tempFile .= "." . pathinfo($this->fileName, PATHINFO_EXTENSION)); $finfo = finfo_open(FILEINFO_MIME_TYPE); - $this->fileMimetype = finfo_buffer($finfo, base64_decode($strBase64)); - $this->fileObject = new \CURLFile($this->tempFile, $this->fileMimetype, $this->fileName); + $this->fileMimetype = finfo_buffer($finfo, base64_decode($strBase64, true)); + $this->fileObject = new CURLFile($this->tempFile, $this->fileMimetype, $this->fileName); parent::__construct(); } /** * Reads the contents of the file. - * - * @return array + * @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 c356384c..bc5ad5b4 100644 --- a/src/Input/BytesInput.php +++ b/src/Input/BytesInput.php @@ -1,7 +1,11 @@ tempFile, $this->tempFile .= "." . pathinfo($this->fileName, PATHINFO_EXTENSION)); $finfo = finfo_open(FILEINFO_MIME_TYPE); $this->fileMimetype = finfo_buffer($finfo, $fileBytes); - $this->fileObject = new \CURLFile($this->tempFile, $this->fileMimetype, $this->fileName); + $this->fileObject = new CURLFile($this->tempFile, $this->fileMimetype, $this->fileName); parent::__construct(); } /** * Reads the contents of the file. - * - * @return array + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/CommonOptions.php b/src/Input/CommonOptions.php deleted file mode 100644 index fca8df40..00000000 --- a/src/Input/CommonOptions.php +++ /dev/null @@ -1,35 +0,0 @@ -fullText = $fullText; - } - - /** - * @param boolean $fullText Whether to include the full text. - * @return $this - */ - public function setFullText(bool $fullText): PredictOptions - { - $this->fullText = $fullText; - return $this; - } -} diff --git a/src/Input/DataSchemaReplace.php b/src/Input/DataSchemaReplace.php deleted file mode 100644 index c7636e47..00000000 --- a/src/Input/DataSchemaReplace.php +++ /dev/null @@ -1,51 +0,0 @@ -fields = array_map(fn ($field) => new DataSchemaField($field), $serverResponse['fields']); - } - - /** - * @return array JSON representation. - */ - public function toJson(): array - { - return [ 'fields' => array_map(fn ($field) => $field->toJson(), $this->fields)]; - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return json_encode( - $this->toJson(), - JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES - ); - } -} diff --git a/src/Input/FileInput.php b/src/Input/FileInput.php index 14c836d8..5ea83d4c 100644 --- a/src/Input/FileInput.php +++ b/src/Input/FileInput.php @@ -1,9 +1,10 @@ file = &$file; $this->filePath = stream_get_meta_data($this->file)['uri']; $this->fileName = basename($this->filePath); $this->fileMimetype = mime_content_type($this->filePath); - $this->fileObject = new \CURLFile($this->filePath, $this->fileName, $this->fileMimetype); + $this->fileObject = new CURLFile($this->filePath, $this->fileName, $this->fileMimetype); parent::__construct(); } /** * Reads the contents of the file. - * - * @return array + * @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/InferenceParameters.php b/src/Input/InferenceParameters.php deleted file mode 100644 index 1cc3f51b..00000000 --- a/src/Input/InferenceParameters.php +++ /dev/null @@ -1,118 +0,0 @@ -|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 PollingOptions|null $pollingOptions Polling options. - */ - public function __construct( - string $modelId, - ?bool $rag = null, - ?bool $rawText = null, - ?bool $polygon = null, - ?bool $confidence = null, - ?string $alias = null, - ?array $webhooksIds = null, - ?string $textContext = null, - DataSchema|string|array|null $dataSchema = null, - ?PollingOptions $pollingOptions = null, - ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); - - $this->rag = $rag; - $this->rawText = $rawText; - $this->polygon = $polygon; - $this->confidence = $confidence; - if (isset($textContext)) { - $this->textContext = $textContext; - } - if (isset($dataSchema)) { - $this->dataSchema = new DataSchema($dataSchema); - } - } - - /** - * @return array Hash representation. - */ - public function asHash(): array - { - $outHash = parent::asHash(); - if (isset($this->rag)) { - $outHash['rag'] = $this->rag ? 'true' : 'false'; - } - if (isset($this->rawText)) { - $outHash['raw_text'] = $this->rawText ? 'true' : 'false'; - } - if (isset($this->polygon)) { - $outHash['polygon'] = $this->polygon ? 'true' : 'false'; - } - if (isset($this->confidence)) { - $outHash['confidence'] = $this->confidence ? 'true' : 'false'; - } - if (isset($this->textContext)) { - $outHash['text_context'] = $this->textContext; - } - if (isset($this->dataSchema)) { - $outHash['data_schema'] = strval($this->dataSchema); - } - return $outHash; - } -} diff --git a/src/Input/InputSource.php b/src/Input/InputSource.php index 52eac200..0feff98e 100644 --- a/src/Input/InputSource.php +++ b/src/Input/InputSource.php @@ -1,10 +1,10 @@ fileMimetype == 'application/octet-stream') { + if ($this->fileMimetype === 'application/octet-stream') { trigger_error( 'File type application/octet-stream is probably incorrect. ' . 'Try to run fixPDF() on the file.', @@ -73,17 +80,16 @@ public function checkNeedsFix(): void /** * Checks the mimetype integrity of a file. * - * @return void * @throws MindeeMimeTypeException Throws if the Mime type isn't allowed. */ - private function checkMimeType() + private function checkMimeType(): void { - if (!in_array($this->fileMimetype, ALLOWED_MIME_TYPES)) { + if (!in_array($this->fileMimetype, ALLOWED_MIME_TYPES, true)) { $fileTypes = implode(', ', ALLOWED_MIME_TYPES); throw new MindeeMimeTypeException( - "File type " . - $this->fileMimetype . - " not allowed, must be one of $fileTypes.", + "File type " + . $this->fileMimetype + . " not allowed, must be one of $fileTypes.", ErrorCode::USER_OPERATION_ERROR ); } @@ -102,32 +108,32 @@ public function __construct() * * @return boolean */ - public function isPDF(): bool + public function isPdf(): bool { $this->checkMimeType(); - return $this->fileMimetype == 'application/pdf'; + return $this->fileMimetype === 'application/pdf'; } /** * Counts the amount of pages in a PDF. * * @return integer - * @throws MindeePDFException Throws if the source pdf can't be properly processed. + * @throws MindeePdfException Throws if the source pdf can't be properly processed. * @throws MindeeSourceException Throws if the source isn't a pdf. */ public function getPageCount(): int { - if (!$this->isPDF()) { + if (!$this->isPdf()) { throw new MindeeSourceException( "File is not a PDF.", ErrorCode::USER_OPERATION_ERROR ); } - $pdf = new FPDI(); + $pdf = new Fpdi(); try { return $pdf->setSourceFile($this->fileObject->getFilename()); } catch (PdfParserException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -146,7 +152,6 @@ public function countDocPages(): int /** * @param string $fileBytes Raw data as bytes. - * @return void */ private function saveBytesAsFile(string $fileBytes): void { @@ -158,14 +163,13 @@ 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. - * @return void - * @throws MindeePDFException Throws if the pdf file can't be processed. + * @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 + public function mergePdfPages(array $pageNumbers): void { try { - $pdf = new FPDI(); + $pdf = new Fpdi(); $pdf->setSourceFile($this->filePath); foreach ($pageNumbers as $pageNumber) { $pdf->AddPage(); @@ -173,8 +177,8 @@ public function mergePDFPages(array $pageNumbers): void } $this->saveBytesAsFile($pdf->Output($this->fileName, 'S')); $pdf->Close(); - } catch (PdfParserException | PdfReaderException $e) { - throw new MindeePDFException( + } catch (PdfParserException|PdfReaderException $e) { + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -187,27 +191,27 @@ public function mergePDFPages(array $pageNumbers): void * @param integer $threshold Semi-arbitrary threshold of minimum bytes on the page for it to be considered empty. * * @return boolean - * @throws MindeePDFException Throws if the pdf file can't be processed. + * @throws MindeePdfException Throws if the pdf file can't be processed. */ - public function isPDFEmpty(int $threshold = 1024): bool + public function isPdfEmpty(int $threshold = 1024): bool { try { - $pdf = new FPDI(); + $pdf = new Fpdi(); $pageCount = $pdf->setSourceFile($this->fileObject->getFilename()); $pdf->Close(); for ($pageNumber = 0; $pageNumber < $pageCount; $pageNumber++) { - $pdfPage = new FPDI(); + $pdfPage = new Fpdi(); $pdfPage->setSourceFile($this->fileObject->getFilename()); $pdfPage->AddPage(); $pdfPage->useTemplate($pdfPage->importPage($pageNumber + 1)); - if (strlen($pdfPage->Output('', 'S')) > $threshold) { + if (strlen((string) $pdfPage->Output('', 'S')) > $threshold) { $pdfPage->Close(); return false; } $pdfPage->Close(); } - } catch (PdfParserException | PdfReaderException $e) { - throw new MindeePDFException( + } catch (PdfParserException|PdfReaderException $e) { + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -218,12 +222,11 @@ public function isPDFEmpty(int $threshold = 1024): bool /** * Reads the contents of the file. - * - * @return array + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { - $fileHandle = fopen($this->fileObject->getFilename(), 'rb'); + $fileHandle = fopen($this->fileObject->getFilename(), 'r'); $strContents = fread($fileHandle, filesize($this->fileObject->getFilename())); fclose($fileHandle); return [basename($this->fileObject->getFilename()), $strContents]; @@ -232,10 +235,9 @@ public function readContents(): array /** * Attempts to fix a PDF file. * - * @return void * @throws MindeeSourceException Throws if the file couldn't be fixed. */ - public function fixPDF(): void + public function fixPdf(): void { if (str_starts_with($this->fileMimetype, "image/")) { error_log("Input file is an image, skipping PDF fix."); @@ -263,17 +265,16 @@ public function fixPDF(): void } /** - * @param integer $quality Quality of the output file. - * @param integer|null $maxWidth Maximum width (Ignored for PDFs). - * @param integer|null $maxHeight Maximum height (Ignored for PDFs). - * @param boolean $forceSourceTextCompression Whether to force the operation on PDFs with source text. - * This will attempt to re-render PDF text over the rasterized original. - * The script will attempt to re-write text, but might not support all fonts & encoding. - * If disabled, ignored the operation. - * WARNING: this operation is strongly discouraged. - * @param boolean $disableSourceText If the PDF has source text, whether to re-apply it to the - * original or not. Needs force_source_text to work. - * @return void + * @param integer $quality Quality of the output file. + * @param integer|null $maxWidth Maximum width (Ignored for PDFs). + * @param integer|null $maxHeight Maximum height (Ignored for PDFs). + * @param boolean $forceSourceTextCompression Whether to force the operation on PDFs with source text. + * This will attempt to re-render PDF text over the rasterized original. + * The script will attempt to re-write text, but might not support all fonts & encoding. + * If disabled, ignored the operation. + * WARNING: this operation is strongly discouraged. + * @param boolean $disableSourceText If the PDF has source text, whether to re-apply it to the + * original or not. Needs force_source_text to work. */ public function compress( int $quality = 85, @@ -282,15 +283,15 @@ public function compress( bool $forceSourceTextCompression = false, bool $disableSourceText = true ): void { - if ($this->isPDF()) { - $this->fileObject = PDFCompressor::compress( + if ($this->isPdf()) { + $this->fileObject = PdfCompressor::compress( $this->fileObject, $quality, $forceSourceTextCompression, $disableSourceText ); $this->fileMimetype = 'application/pdf'; - $pathInfo = pathinfo($this->filePath); + $pathInfo = pathinfo((string) $this->filePath); $this->filePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . '.pdf'; } else { $this->fileObject = ImageCompressor::compress( @@ -300,7 +301,7 @@ public function compress( $maxHeight ); $this->fileMimetype = 'image/jpeg'; - $pathInfo = pathinfo($this->filePath); + $pathInfo = pathinfo((string) $this->filePath); $this->filePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . '.jpg'; } } @@ -313,10 +314,10 @@ public function compress( */ public function hasSourceText(): bool { - if (!$this->isPDF()) { + if (!$this->isPdf()) { return false; } - return PDFUtils::hasSourceText($this->filePath); + return PdfUtils::hasSourceText($this->filePath); } @@ -324,13 +325,12 @@ public function hasSourceText(): bool * Applies PDF-specific operations on the current file based on the specified PageOptions. * * @param PageOptions|null $pageOptions The options specifying which pages to modify or retain in the PDF file. - * @return void - * @throws MindeePDFException If a PDF processing error occurs during the operation. + * @throws MindeePdfException If a PDF processing error occurs during the operation. */ public function applyPageOptions(?PageOptions $pageOptions): void { - if ($this->isPDFEmpty()) { - throw new MindeePDFException( + if ($this->isPdfEmpty()) { + throw new MindeePdfException( "Pages are empty in PDF file.", ErrorCode::USER_INPUT_ERROR ); @@ -340,24 +340,24 @@ public function applyPageOptions(?PageOptions $pageOptions): void } $allPages = range(0, $this->getPageCount() - 1); $pagesToKeep = []; - if ($pageOptions->operation == KEEP_ONLY) { + if ($pageOptions->operation === KEEP_ONLY) { foreach ($pageOptions->pageIndexes as $pageId) { if ($pageId < 0) { $pageId = $this->getPageCount() + $pageId; } - if (!in_array($pageId, $allPages)) { + if (!in_array($pageId, $allPages, true)) { error_log("Page index '" . $pageId . "' is not present in source document"); } else { $pagesToKeep[] = $pageId; } } - } elseif ($pageOptions->operation == REMOVE) { + } elseif ($pageOptions->operation === REMOVE) { $pagesToRemove = []; foreach ($pageOptions->pageIndexes as $pageId) { if ($pageId < 0) { $pageId = $this->getPageCount() + $pageId; } - if (!in_array($pageId, $allPages)) { + if (!in_array($pageId, $allPages, true)) { error_log("Page index '" . $pageId . "' is not present in source document"); } else { $pagesToRemove[] = $pageId; @@ -365,17 +365,17 @@ public function applyPageOptions(?PageOptions $pageOptions): void } $pagesToKeep = array_diff($allPages, $pagesToRemove); } else { - throw new MindeePDFException( + throw new MindeePdfException( "Unknown operation '" . $pageOptions->operation . "'.", ErrorCode::USER_OPERATION_ERROR ); } if (count($pagesToKeep) < 1) { - throw new MindeePDFException( + throw new MindeePdfException( "Resulting PDF would have no pages left.", ErrorCode::USER_OPERATION_ERROR ); } - $this->mergePDFPages($pagesToKeep); + $this->mergePdfPages($pagesToKeep); } } diff --git a/src/Input/LocalResponse.php b/src/Input/LocalResponse.php index 9a16086d..6f48dede 100644 --- a/src/Input/LocalResponse.php +++ b/src/Input/LocalResponse.php @@ -1,10 +1,18 @@ $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); } /** - * @return array * @throws MindeeException Throws if the file contents cannot be converted to a valid array. + * @return array> The file contents. */ public function toArray(): array { @@ -119,10 +118,9 @@ public function isValidHMACSignature(string $secretKey, string $signature): bool /** * Deserialize the loaded local response into the requested BaseResponse-derived class. * - * Typically used when dealing with V2 webhook callbacks. - * - * @param string $responseClass The class name into which the payload should be deserialized. - * @return mixed An instance of responseClass populated with the file content. + * @template T + * @param class-string $responseClass The class name into which the payload should be deserialized. + * @return T An instance of responseClass populated with the file content. * @throws MindeeException If the provided class cannot be instantiated. */ public function deserializeResponse(string $responseClass): mixed diff --git a/src/Input/PageOptions.php b/src/Input/PageOptions.php index d3882e25..1f211217 100644 --- a/src/Input/PageOptions.php +++ b/src/Input/PageOptions.php @@ -1,5 +1,7 @@ |null $pageIndexes Indexes of the page. + * @param string $operation Operation to apply. + * @param integer $onMinPage Minimum page amount. */ - public int $onMinPage; - - /** - * @param array|null $pageIndexes Indexes of the page. - * @param string $operation Operation to apply. - * @param integer $onMinPage Minimum page amount. - */ - public function __construct( - ?array $pageIndexes = null, - string $operation = KEEP_ONLY, - int $onMinPage = 0 - ) { - $this->pageIndexes = $pageIndexes; - $this->operation = $operation; - $this->onMinPage = $onMinPage; - } + public function __construct(public ?array $pageIndexes = null, public string $operation = KEEP_ONLY, public int $onMinPage = 0) {} /** @@ -57,9 +38,9 @@ public function __construct( public function isEmpty(): bool { if ( - ($this->pageIndexes !== null && $this->pageIndexes !== []) || - $this->operation !== KEEP_ONLY || - $this->onMinPage !== 0 + ($this->pageIndexes !== null && $this->pageIndexes !== []) + || $this->operation !== KEEP_ONLY + || $this->onMinPage !== 0 ) { return false; } diff --git a/src/Input/PathInput.php b/src/Input/PathInput.php index e236866f..c41a4f93 100644 --- a/src/Input/PathInput.php +++ b/src/Input/PathInput.php @@ -1,7 +1,11 @@ filePath); $this->fileMimetype = $mimeType; - $this->fileObject = new \CURLFile($this->filePath, $mimeType, $this->fileName); + $this->fileObject = new CURLFile($this->filePath, $mimeType, $this->fileName); finfo_close($file); parent::__construct(); } diff --git a/src/Input/PredictOptions.php b/src/Input/PredictOptions.php deleted file mode 100644 index bc8daf0c..00000000 --- a/src/Input/PredictOptions.php +++ /dev/null @@ -1,60 +0,0 @@ -includeWords = $includeWords; - $this->cropper = $cropper; - } - - /** - * @param boolean $includeWords Whether to include the full text. - * @return $this - */ - public function setIncludeWords(bool $includeWords): PredictOptions - { - $this->includeWords = $includeWords; - return $this; - } - - /** - * @param boolean $cropper Whether to include the Cropper. - * @return $this - */ - public function setCropper(bool $cropper): PredictOptions - { - $this->cropper = $cropper; - return $this; - } -} diff --git a/src/Input/URLInputSource.php b/src/Input/UrlInputSource.php similarity index 67% rename from src/Input/URLInputSource.php rename to src/Input/UrlInputSource.php index 7c56fcf7..41116abf 100644 --- a/src/Input/URLInputSource.php +++ b/src/Input/UrlInputSource.php @@ -1,5 +1,7 @@ url, PHP_URL_PATH)); + $filename ??= basename(parse_url($this->url, PHP_URL_PATH)); if ($filename === '' || !pathinfo($filename, PATHINFO_EXTENSION)) { throw new MindeeSourceException( 'Filename must end with an extension.', @@ -66,11 +67,10 @@ public function asLocalInputSource( * Attempts to grab a file's extension. * * @param string|null $filename Initial file name. - * @return string|null */ private static function getFileExtension(?string $filename): ?string { - $extension = pathinfo($filename, PATHINFO_EXTENSION); + $extension = pathinfo((string) $filename, PATHINFO_EXTENSION); return $extension ? "." . strtolower($extension) : null; } @@ -78,7 +78,6 @@ private static function getFileExtension(?string $filename): ?string * Generates a unique filename. * * @param string|null $extension File extension, defaults to .tmp. - * @return string */ private static function generateFileName(?string $extension): string { @@ -90,14 +89,13 @@ private static function generateFileName(?string $extension): string /** * Downloads the file and saves it to the specified path. * - * @param string $path Path to save the file. - * @param string|null $filename Optional name for the saved file. - * @param string|null $username Optional username for credential-based authentication. - * @param string|null $password Optional password for credential-based authentication. - * @param string|null $token Optional token for JWT-based authentication. - * @param integer $maxRedirects Maximum amount of redirects to follow. - * @return void - * @throws MindeeSourceException Throws if the file can't be accessed, downloaded or saved. + * @param string $path Path to save the file. + * @param string|null $filename Optional name for the saved file. + * @param string|null $username Optional username for credential-based authentication. + * @param string|null $password Optional password for credential-based authentication. + * @param string|null $token Optional token for JWT-based authentication. + * @param integer $maxRedirects Maximum amount of redirects to follow. + * @throws MindeeSourceException Throws if the file can't be accessed, downloaded or saved. */ public function saveToFile( string $path, @@ -107,9 +105,9 @@ public function saveToFile( ?string $token = null, int $maxRedirects = 3 ): void { - $filename = $filename ?? basename(parse_url($this->url, PHP_URL_PATH)); + $filename ??= basename(parse_url($this->url, PHP_URL_PATH)); if ($filename === '' || !pathinfo($filename, PATHINFO_EXTENSION)) { - $filename = URLInputSource::generateFileName(URLInputSource::getFileExtension($filename)); + $filename = self::generateFileName(self::getFileExtension($filename)); } $response = $this->downloadFile($username, $password, $token, $maxRedirects); @@ -126,12 +124,11 @@ public function saveToFile( /** * Downloads the file from the URL. * - * @param string|null $username Optional username for credential-based authentication. - * @param string|null $password Optional password for credential-based authentication. - * @param string|null $token Optional token for JWT-based authentication. - * @param integer $maxRedirects Maximum amount of redirects to follow. - * @return string - * @throws MindeeSourceException Throws if the file can't be accessed or downloaded. + * @param string|null $username Optional username for credential-based authentication. + * @param string|null $password Optional password for credential-based authentication. + * @param string|null $token Optional token for JWT-based authentication. + * @param integer $maxRedirects Maximum amount of redirects to follow. + * @throws MindeeSourceException Throws if the file can't be accessed or downloaded. */ private function downloadFile( ?string $username = null, diff --git a/src/Input/WorkflowOptions.php b/src/Input/WorkflowOptions.php deleted file mode 100644 index 658ce647..00000000 --- a/src/Input/WorkflowOptions.php +++ /dev/null @@ -1,51 +0,0 @@ -alias = $alias; - $this->priority = $priority; - $this->publicUrl = $publicUrl; - $this->rag = $rag; - } -} diff --git a/src/PDF/PDFCompressor.php b/src/PDF/PDFCompressor.php deleted file mode 100644 index 5906f6a3..00000000 --- a/src/PDF/PDFCompressor.php +++ /dev/null @@ -1,245 +0,0 @@ -setDataTmFontInfoHasToBeIncluded(true); - $parser = new Parser([], $config); - $pdf = $parser->parseFile($pdfPath); - - if (strlen($pdf->getText()) > 0) { - if ($forceSourceTextCompression) { - if (!$disableSourceText) { - error_log("[WARNING] Re-writing PDF source-text is an EXPERIMENTAL feature."); - } else { - error_log("[WARNING] Source file '$pdfPath' contains text, but disable_source_text flag" - . " is set to false. Resulting file will not contain any embedded text."); - } - } else { - error_log("[WARNING] Source-text detected in input PDF '$pdfPath'. Aborting operation."); - $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; - copy($pdfPath, $outputPath); - return PDFUtils::toCURLFile($outputPath); - } - } - - try { - $fpdi = new CustomFPDI(); - $pageCount = $fpdi->setSourceFile($pdfPath); - } catch (CrossReferenceException $e) { - error_log("[WARNING] PDF format for '$pdfPath' is not directly supported." . - " Output PDF will be rasterized and source text won't be available."); - $pdfPath = PDFUtils::downgradePdfVersion($pdfPath); - $fpdi = new CustomFPDI(); - $pdf = $parser->parseFile($pdfPath); - $pageCount = $fpdi->setSourceFile($pdfPath); - } - - $outPdf = new CustomFPDI(); - for ($i = 1; $i <= $pageCount; $i++) { - list($tempJpegFile, $orientation) = static::processPdfPage($pdfPath, $i, $quality); - list($width, $height) = getimagesize($tempJpegFile); - $outPdf->AddPage($orientation, [$width, $height]); - $outPdf->Image($tempJpegFile, 0, 0, $width, $height); - unlink($tempJpegFile); - - if (!$disableSourceText) { - static::injectTextForPage($pdf->getPages()[$i - 1], $outPdf); - } - } - - $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; - $outPdf->Output('F', $outputPath); - $finalPDFSize = filesize($outputPath); - - if ($initialFileSize < $finalPDFSize) { - error_log("[WARNING] Compressed PDF for '$pdfPath' would be larger than input." . - " Aborting operation."); - return PDFUtils::toCURLFile(PDFUtils::extractFilePath($input)); - } - return PDFUtils::toCURLFile($outputPath); - } catch (\Exception $e) { - throw new MindeePDFException( - "Couldn't compress PDF.", - ErrorCode::FILE_OPERATION_ABORTED, - $e - ); - } - } - - /** - * @param Page $inputPage Input page. - * @param CustomFPDI $outputPdf Output PDF handle. - * @return void - * @throws MindeePDFException Throws if text can't be inserted into the page. - */ - private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void - { - try { - $textElements = PDFUtils::extractTextElements($inputPage); - 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 - ); - } - } - - /** - * 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. - * @return void - * @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. - * @throws MindeePDFException If there's an error processing the page. - */ - private static function processPdfPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array - { - try { - $singlePagePdf = new FPDI(); - $singlePagePdf->setSourceFile($sourcePdfPath); - $tplId = $singlePagePdf->importPage($pageIndex); - $size = $singlePagePdf->getTemplateSize($tplId); - - $singlePagePdf->AddPage($size['orientation'], [$size['width'], $size['height']]); - $singlePagePdf->useTemplate($tplId); - - $tempPdfFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.pdf'; - $singlePagePdf->Output('F', $tempPdfFile); - - $imagick = new \Imagick(); - $imagick->readImage($tempPdfFile); - $imagick->setImageFormat('jpg'); - $imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE); - $imagick->setImageCompression(\Imagick::COMPRESSION_JPEG); - $imagick->setImageCompressionQuality($imageQuality); - - $tempJpegFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.jpg'; - $imagick->writeImage($tempJpegFile); - - unlink($tempPdfFile); - - return [$tempJpegFile, $size['orientation']]; - } catch (\Exception $e) { - throw new MindeePDFException( - "Couldn't process PDF page $pageIndex.", - ErrorCode::PDF_CANT_PROCESS, - $e - ); - } - } -} diff --git a/src/Parsing/Common/ApiRequest.php b/src/Parsing/Common/ApiRequest.php deleted file mode 100644 index b39065b0..00000000 --- a/src/Parsing/Common/ApiRequest.php +++ /dev/null @@ -1,42 +0,0 @@ -url = $rawResponse['url']; - $this->error = $rawResponse['error']; - $this->resources = $rawResponse['resources']; - $this->status = $rawResponse['status']; - $this->statusCode = $rawResponse['status_code']; - } -} diff --git a/src/Parsing/Common/OrientationField.php b/src/Parsing/Common/OrientationField.php deleted file mode 100644 index 7409e208..00000000 --- a/src/Parsing/Common/OrientationField.php +++ /dev/null @@ -1,38 +0,0 @@ -value = 0; - if (array_key_exists($valueKey, $rawPrediction) && is_numeric($rawPrediction[$valueKey])) { - $this->value = intval($rawPrediction[$valueKey]); - if (!in_array($this->value, [0, 90, 180, 270])) { - $this->value = 0; - } - } - } -} diff --git a/src/Parsing/Standard/BaseField.php b/src/Parsing/Standard/BaseField.php deleted file mode 100644 index 1f2b5d92..00000000 --- a/src/Parsing/Standard/BaseField.php +++ /dev/null @@ -1,69 +0,0 @@ -pageId = $rawPrediction['page_id']; - } else { - $this->pageId = $pageId; - } - $this->reconstructed = $reconstructed; - if (array_key_exists($valueKey, $rawPrediction) && $rawPrediction[$valueKey] != 'N/A') { - $this->value = $rawPrediction[$valueKey]; - $this->setConfidence($rawPrediction); - } else { - $this->value = null; - } - } - - /** - * Compares with the value of another field. - * - * @param BaseField $obj Field to compare. - * @return boolean - */ - public function __compare(BaseField $obj): bool - { - return $this->value == $obj->value; - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return isset($this->value) ? strval($this->value) : ''; - } -} diff --git a/src/Parsing/Standard/ClassificationField.php b/src/Parsing/Standard/ClassificationField.php deleted file mode 100644 index d530f90d..00000000 --- a/src/Parsing/Standard/ClassificationField.php +++ /dev/null @@ -1,33 +0,0 @@ -boundingBox = PositionField::getQuadrilateral($rawPrediction, 'bounding_box'); - $this->quadrangle = PositionField::getQuadrilateral($rawPrediction, 'quadrangle'); - $this->rectangle = PositionField::getQuadrilateral($rawPrediction, 'rectangle'); - $this->polygon = PositionField::getPolygon($rawPrediction, 'polygon'); - - $this->value = $this->polygon; - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - if ($this->polygon) { - return 'Polygon with ' . count($this->polygon->getCoordinates()) . ' points.'; - } - if ($this->boundingBox) { - return 'Polygon with ' . count($this->boundingBox->getCoordinates()) . ' points.'; - } - if ($this->rectangle) { - return 'Polygon with ' . count($this->rectangle->getCoordinates()) . ' points.'; - } - if ($this->quadrangle) { - return 'Polygon with ' . count($this->quadrangle->getCoordinates()) . ' points.'; - } - - return ''; - } -} diff --git a/src/Parsing/Common/SummaryHelper.php b/src/Parsing/SummaryHelper.php similarity index 63% rename from src/Parsing/Common/SummaryHelper.php rename to src/Parsing/SummaryHelper.php index 9165acfc..2d551ada 100644 --- a/src/Parsing/Common/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -1,9 +1,14 @@ 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 function ($error) { - return new ErrorItem($error); - }, $serverResponse['errors']); - } else { - $this->errors = []; - } - } -} diff --git a/src/Parsing/V2/Field/FieldLocation.php b/src/Parsing/V2/Field/FieldLocation.php deleted file mode 100644 index e954a17b..00000000 --- a/src/Parsing/V2/Field/FieldLocation.php +++ /dev/null @@ -1,44 +0,0 @@ -polygon = isset($serverResponse['polygon']) ? new Polygon($serverResponse['polygon']) : null; - $this->page = isset($serverResponse['page']) && is_int($serverResponse['page']) - ? $serverResponse['page'] - : null; - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return $this->polygon ? $this->polygon . " on page $this->page" : ''; - } -} diff --git a/src/Parsing/V2/Field/SimpleField.php b/src/Parsing/V2/Field/SimpleField.php deleted file mode 100644 index f5177f2b..00000000 --- a/src/Parsing/V2/Field/SimpleField.php +++ /dev/null @@ -1,41 +0,0 @@ -value = array_key_exists('value', $serverResponse) ? $serverResponse['value'] : null; - if (is_int($this->value)) { - $this->value = (float) $this->value; - } - } - - /** - * @return string - */ - public function __toString(): string - { - if (is_bool($this->value)) { - return $this->value ? 'True' : 'False'; - } - if (is_numeric($this->value)) { - return number_format($this->value, 1, '.', ''); - } - return $this->value !== null ? (string)$this->value : ''; - } -} diff --git a/src/Parsing/V2/InferenceResponse.php b/src/Parsing/V2/InferenceResponse.php deleted file mode 100644 index cbb3ea87..00000000 --- a/src/Parsing/V2/InferenceResponse.php +++ /dev/null @@ -1,28 +0,0 @@ -inference = new Inference($rawResponse['inference']); - } -} diff --git a/src/Parsing/V2/RawTextPage.php b/src/Parsing/V2/RawTextPage.php deleted file mode 100644 index 07d88edc..00000000 --- a/src/Parsing/V2/RawTextPage.php +++ /dev/null @@ -1,32 +0,0 @@ -content = $serverResponse['content']; - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return $this->content ?? ''; - } -} diff --git a/src/PDF/CustomFPDI.php b/src/Pdf/CustomFpdi.php similarity index 69% rename from src/PDF/CustomFPDI.php rename to src/Pdf/CustomFpdi.php index 2b800f5f..96551c12 100644 --- a/src/PDF/CustomFPDI.php +++ b/src/Pdf/CustomFpdi.php @@ -1,40 +1,43 @@ x; } - if ($y == -1) { + if ((int) $y === -1) { $y = $this->y; } - if (intval($angle) != 0) { + if ((int) $angle !== 0) { $angle = -$angle; } $angle *= M_PI / 180; @@ -60,31 +63,30 @@ public function rotate(float $angle, float $x = -1, float $y = -1) /** * Ends the page, resetting any rotation. * - * @return void */ - protected function _endpage() //phpcs:ignore + protected function _endpage(): void { - if ($this->angle != 0) { + if ($this->angle !== 0) { $this->angle = 0; $this->_out('Q'); } parent::_endpage(); } + /** * Starts a new transformation. * - * @return void */ - public function startTransform() + public function startTransform(): void { $this->_out('q'); } + /** * Stops the current transformation. * - * @return void */ - public function stopTransform() + public function stopTransform(): void { $this->_out('Q'); } diff --git a/src/Extraction/ExtractedPdf.php b/src/Pdf/ExtractedPdf.php similarity index 81% rename from src/Extraction/ExtractedPdf.php rename to src/Pdf/ExtractedPdf.php index 860d642c..d23f3f67 100644 --- a/src/Extraction/ExtractedPdf.php +++ b/src/Pdf/ExtractedPdf.php @@ -1,30 +1,24 @@ pdfBytes = $pdfBytes; - $this->filename = $filename; } /** @@ -46,7 +38,7 @@ public function __construct(string $pdfBytes, string $filename) * * @return integer the number of pages in the file * - * @throws MindeePDFException Throws if FPDI is unable to process the file. + * @throws MindeePdfException Throws if FPDI is unable to process the file. */ public function getPageCount(): int { @@ -58,7 +50,7 @@ public function getPageCount(): int return $pdfHandle->setSourceFile($tempFilename); } catch (PdfParserException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Couldn't open PDF file.", ErrorCode::PDF_CANT_CREATE, $e @@ -70,7 +62,6 @@ public function getPageCount(): int * Write the PDF to a file. * * @param string $outputPath The output directory (must exist). - * @return void */ public function writeToFile(string $outputPath): void { diff --git a/src/Pdf/PdfCompressor.php b/src/Pdf/PdfCompressor.php new file mode 100644 index 00000000..8c474157 --- /dev/null +++ b/src/Pdf/PdfCompressor.php @@ -0,0 +1,179 @@ +setDataTmFontInfoHasToBeIncluded(true); + $parser = new Parser([], $config); + $pdf = $parser->parseFile($pdfPath); + + if ($pdf->getText() !== '') { + if ($forceSourceTextCompression) { + if (!$disableSourceText) { + error_log("[WARNING] Re-writing PDF source-text is an EXPERIMENTAL feature."); + } else { + error_log("[WARNING] Source file '$pdfPath' contains text, but disable_source_text flag" + . " is set to false. Resulting file will not contain any embedded text."); + } + } else { + error_log("[WARNING] Source-text detected in input PDF '$pdfPath'. Aborting operation."); + $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; + copy($pdfPath, $outputPath); + return PdfUtils::toCURLFile($outputPath); + } + } + + try { + $fpdi = new CustomFpdi(); + $pageCount = $fpdi->setSourceFile($pdfPath); + } catch (CrossReferenceException) { + error_log("[WARNING] PDF format for '$pdfPath' is not directly supported." + . " Output PDF will be rasterized and source text won't be available."); + $pdfPath = PdfUtils::downgradePdfVersion($pdfPath); + $fpdi = new CustomFpdi(); + $pdf = $parser->parseFile($pdfPath); + $pageCount = $fpdi->setSourceFile($pdfPath); + } + + $outPdf = new CustomFpdi(); + for ($i = 1; $i <= $pageCount; $i++) { + [$tempJpegFile, $orientation] = static::processPdfPage($pdfPath, $i, $quality); + [$width, $height] = getimagesize($tempJpegFile); + $outPdf->AddPage($orientation, [$width, $height]); + $outPdf->Image($tempJpegFile, 0, 0, $width, $height); + unlink($tempJpegFile); + + if (!$disableSourceText) { + static::injectTextForPage($pdf->getPages()[$i - 1], $outPdf); + } + } + + $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; + $outPdf->Output('F', $outputPath); + $finalPdfSize = filesize($outputPath); + + if ($initialFileSize < $finalPdfSize) { + error_log("[WARNING] Compressed PDF for '$pdfPath' would be larger than input." + . " Aborting operation."); + return PdfUtils::toCURLFile(PdfUtils::extractFilePath($input)); + } + return PdfUtils::toCURLFile($outputPath); + } catch (Exception $e) { + throw new MindeePdfException( + "Couldn't compress PDF.", + ErrorCode::FILE_OPERATION_ABORTED, + $e + ); + } + } + + /** + * @param Page $inputPage Input page. + * @param CustomFpdi $outputPdf Output PDF handle. + * @throws MindeePdfException Throws if text can't be inserted into the page. + */ + protected static function injectTextForPage(Page $inputPage, CustomFpdi $outputPdf): void + { + try { + $textElements = PdfUtils::extractTextElements($inputPage); + 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{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. + */ + protected static function processPdfPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array + { + try { + $singlePagePdf = new Fpdi(); + $singlePagePdf->setSourceFile($sourcePdfPath); + $tplId = $singlePagePdf->importPage($pageIndex); + $size = $singlePagePdf->getTemplateSize($tplId); + + $singlePagePdf->AddPage($size['orientation'], [$size['width'], $size['height']]); + $singlePagePdf->useTemplate($tplId); + + $tempPdfFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.pdf'; + $singlePagePdf->Output('F', $tempPdfFile); + + $imagick = new Imagick(); + $imagick->readImage($tempPdfFile); + $imagick->setImageFormat('jpg'); + $imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); + $imagick->setImageCompression(Imagick::COMPRESSION_JPEG); + $imagick->setImageCompressionQuality($imageQuality); + + $tempJpegFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.jpg'; + $imagick->writeImage($tempJpegFile); + + unlink($tempPdfFile); + + return [$tempJpegFile, $size['orientation']]; + } catch (Exception $e) { + throw new MindeePdfException( + "Couldn't process PDF page $pageIndex.", + ErrorCode::PDF_CANT_PROCESS, + $e + ); + } + } +} diff --git a/src/Extraction/PdfExtractor.php b/src/Pdf/PdfExtractor.php similarity index 53% rename from src/Extraction/PdfExtractor.php rename to src/Pdf/PdfExtractor.php index 36bac699..7c8991a2 100644 --- a/src/Extraction/PdfExtractor.php +++ b/src/Pdf/PdfExtractor.php @@ -1,17 +1,24 @@ fileName = $localInput->fileName; - if ($localInput->isPDF()) { + if ($localInput->isPdf()) { $this->pdfBytes = $localInput->readContents()[1]; } else { try { - $image = new \Imagick(); - } catch (\ImagickException $e) { - throw new MindeePDFException("Imagick could not process this file.\n", 0, $e); + $image = new Imagick(); + } catch (ImagickException $e) { + throw new MindeePdfException("Imagick could not process this file.\n", 0, $e); } $image->readImageBlob($localInput->readContents()[1]); $image->setImageFormat('pdf'); @@ -58,7 +65,7 @@ public function __construct(LocalInputSource $localInput) * * @return integer The number of pages in the file. * - * @throws MindeePDFException Throws if FPDI is unable to process the file. + * @throws MindeePdfException Throws if FPDI is unable to process the file. */ public function getPageCount(): int { @@ -70,27 +77,27 @@ public function getPageCount(): int return $pdfHandle->setSourceFile($tempFilename); } catch (PdfParserException $e) { - throw new MindeePDFException("Couldn't open PDF file. FPDI sent the following: ", 0, $e); + throw new MindeePdfException("Couldn't open PDF file. FPDI sent the following: ", 0, $e); } } /** * 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> $pageIndexes List of sub-lists of pages to keep. * * @return ExtractedPdf[] list of extracted documents * - * @throws MindeePDFException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. - * @throws \InvalidArgumentException Throws if invalid indexes are provided. + * @throws MindeePdfException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. + * @throws InvalidArgumentException Throws if invalid indexes are provided. */ - public function extractSubDocuments(mixed $pageIndexes): array + public function extractSubDocuments(array $pageIndexes): array { $extractedPdfs = []; foreach ($pageIndexes as $pageIndexElem) { if (empty($pageIndexElem)) { - throw new \InvalidArgumentException('Empty indexes not allowed for extraction.'); + throw new InvalidArgumentException('Empty indexes not allowed for extraction.'); } $extension = pathinfo($this->fileName, PATHINFO_EXTENSION); @@ -116,12 +123,12 @@ public function extractSubDocuments(mixed $pageIndexes): array $mergedPdfBytes = $pdf->Output('S'); } catch ( - CrossReferenceException | - FilterException | - PdfParserException | + CrossReferenceException| + FilterException| + PdfParserException| PdfReaderException $e ) { - throw new MindeePDFException("PDF file couldn't be processed during extraction.", 0, $e); + throw new MindeePdfException("PDF file couldn't be processed during extraction.", 0, $e); } $extractedPdfs[] = new ExtractedPdf($mergedPdfBytes, $fieldFilename); } @@ -132,58 +139,17 @@ 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 boolean $strict Whether to trust confidence scores or not. + * @param array> $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 */ - public function extractInvoices(mixed $pageIndexes, bool $strict = false): array + public function extractInvoices(array $pageIndexes, bool $strict = false): array { if (empty($pageIndexes)) { return []; } - if (!$strict) { - $indexes = array_map(fn ($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); - - return $this->extractSubDocuments($indexes); - } - if (is_array($pageIndexes[0])) { - return $this->extractSubDocuments($pageIndexes); - } - - $correctPageIndexes = []; - $currentList = []; - $previousConfidence = null; - - $i = 0; - foreach ($pageIndexes as $pageIndex) { - $confidence = $pageIndex->confidence; - $pageList = $pageIndex->pageIndexes; - - if ($confidence >= 0.5 && null === $previousConfidence) { - $currentList = $pageList; - } elseif ($confidence >= 0.5 && $i !== count($pageIndexes) - 1) { - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - $currentList = $pageList; - } elseif ($confidence < 0.5 && $i === count($pageIndexes) - 1) { - $currentList = array_merge($currentList, $pageList); - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - } else { - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - $correctPageIndexes[] = $pageList; - } - - $previousConfidence = $confidence; - ++$i; - } - - return $this->extractSubDocuments($correctPageIndexes); + return $this->extractSubDocuments($pageIndexes); } /** diff --git a/src/PDF/PDFUtils.php b/src/Pdf/PdfUtils.php similarity index 66% rename from src/PDF/PDFUtils.php rename to src/Pdf/PdfUtils.php index 710cfccf..1e0aefca 100644 --- a/src/PDF/PDFUtils.php +++ b/src/Pdf/PdfUtils.php @@ -1,25 +1,34 @@ getImageFilename(); - } elseif ($input instanceof \SplFileObject) { + } elseif ($input instanceof SplFileObject) { return $input->getRealPath(); } 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.'); + throw new MindeePdfException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); } - $imagickHandle->setImageFormat('jpeg'); - return $imagickHandle; - } catch (MindeePDFException $e) { + } catch (MindeePdfException $e) { throw $e; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Conversion to MagickImage failed.\n", ErrorCode::IMAGE_CANT_PROCESS, $e @@ -64,16 +78,16 @@ public static function hasSourceText(string $pdfPath): bool $config->setDataTmFontInfoHasToBeIncluded(true); $parser = new Parser([], $config); $pdf = $parser->parseFile($pdfPath); - return strlen($pdf->getText()) > 0; + return $pdf->getText() !== ''; } /** * 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. - * @throws MindeePDFException Throws if the PDF can't be parsed or text elements can't be extracted. + * @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 { @@ -86,15 +100,13 @@ public static function extractPagesTextElements(string $pdfPath): array foreach ($pdf->getPages() as $pageNumber => $page) { $result = self::extractTextElements($page); - $text = implode('', array_map(function ($e) { - return $e['text']; - }, $result)); + $text = implode('', array_map(static fn($e) => $e['text'], $result)); $allPagesTextElements[$pageNumber] = $text; } return $allPagesTextElements; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( 'Failed to parse PDF or extract text elements: ', ErrorCode::PDF_CANT_PROCESS, $e @@ -108,15 +120,15 @@ public static function extractPagesTextElements(string $pdfPath): array * * @param string $inputPath Input PDF path. * @return string Output path. - * @throws MindeePDFException Throws if the file can't be handled through Imagick. - * @throws Exception Will be thrown as MindeePDFException, this is just for PHPCS linting purposes. + * @throws MindeePdfException Throws if the file can't be handled through ghostscript. + * @throws Exception Will be thrown as MindeePdfException, this is just for PHPCS linting purposes. */ 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}\""; + $command = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET" + . " -dBATCH -sOutputFile=$outputPath \"$inputPath\""; exec($command, $output, $returnCode); @@ -127,7 +139,7 @@ public static function downgradePdfVersion(string $inputPath): string return $outputPath; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Cannot downgrade PDF version.", ErrorCode::PDF_CANT_PROCESS, $e @@ -140,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. - * @throws MindeePDFException Throws if the text elements can't be extracted. + * @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 { @@ -156,18 +169,18 @@ public static function extractTextElements(Page $page): array if (isset($text[1])) { $textElements[] = [ 'text' => $text[1], - 'rotation' => rad2deg(floatval($text[0][2])), - 'x' => floatval($text[0][4]), - 'y' => floatval($text[0][5]), + 'rotation' => rad2deg((float) ($text[0][2])), + 'x' => (float) ($text[0][4]), + 'y' => (float) ($text[0][5]), 'font' => $page->getFont($text[2]), - 'size' => floatval($text[3]) + 'size' => (float) ($text[3]), ]; } } return $textElements; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( 'Failed to parse text elements: ', ErrorCode::PDF_CANT_PROCESS, $e @@ -177,12 +190,12 @@ 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); + $parts = explode('-', (string) $cleanName, 2); $fontFamily = $parts[0]; $fontStyle = $parts[1] ?? ''; @@ -191,31 +204,30 @@ 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'; } return [ 'family' => $fontFamily, - 'style' => $fontStyle + 'style' => $fontStyle, ]; } /** * 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. - * @return void + * @param CustomFpdi $pdf The output PDF object. + * @param array $element Text element array containing text, position, font, size, and color. */ - public static function addTextElement(CustomFPDI $pdf, array $element): void + public static function addTextElement(CustomFpdi $pdf, array $element): void { $fontInfo = static::standardizeFontName($element['font']->getName()); $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. @@ -230,7 +242,6 @@ public static function addTextElement(CustomFPDI $pdf, array $element): void /** * Loads a pdf handle into a valid CURLFile handle. * @param string $path Imagick image handle. - * @return CURLFile * @throws MindeeImageException Throws if the image can't be converted back into a CURLFile. */ public static function toCURLFile(string $path): CURLFile diff --git a/src/Product/BillOfLading/BillOfLadingV1.php b/src/Product/BillOfLading/BillOfLadingV1.php deleted file mode 100644 index efec526b..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new BillOfLadingV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(BillOfLadingV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/Product/BillOfLading/BillOfLadingV1Carrier.php deleted file mode 100644 index 55b196e9..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1Carrier.php +++ /dev/null @@ -1,92 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->name = $rawPrediction["name"] ?? null; - $this->professionalNumber = $rawPrediction["professional_number"] ?? null; - $this->scac = $rawPrediction["scac"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelper::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelper::formatForDisplay($this->scac); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelper::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelper::formatForDisplay($this->scac); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Professional Number: " . $printable["professionalNumber"]; - $outStr .= "\n :SCAC: " . $printable["scac"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/Product/BillOfLading/BillOfLadingV1CarrierItem.php deleted file mode 100644 index 9b5d68fe..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ /dev/null @@ -1,119 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->grossWeight = isset($rawPrediction["gross_weight"]) ? - floatval($rawPrediction["gross_weight"]) : null; - $this->measurement = isset($rawPrediction["measurement"]) ? - floatval($rawPrediction["measurement"]) : null; - $this->measurementUnit = $rawPrediction["measurement_unit"] ?? null; - $this->quantity = isset($rawPrediction["quantity"]) ? - floatval($rawPrediction["quantity"]) : null; - $this->weightUnit = $rawPrediction["weight_unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["grossWeight"] = SummaryHelper::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelper::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelper::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelper::formatForDisplay($this->weightUnit); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["grossWeight"] = SummaryHelper::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelper::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelper::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelper::formatForDisplay($this->weightUnit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["grossWeight"], 12); - $outStr .= SummaryHelper::padString($printable["measurement"], 11); - $outStr .= SummaryHelper::padString($printable["measurementUnit"], 16); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["weightUnit"], 11); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php deleted file mode 100644 index b579173e..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ /dev/null @@ -1,70 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::carrierItemsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::carrierItemsSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | Gross Weight"; - $outStr .= " | Measurement"; - $outStr .= " | Measurement Unit"; - $outStr .= " | Quantity"; - $outStr .= " | Weight Unit"; - $outStr .= " |\n" . self::carrierItemsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1Consignee.php b/src/Product/BillOfLading/BillOfLadingV1Consignee.php deleted file mode 100644 index 2ebe9365..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1Consignee.php +++ /dev/null @@ -1,100 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1Document.php b/src/Product/BillOfLading/BillOfLadingV1Document.php deleted file mode 100644 index 8e836c2e..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1Document.php +++ /dev/null @@ -1,171 +0,0 @@ -billOfLadingNumber = new StringField( - $rawPrediction["bill_of_lading_number"], - $pageId - ); - if (!isset($rawPrediction["carrier"])) { - throw new MindeeUnsetException(); - } - $this->carrier = new BillOfLadingV1Carrier( - $rawPrediction["carrier"], - $pageId - ); - if (!isset($rawPrediction["carrier_items"])) { - throw new MindeeUnsetException(); - } - $this->carrierItems = new BillOfLadingV1CarrierItems( - $rawPrediction["carrier_items"], - $pageId - ); - if (!isset($rawPrediction["consignee"])) { - throw new MindeeUnsetException(); - } - $this->consignee = new BillOfLadingV1Consignee( - $rawPrediction["consignee"], - $pageId - ); - if (!isset($rawPrediction["date_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->dateOfIssue = new DateField( - $rawPrediction["date_of_issue"], - $pageId - ); - if (!isset($rawPrediction["departure_date"])) { - throw new MindeeUnsetException(); - } - $this->departureDate = new DateField( - $rawPrediction["departure_date"], - $pageId - ); - if (!isset($rawPrediction["notify_party"])) { - throw new MindeeUnsetException(); - } - $this->notifyParty = new BillOfLadingV1NotifyParty( - $rawPrediction["notify_party"], - $pageId - ); - if (!isset($rawPrediction["place_of_delivery"])) { - throw new MindeeUnsetException(); - } - $this->placeOfDelivery = new StringField( - $rawPrediction["place_of_delivery"], - $pageId - ); - if (!isset($rawPrediction["port_of_discharge"])) { - throw new MindeeUnsetException(); - } - $this->portOfDischarge = new StringField( - $rawPrediction["port_of_discharge"], - $pageId - ); - if (!isset($rawPrediction["port_of_loading"])) { - throw new MindeeUnsetException(); - } - $this->portOfLoading = new StringField( - $rawPrediction["port_of_loading"], - $pageId - ); - if (!isset($rawPrediction["shipper"])) { - throw new MindeeUnsetException(); - } - $this->shipper = new BillOfLadingV1Shipper( - $rawPrediction["shipper"], - $pageId - ); - } - - /** - * @return string String representation. - */ - 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() : ""; - $carrierItemsSummary = strval($this->carrierItems); - - $outStr = ":Bill of Lading Number: $this->billOfLadingNumber -:Shipper: $shipperToFieldList -:Consignee: $consigneeToFieldList -:Notify Party: $notifyPartyToFieldList -:Carrier: $carrierToFieldList -:Items: $carrierItemsSummary -:Port of Loading: $this->portOfLoading -:Port of Discharge: $this->portOfDischarge -:Place of Delivery: $this->placeOfDelivery -:Date of issue: $this->dateOfIssue -:Departure Date: $this->departureDate -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php deleted file mode 100644 index ec96befb..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ /dev/null @@ -1,100 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/Product/BillOfLading/BillOfLadingV1Shipper.php deleted file mode 100644 index bd3ae072..00000000 --- a/src/Product/BillOfLading/BillOfLadingV1Shipper.php +++ /dev/null @@ -1,100 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/DeliveryNote/DeliveryNoteV1.php b/src/Product/DeliveryNote/DeliveryNoteV1.php deleted file mode 100644 index 11c34e03..00000000 --- a/src/Product/DeliveryNote/DeliveryNoteV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new DeliveryNoteV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(DeliveryNoteV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/Product/DeliveryNote/DeliveryNoteV1Document.php deleted file mode 100644 index 426646b5..00000000 --- a/src/Product/DeliveryNote/DeliveryNoteV1Document.php +++ /dev/null @@ -1,119 +0,0 @@ -customerAddress = new StringField( - $rawPrediction["customer_address"], - $pageId - ); - if (!isset($rawPrediction["customer_name"])) { - throw new MindeeUnsetException(); - } - $this->customerName = new StringField( - $rawPrediction["customer_name"], - $pageId - ); - if (!isset($rawPrediction["delivery_date"])) { - throw new MindeeUnsetException(); - } - $this->deliveryDate = new DateField( - $rawPrediction["delivery_date"], - $pageId - ); - if (!isset($rawPrediction["delivery_number"])) { - throw new MindeeUnsetException(); - } - $this->deliveryNumber = new StringField( - $rawPrediction["delivery_number"], - $pageId - ); - if (!isset($rawPrediction["supplier_address"])) { - throw new MindeeUnsetException(); - } - $this->supplierAddress = new StringField( - $rawPrediction["supplier_address"], - $pageId - ); - if (!isset($rawPrediction["supplier_name"])) { - throw new MindeeUnsetException(); - } - $this->supplierName = new StringField( - $rawPrediction["supplier_name"], - $pageId - ); - if (!isset($rawPrediction["total_amount"])) { - throw new MindeeUnsetException(); - } - $this->totalAmount = new AmountField( - $rawPrediction["total_amount"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - - $outStr = ":Delivery Date: $this->deliveryDate -:Delivery Number: $this->deliveryNumber -:Supplier Name: $this->supplierName -:Supplier Address: $this->supplierAddress -:Customer Name: $this->customerName -:Customer Address: $this->customerAddress -:Total Amount: $this->totalAmount -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/Product/FinancialDocument/FinancialDocumentV1LineItem.php deleted file mode 100644 index ed04696d..00000000 --- a/src/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ /dev/null @@ -1,137 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->productCode = $rawPrediction["product_code"] ?? null; - $this->quantity = isset($rawPrediction["quantity"]) ? - floatval($rawPrediction["quantity"]) : null; - $this->taxAmount = isset($rawPrediction["tax_amount"]) ? - floatval($rawPrediction["tax_amount"]) : null; - $this->taxRate = isset($rawPrediction["tax_rate"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->totalAmount = isset($rawPrediction["total_amount"]) ? - floatval($rawPrediction["total_amount"]) : null; - $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["productCode"], 12); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["taxAmount"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 12); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitMeasure"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1.php b/src/Product/Fr/EnergyBill/EnergyBillV1.php deleted file mode 100644 index d027d1be..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new EnergyBillV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(EnergyBillV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/Product/Fr/EnergyBill/EnergyBillV1Document.php deleted file mode 100644 index 9667b67b..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ /dev/null @@ -1,210 +0,0 @@ -contractId = new StringField( - $rawPrediction["contract_id"], - $pageId - ); - if (!isset($rawPrediction["delivery_point"])) { - throw new MindeeUnsetException(); - } - $this->deliveryPoint = new StringField( - $rawPrediction["delivery_point"], - $pageId - ); - if (!isset($rawPrediction["due_date"])) { - throw new MindeeUnsetException(); - } - $this->dueDate = new DateField( - $rawPrediction["due_date"], - $pageId - ); - if (!isset($rawPrediction["energy_consumer"])) { - throw new MindeeUnsetException(); - } - $this->energyConsumer = new EnergyBillV1EnergyConsumer( - $rawPrediction["energy_consumer"], - $pageId - ); - if (!isset($rawPrediction["energy_supplier"])) { - throw new MindeeUnsetException(); - } - $this->energySupplier = new EnergyBillV1EnergySupplier( - $rawPrediction["energy_supplier"], - $pageId - ); - if (!isset($rawPrediction["energy_usage"])) { - throw new MindeeUnsetException(); - } - $this->energyUsage = new EnergyBillV1EnergyUsages( - $rawPrediction["energy_usage"], - $pageId - ); - if (!isset($rawPrediction["invoice_date"])) { - throw new MindeeUnsetException(); - } - $this->invoiceDate = new DateField( - $rawPrediction["invoice_date"], - $pageId - ); - if (!isset($rawPrediction["invoice_number"])) { - throw new MindeeUnsetException(); - } - $this->invoiceNumber = new StringField( - $rawPrediction["invoice_number"], - $pageId - ); - if (!isset($rawPrediction["meter_details"])) { - throw new MindeeUnsetException(); - } - $this->meterDetails = new EnergyBillV1MeterDetail( - $rawPrediction["meter_details"], - $pageId - ); - if (!isset($rawPrediction["subscription"])) { - throw new MindeeUnsetException(); - } - $this->subscription = new EnergyBillV1Subscriptions( - $rawPrediction["subscription"], - $pageId - ); - if (!isset($rawPrediction["taxes_and_contributions"])) { - throw new MindeeUnsetException(); - } - $this->taxesAndContributions = new EnergyBillV1TaxesAndContributions( - $rawPrediction["taxes_and_contributions"], - $pageId - ); - if (!isset($rawPrediction["total_amount"])) { - throw new MindeeUnsetException(); - } - $this->totalAmount = new AmountField( - $rawPrediction["total_amount"], - $pageId - ); - if (!isset($rawPrediction["total_before_taxes"])) { - throw new MindeeUnsetException(); - } - $this->totalBeforeTaxes = new AmountField( - $rawPrediction["total_before_taxes"], - $pageId - ); - if (!isset($rawPrediction["total_taxes"])) { - throw new MindeeUnsetException(); - } - $this->totalTaxes = new AmountField( - $rawPrediction["total_taxes"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $energySupplierToFieldList = $this->energySupplier != null ? $this->energySupplier->toFieldList() : ""; - $energyConsumerToFieldList = $this->energyConsumer != null ? $this->energyConsumer->toFieldList() : ""; - $subscriptionSummary = strval($this->subscription); - $energyUsageSummary = strval($this->energyUsage); - $taxesAndContributionsSummary = strval($this->taxesAndContributions); - $meterDetailsToFieldList = $this->meterDetails != null ? $this->meterDetails->toFieldList() : ""; - - $outStr = ":Invoice Number: $this->invoiceNumber -:Contract ID: $this->contractId -:Delivery Point: $this->deliveryPoint -:Invoice Date: $this->invoiceDate -:Due Date: $this->dueDate -:Total Before Taxes: $this->totalBeforeTaxes -:Total Taxes: $this->totalTaxes -:Total Amount: $this->totalAmount -:Energy Supplier: $energySupplierToFieldList -:Energy Consumer: $energyConsumerToFieldList -:Subscription: $subscriptionSummary -:Energy Usage: $energyUsageSummary -:Taxes and Contributions: $taxesAndContributionsSummary -:Meter Details: $meterDetailsToFieldList -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php deleted file mode 100644 index c09a048a..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ /dev/null @@ -1,84 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Name: " . $printable["name"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php deleted file mode 100644 index b95eafc3..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ /dev/null @@ -1,84 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Name: " . $printable["name"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php deleted file mode 100644 index 4e6767a6..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ /dev/null @@ -1,136 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->consumption = isset($rawPrediction["consumption"]) ? - floatval($rawPrediction["consumption"]) : null; - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) ? - floatval($rawPrediction["total"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["consumption"] = SummaryHelper::formatFloat($this->consumption); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["consumption"] = SummaryHelper::formatFloat($this->consumption); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["consumption"], 11); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unit"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php deleted file mode 100644 index 39f0b4c7..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ /dev/null @@ -1,74 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::energyUsageSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::energyUsageSeparator('-') . "\n "; - $outStr .= " | Consumption"; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit of Measure"; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::energyUsageSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php b/src/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php deleted file mode 100644 index 1917d973..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php +++ /dev/null @@ -1,92 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $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. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["meterNumber"] = SummaryHelper::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelper::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["meterNumber"] = SummaryHelper::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelper::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Meter Number: " . $printable["meterNumber"]; - $outStr .= "\n :Meter Type: " . $printable["meterType"]; - $outStr .= "\n :Unit of Power: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php deleted file mode 100644 index 04c81e3e..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ /dev/null @@ -1,119 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) ? - floatval($rawPrediction["total"]) : null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php deleted file mode 100644 index 78d4818f..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ /dev/null @@ -1,70 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::subscriptionSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::subscriptionSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::subscriptionSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php b/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php deleted file mode 100644 index 109d39b8..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php +++ /dev/null @@ -1,119 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) ? - floatval($rawPrediction["total"]) : null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php deleted file mode 100644 index 477416e1..00000000 --- a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ /dev/null @@ -1,70 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::taxesAndContributionsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::taxesAndContributionsSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::taxesAndContributionsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Fr/HealthCard/HealthCardV1.php b/src/Product/Fr/HealthCard/HealthCardV1.php deleted file mode 100644 index de417661..00000000 --- a/src/Product/Fr/HealthCard/HealthCardV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new HealthCardV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(HealthCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Fr/HealthCard/HealthCardV1Document.php b/src/Product/Fr/HealthCard/HealthCardV1Document.php deleted file mode 100644 index 94f2d774..00000000 --- a/src/Product/Fr/HealthCard/HealthCardV1Document.php +++ /dev/null @@ -1,86 +0,0 @@ -givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), - $rawPrediction["given_names"] - ); - if (!isset($rawPrediction["issuance_date"])) { - throw new MindeeUnsetException(); - } - $this->issuanceDate = new DateField( - $rawPrediction["issuance_date"], - $pageId - ); - if (!isset($rawPrediction["social_security"])) { - throw new MindeeUnsetException(); - } - $this->socialSecurity = new StringField( - $rawPrediction["social_security"], - $pageId - ); - if (!isset($rawPrediction["surname"])) { - throw new MindeeUnsetException(); - } - $this->surname = new StringField( - $rawPrediction["surname"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $givenNames = implode( - "\n ", - $this->givenNames - ); - - $outStr = ":Given Name(s): $givenNames -:Surname: $this->surname -:Social Security Number: $this->socialSecurity -:Issuance Date: $this->issuanceDate -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3.php b/src/Product/Fr/Payslip/PayslipV3.php deleted file mode 100644 index b58461ea..00000000 --- a/src/Product/Fr/Payslip/PayslipV3.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new PayslipV3Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(PayslipV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php deleted file mode 100644 index 7cdbb5a6..00000000 --- a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ /dev/null @@ -1,92 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->bankName = $rawPrediction["bank_name"] ?? null; - $this->iban = $rawPrediction["iban"] ?? null; - $this->swift = $rawPrediction["swift"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bankName"] = SummaryHelper::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelper::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelper::formatForDisplay($this->swift); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["bankName"] = SummaryHelper::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelper::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelper::formatForDisplay($this->swift); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Bank Name: " . $printable["bankName"]; - $outStr .= "\n :IBAN: " . $printable["iban"]; - $outStr .= "\n :SWIFT: " . $printable["swift"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3Document.php b/src/Product/Fr/Payslip/PayslipV3Document.php deleted file mode 100644 index 012dcc82..00000000 --- a/src/Product/Fr/Payslip/PayslipV3Document.php +++ /dev/null @@ -1,137 +0,0 @@ -bankAccountDetails = new PayslipV3BankAccountDetail( - $rawPrediction["bank_account_details"], - $pageId - ); - if (!isset($rawPrediction["employee"])) { - throw new MindeeUnsetException(); - } - $this->employee = new PayslipV3Employee( - $rawPrediction["employee"], - $pageId - ); - if (!isset($rawPrediction["employer"])) { - throw new MindeeUnsetException(); - } - $this->employer = new PayslipV3Employer( - $rawPrediction["employer"], - $pageId - ); - if (!isset($rawPrediction["employment"])) { - throw new MindeeUnsetException(); - } - $this->employment = new PayslipV3Employment( - $rawPrediction["employment"], - $pageId - ); - if (!isset($rawPrediction["paid_time_off"])) { - throw new MindeeUnsetException(); - } - $this->paidTimeOff = new PayslipV3PaidTimeOffs( - $rawPrediction["paid_time_off"], - $pageId - ); - if (!isset($rawPrediction["pay_detail"])) { - throw new MindeeUnsetException(); - } - $this->payDetail = new PayslipV3PayDetail( - $rawPrediction["pay_detail"], - $pageId - ); - if (!isset($rawPrediction["pay_period"])) { - throw new MindeeUnsetException(); - } - $this->payPeriod = new PayslipV3PayPeriod( - $rawPrediction["pay_period"], - $pageId - ); - if (!isset($rawPrediction["salary_details"])) { - throw new MindeeUnsetException(); - } - $this->salaryDetails = new PayslipV3SalaryDetails( - $rawPrediction["salary_details"], - $pageId - ); - } - - /** - * @return string String representation. - */ - 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() : ""; - $salaryDetailsSummary = strval($this->salaryDetails); - $payDetailToFieldList = $this->payDetail != null ? $this->payDetail->toFieldList() : ""; - $paidTimeOffSummary = strval($this->paidTimeOff); - - $outStr = ":Pay Period: $payPeriodToFieldList -:Employee: $employeeToFieldList -:Employer: $employerToFieldList -:Bank Account Details: $bankAccountDetailsToFieldList -:Employment: $employmentToFieldList -:Salary Details: $salaryDetailsSummary -:Pay Detail: $payDetailToFieldList -:Paid Time Off: $paidTimeOffSummary -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3Employee.php b/src/Product/Fr/Payslip/PayslipV3Employee.php deleted file mode 100644 index cfec9c3f..00000000 --- a/src/Product/Fr/Payslip/PayslipV3Employee.php +++ /dev/null @@ -1,124 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->dateOfBirth = $rawPrediction["date_of_birth"] ?? null; - $this->firstName = $rawPrediction["first_name"] ?? null; - $this->lastName = $rawPrediction["last_name"] ?? null; - $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. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelper::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelper::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelper::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelper::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelper::formatForDisplay($this->socialSecurityNumber); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelper::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelper::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelper::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelper::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelper::formatForDisplay($this->socialSecurityNumber); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Date of Birth: " . $printable["dateOfBirth"]; - $outStr .= "\n :First Name: " . $printable["firstName"]; - $outStr .= "\n :Last Name: " . $printable["lastName"]; - $outStr .= "\n :Phone Number: " . $printable["phoneNumber"]; - $outStr .= "\n :Registration Number: " . $printable["registrationNumber"]; - $outStr .= "\n :Social Security Number: " . $printable["socialSecurityNumber"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3Employer.php b/src/Product/Fr/Payslip/PayslipV3Employer.php deleted file mode 100644 index a46a7689..00000000 --- a/src/Product/Fr/Payslip/PayslipV3Employer.php +++ /dev/null @@ -1,124 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->companyId = $rawPrediction["company_id"] ?? null; - $this->companySite = $rawPrediction["company_site"] ?? null; - $this->nafCode = $rawPrediction["naf_code"] ?? null; - $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. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelper::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelper::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelper::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelper::formatForDisplay($this->urssafNumber); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelper::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelper::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelper::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelper::formatForDisplay($this->urssafNumber); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Company ID: " . $printable["companyId"]; - $outStr .= "\n :Company Site: " . $printable["companySite"]; - $outStr .= "\n :NAF Code: " . $printable["nafCode"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone Number: " . $printable["phoneNumber"]; - $outStr .= "\n :URSSAF Number: " . $printable["urssafNumber"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3Employment.php b/src/Product/Fr/Payslip/PayslipV3Employment.php deleted file mode 100644 index 2ab159f3..00000000 --- a/src/Product/Fr/Payslip/PayslipV3Employment.php +++ /dev/null @@ -1,124 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->category = $rawPrediction["category"] ?? null; - $this->coefficient = $rawPrediction["coefficient"] ?? null; - $this->collectiveAgreement = $rawPrediction["collective_agreement"] ?? null; - $this->jobTitle = $rawPrediction["job_title"] ?? null; - $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. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["category"] = SummaryHelper::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelper::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelper::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelper::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelper::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelper::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["category"] = SummaryHelper::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelper::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelper::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelper::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelper::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelper::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Category: " . $printable["category"]; - $outStr .= "\n :Coefficient: " . $printable["coefficient"]; - $outStr .= "\n :Collective Agreement: " . $printable["collectiveAgreement"]; - $outStr .= "\n :Job Title: " . $printable["jobTitle"]; - $outStr .= "\n :Position Level: " . $printable["positionLevel"]; - $outStr .= "\n :Seniority Date: " . $printable["seniorityDate"]; - $outStr .= "\n :Start Date: " . $printable["startDate"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php deleted file mode 100644 index 25a7fe9c..00000000 --- a/src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ /dev/null @@ -1,111 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->accrued = isset($rawPrediction["accrued"]) ? - floatval($rawPrediction["accrued"]) : null; - $this->period = $rawPrediction["period"] ?? null; - $this->ptoType = $rawPrediction["pto_type"] ?? null; - $this->remaining = isset($rawPrediction["remaining"]) ? - floatval($rawPrediction["remaining"]) : null; - $this->used = isset($rawPrediction["used"]) ? - floatval($rawPrediction["used"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["accrued"] = SummaryHelper::formatFloat($this->accrued); - $outArr["period"] = SummaryHelper::formatForDisplay($this->period, 6); - $outArr["ptoType"] = SummaryHelper::formatForDisplay($this->ptoType, 11); - $outArr["remaining"] = SummaryHelper::formatFloat($this->remaining); - $outArr["used"] = SummaryHelper::formatFloat($this->used); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["accrued"] = SummaryHelper::formatFloat($this->accrued); - $outArr["period"] = SummaryHelper::formatForDisplay($this->period); - $outArr["ptoType"] = SummaryHelper::formatForDisplay($this->ptoType); - $outArr["remaining"] = SummaryHelper::formatFloat($this->remaining); - $outArr["used"] = SummaryHelper::formatFloat($this->used); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["accrued"], 9); - $outStr .= SummaryHelper::padString($printable["period"], 6); - $outStr .= SummaryHelper::padString($printable["ptoType"], 11); - $outStr .= SummaryHelper::padString($printable["remaining"], 9); - $outStr .= SummaryHelper::padString($printable["used"], 9); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php deleted file mode 100644 index 464ca86d..00000000 --- a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ /dev/null @@ -1,68 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::paidTimeOffSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::paidTimeOffSeparator('-') . "\n "; - $outStr .= " | Accrued "; - $outStr .= " | Period"; - $outStr .= " | Type "; - $outStr .= " | Remaining"; - $outStr .= " | Used "; - $outStr .= " |\n" . self::paidTimeOffSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3PayDetail.php b/src/Product/Fr/Payslip/PayslipV3PayDetail.php deleted file mode 100644 index d904e97f..00000000 --- a/src/Product/Fr/Payslip/PayslipV3PayDetail.php +++ /dev/null @@ -1,158 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->grossSalary = isset($rawPrediction["gross_salary"]) ? - floatval($rawPrediction["gross_salary"]) : null; - $this->grossSalaryYtd = isset($rawPrediction["gross_salary_ytd"]) ? - floatval($rawPrediction["gross_salary_ytd"]) : null; - $this->incomeTaxRate = isset($rawPrediction["income_tax_rate"]) ? - floatval($rawPrediction["income_tax_rate"]) : null; - $this->incomeTaxWithheld = isset($rawPrediction["income_tax_withheld"]) ? - floatval($rawPrediction["income_tax_withheld"]) : null; - $this->netPaid = isset($rawPrediction["net_paid"]) ? - floatval($rawPrediction["net_paid"]) : null; - $this->netPaidBeforeTax = isset($rawPrediction["net_paid_before_tax"]) ? - floatval($rawPrediction["net_paid_before_tax"]) : null; - $this->netTaxable = isset($rawPrediction["net_taxable"]) ? - floatval($rawPrediction["net_taxable"]) : null; - $this->netTaxableYtd = isset($rawPrediction["net_taxable_ytd"]) ? - floatval($rawPrediction["net_taxable_ytd"]) : null; - $this->totalCostEmployer = isset($rawPrediction["total_cost_employer"]) ? - floatval($rawPrediction["total_cost_employer"]) : null; - $this->totalTaxesAndDeductions = isset($rawPrediction["total_taxes_and_deductions"]) ? - floatval($rawPrediction["total_taxes_and_deductions"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["grossSalary"] = SummaryHelper::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelper::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelper::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelper::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelper::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelper::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelper::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelper::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelper::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelper::formatFloat($this->totalTaxesAndDeductions); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["grossSalary"] = SummaryHelper::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelper::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelper::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelper::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelper::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelper::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelper::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelper::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelper::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelper::formatFloat($this->totalTaxesAndDeductions); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Gross Salary: " . $printable["grossSalary"]; - $outStr .= "\n :Gross Salary YTD: " . $printable["grossSalaryYtd"]; - $outStr .= "\n :Income Tax Rate: " . $printable["incomeTaxRate"]; - $outStr .= "\n :Income Tax Withheld: " . $printable["incomeTaxWithheld"]; - $outStr .= "\n :Net Paid: " . $printable["netPaid"]; - $outStr .= "\n :Net Paid Before Tax: " . $printable["netPaidBeforeTax"]; - $outStr .= "\n :Net Taxable: " . $printable["netTaxable"]; - $outStr .= "\n :Net Taxable YTD: " . $printable["netTaxableYtd"]; - $outStr .= "\n :Total Cost Employer: " . $printable["totalCostEmployer"]; - $outStr .= "\n :Total Taxes and Deductions: " . $printable["totalTaxesAndDeductions"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/Product/Fr/Payslip/PayslipV3PayPeriod.php deleted file mode 100644 index 19e9742d..00000000 --- a/src/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ /dev/null @@ -1,108 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->month = $rawPrediction["month"] ?? null; - $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. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelper::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelper::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelper::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelper::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :End Date: " . $printable["endDate"]; - $outStr .= "\n :Month: " . $printable["month"]; - $outStr .= "\n :Payment Date: " . $printable["paymentDate"]; - $outStr .= "\n :Start Date: " . $printable["startDate"]; - $outStr .= "\n :Year: " . $printable["year"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/Product/Fr/Payslip/PayslipV3SalaryDetail.php deleted file mode 100644 index 75c93f68..00000000 --- a/src/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ /dev/null @@ -1,112 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) ? - floatval($rawPrediction["amount"]) : null; - $this->base = isset($rawPrediction["base"]) ? - floatval($rawPrediction["base"]) : null; - $this->description = $rawPrediction["description"] ?? null; - $this->number = isset($rawPrediction["number"]) ? - floatval($rawPrediction["number"]) : null; - $this->rate = isset($rawPrediction["rate"]) ? - floatval($rawPrediction["rate"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["base"] = SummaryHelper::formatFloat($this->base); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["number"] = SummaryHelper::formatFloat($this->number); - $outArr["rate"] = SummaryHelper::formatFloat($this->rate); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["base"] = SummaryHelper::formatFloat($this->base); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["number"] = SummaryHelper::formatFloat($this->number); - $outArr["rate"] = SummaryHelper::formatFloat($this->rate); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["amount"], 12); - $outStr .= SummaryHelper::padString($printable["base"], 9); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["number"], 6); - $outStr .= SummaryHelper::padString($printable["rate"], 9); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php deleted file mode 100644 index 2a8dd8da..00000000 --- a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ /dev/null @@ -1,68 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::salaryDetailsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::salaryDetailsSeparator('-') . "\n "; - $outStr .= " | Amount "; - $outStr .= " | Base "; - $outStr .= " | Description "; - $outStr .= " | Number"; - $outStr .= " | Rate "; - $outStr .= " |\n" . self::salaryDetailsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Ind/IndianPassport/IndianPassportV1.php b/src/Product/Ind/IndianPassport/IndianPassportV1.php deleted file mode 100644 index a77be27b..00000000 --- a/src/Product/Ind/IndianPassport/IndianPassportV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new IndianPassportV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(IndianPassportV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/Product/Ind/IndianPassport/IndianPassportV1Document.php deleted file mode 100644 index 0de52578..00000000 --- a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ /dev/null @@ -1,311 +0,0 @@ -address1 = new StringField( - $rawPrediction["address1"], - $pageId - ); - if (!isset($rawPrediction["address2"])) { - throw new MindeeUnsetException(); - } - $this->address2 = new StringField( - $rawPrediction["address2"], - $pageId - ); - if (!isset($rawPrediction["address3"])) { - throw new MindeeUnsetException(); - } - $this->address3 = new StringField( - $rawPrediction["address3"], - $pageId - ); - if (!isset($rawPrediction["birth_date"])) { - throw new MindeeUnsetException(); - } - $this->birthDate = new DateField( - $rawPrediction["birth_date"], - $pageId - ); - if (!isset($rawPrediction["birth_place"])) { - throw new MindeeUnsetException(); - } - $this->birthPlace = new StringField( - $rawPrediction["birth_place"], - $pageId - ); - if (!isset($rawPrediction["country"])) { - throw new MindeeUnsetException(); - } - $this->country = new StringField( - $rawPrediction["country"], - $pageId - ); - if (!isset($rawPrediction["expiry_date"])) { - throw new MindeeUnsetException(); - } - $this->expiryDate = new DateField( - $rawPrediction["expiry_date"], - $pageId - ); - if (!isset($rawPrediction["file_number"])) { - throw new MindeeUnsetException(); - } - $this->fileNumber = new StringField( - $rawPrediction["file_number"], - $pageId - ); - if (!isset($rawPrediction["gender"])) { - throw new MindeeUnsetException(); - } - $this->gender = new ClassificationField( - $rawPrediction["gender"], - $pageId - ); - if (!isset($rawPrediction["given_names"])) { - throw new MindeeUnsetException(); - } - $this->givenNames = new StringField( - $rawPrediction["given_names"], - $pageId - ); - if (!isset($rawPrediction["id_number"])) { - throw new MindeeUnsetException(); - } - $this->idNumber = new StringField( - $rawPrediction["id_number"], - $pageId - ); - if (!isset($rawPrediction["issuance_date"])) { - throw new MindeeUnsetException(); - } - $this->issuanceDate = new DateField( - $rawPrediction["issuance_date"], - $pageId - ); - if (!isset($rawPrediction["issuance_place"])) { - throw new MindeeUnsetException(); - } - $this->issuancePlace = new StringField( - $rawPrediction["issuance_place"], - $pageId - ); - if (!isset($rawPrediction["legal_guardian"])) { - throw new MindeeUnsetException(); - } - $this->legalGuardian = new StringField( - $rawPrediction["legal_guardian"], - $pageId - ); - if (!isset($rawPrediction["mrz1"])) { - throw new MindeeUnsetException(); - } - $this->mrz1 = new StringField( - $rawPrediction["mrz1"], - $pageId - ); - if (!isset($rawPrediction["mrz2"])) { - throw new MindeeUnsetException(); - } - $this->mrz2 = new StringField( - $rawPrediction["mrz2"], - $pageId - ); - if (!isset($rawPrediction["name_of_mother"])) { - throw new MindeeUnsetException(); - } - $this->nameOfMother = new StringField( - $rawPrediction["name_of_mother"], - $pageId - ); - if (!isset($rawPrediction["name_of_spouse"])) { - throw new MindeeUnsetException(); - } - $this->nameOfSpouse = new StringField( - $rawPrediction["name_of_spouse"], - $pageId - ); - if (!isset($rawPrediction["old_passport_date_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportDateOfIssue = new DateField( - $rawPrediction["old_passport_date_of_issue"], - $pageId - ); - if (!isset($rawPrediction["old_passport_number"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportNumber = new StringField( - $rawPrediction["old_passport_number"], - $pageId - ); - if (!isset($rawPrediction["old_passport_place_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportPlaceOfIssue = new StringField( - $rawPrediction["old_passport_place_of_issue"], - $pageId - ); - if (!isset($rawPrediction["page_number"])) { - throw new MindeeUnsetException(); - } - $this->pageNumber = new ClassificationField( - $rawPrediction["page_number"], - $pageId - ); - if (!isset($rawPrediction["surname"])) { - throw new MindeeUnsetException(); - } - $this->surname = new StringField( - $rawPrediction["surname"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - - $outStr = ":Page Number: $this->pageNumber -:Country: $this->country -:ID Number: $this->idNumber -:Given Names: $this->givenNames -:Surname: $this->surname -:Birth Date: $this->birthDate -:Birth Place: $this->birthPlace -:Issuance Place: $this->issuancePlace -:Gender: $this->gender -:Issuance Date: $this->issuanceDate -:Expiry Date: $this->expiryDate -:MRZ Line 1: $this->mrz1 -:MRZ Line 2: $this->mrz2 -:Legal Guardian: $this->legalGuardian -:Name of Spouse: $this->nameOfSpouse -:Name of Mother: $this->nameOfMother -:Old Passport Date of Issue: $this->oldPassportDateOfIssue -:Old Passport Number: $this->oldPassportNumber -:Old Passport Place of Issue: $this->oldPassportPlaceOfIssue -:Address Line 1: $this->address1 -:Address Line 2: $this->address2 -:Address Line 3: $this->address3 -:File Number: $this->fileNumber -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Invoice/InvoiceV4LineItem.php b/src/Product/Invoice/InvoiceV4LineItem.php deleted file mode 100644 index 461fe49e..00000000 --- a/src/Product/Invoice/InvoiceV4LineItem.php +++ /dev/null @@ -1,137 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->productCode = $rawPrediction["product_code"] ?? null; - $this->quantity = isset($rawPrediction["quantity"]) ? - floatval($rawPrediction["quantity"]) : null; - $this->taxAmount = isset($rawPrediction["tax_amount"]) ? - floatval($rawPrediction["tax_amount"]) : null; - $this->taxRate = isset($rawPrediction["tax_rate"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->totalAmount = isset($rawPrediction["total_amount"]) ? - floatval($rawPrediction["total_amount"]) : null; - $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["productCode"], 12); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["taxAmount"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 12); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitMeasure"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1.php deleted file mode 100644 index 6dd5e427..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new NutritionFactsLabelV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(NutritionFactsLabelV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php deleted file mode 100644 index d8b0a3d2..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php deleted file mode 100644 index 48dc38b3..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php deleted file mode 100644 index 593ef85f..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php deleted file mode 100644 index bcba21c4..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php deleted file mode 100644 index 4059714e..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ /dev/null @@ -1,214 +0,0 @@ -addedSugars = new NutritionFactsLabelV1AddedSugar( - $rawPrediction["added_sugars"], - $pageId - ); - if (!isset($rawPrediction["calories"])) { - throw new MindeeUnsetException(); - } - $this->calories = new NutritionFactsLabelV1Calorie( - $rawPrediction["calories"], - $pageId - ); - if (!isset($rawPrediction["cholesterol"])) { - throw new MindeeUnsetException(); - } - $this->cholesterol = new NutritionFactsLabelV1Cholesterol( - $rawPrediction["cholesterol"], - $pageId - ); - if (!isset($rawPrediction["dietary_fiber"])) { - throw new MindeeUnsetException(); - } - $this->dietaryFiber = new NutritionFactsLabelV1DietaryFiber( - $rawPrediction["dietary_fiber"], - $pageId - ); - if (!isset($rawPrediction["nutrients"])) { - throw new MindeeUnsetException(); - } - $this->nutrients = new NutritionFactsLabelV1Nutrients( - $rawPrediction["nutrients"], - $pageId - ); - if (!isset($rawPrediction["protein"])) { - throw new MindeeUnsetException(); - } - $this->protein = new NutritionFactsLabelV1Protein( - $rawPrediction["protein"], - $pageId - ); - if (!isset($rawPrediction["saturated_fat"])) { - throw new MindeeUnsetException(); - } - $this->saturatedFat = new NutritionFactsLabelV1SaturatedFat( - $rawPrediction["saturated_fat"], - $pageId - ); - if (!isset($rawPrediction["serving_per_box"])) { - throw new MindeeUnsetException(); - } - $this->servingPerBox = new AmountField( - $rawPrediction["serving_per_box"], - $pageId - ); - if (!isset($rawPrediction["serving_size"])) { - throw new MindeeUnsetException(); - } - $this->servingSize = new NutritionFactsLabelV1ServingSize( - $rawPrediction["serving_size"], - $pageId - ); - if (!isset($rawPrediction["sodium"])) { - throw new MindeeUnsetException(); - } - $this->sodium = new NutritionFactsLabelV1Sodium( - $rawPrediction["sodium"], - $pageId - ); - if (!isset($rawPrediction["total_carbohydrate"])) { - throw new MindeeUnsetException(); - } - $this->totalCarbohydrate = new NutritionFactsLabelV1TotalCarbohydrate( - $rawPrediction["total_carbohydrate"], - $pageId - ); - if (!isset($rawPrediction["total_fat"])) { - throw new MindeeUnsetException(); - } - $this->totalFat = new NutritionFactsLabelV1TotalFat( - $rawPrediction["total_fat"], - $pageId - ); - if (!isset($rawPrediction["total_sugars"])) { - throw new MindeeUnsetException(); - } - $this->totalSugars = new NutritionFactsLabelV1TotalSugar( - $rawPrediction["total_sugars"], - $pageId - ); - if (!isset($rawPrediction["trans_fat"])) { - throw new MindeeUnsetException(); - } - $this->transFat = new NutritionFactsLabelV1TransFat( - $rawPrediction["trans_fat"], - $pageId - ); - } - - /** - * @return string String representation. - */ - 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() : ""; - $nutrientsSummary = strval($this->nutrients); - - $outStr = ":Serving per Box: $this->servingPerBox -:Serving Size: $servingSizeToFieldList -:Calories: $caloriesToFieldList -:Total Fat: $totalFatToFieldList -:Saturated Fat: $saturatedFatToFieldList -:Trans Fat: $transFatToFieldList -:Cholesterol: $cholesterolToFieldList -:Total Carbohydrate: $totalCarbohydrateToFieldList -:Dietary Fiber: $dietaryFiberToFieldList -:Total Sugars: $totalSugarsToFieldList -:Added Sugars: $addedSugarsToFieldList -:Protein: $proteinToFieldList -:sodium: $sodiumToFieldList -:nutrients: $nutrientsSummary -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php deleted file mode 100644 index 299bebe0..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ /dev/null @@ -1,111 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->name = $rawPrediction["name"] ?? null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 20); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["dailyValue"], 11); - $outStr .= SummaryHelper::padString($printable["name"], 20); - $outStr .= SummaryHelper::padString($printable["per100G"], 8); - $outStr .= SummaryHelper::padString($printable["perServing"], 11); - $outStr .= SummaryHelper::padString($printable["unit"], 4); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php deleted file mode 100644 index 17ae8072..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ /dev/null @@ -1,68 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::nutrientsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::nutrientsSeparator('-') . "\n "; - $outStr .= " | Daily Value"; - $outStr .= " | Name "; - $outStr .= " | Per 100g"; - $outStr .= " | Per Serving"; - $outStr .= " | Unit"; - $outStr .= " |\n" . self::nutrientsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php deleted file mode 100644 index 2585e5d0..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php deleted file mode 100644 index 25517a74..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php deleted file mode 100644 index 901d9fe5..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ /dev/null @@ -1,85 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) ? - floatval($rawPrediction["amount"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Amount: " . $printable["amount"]; - $outStr .= "\n :Unit: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php deleted file mode 100644 index f7d897d2..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ /dev/null @@ -1,103 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - $outStr .= "\n :Unit: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php deleted file mode 100644 index 51de30f7..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php deleted file mode 100644 index af421e6c..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php deleted file mode 100644 index cd122c34..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php deleted file mode 100644 index e3aded8f..00000000 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ /dev/null @@ -1,95 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; - $this->per100G = isset($rawPrediction["per_100g"]) ? - floatval($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) ? - floatval($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Product/Receipt/ReceiptV5LineItem.php b/src/Product/Receipt/ReceiptV5LineItem.php deleted file mode 100644 index 4d184697..00000000 --- a/src/Product/Receipt/ReceiptV5LineItem.php +++ /dev/null @@ -1,103 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->quantity = isset($rawPrediction["quantity"]) ? - floatval($rawPrediction["quantity"]) : null; - $this->totalAmount = isset($rawPrediction["total_amount"]) ? - floatval($rawPrediction["total_amount"]) : null; - $this->unitPrice = isset($rawPrediction["unit_price"]) ? - floatval($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Resume/ResumeV1Certificate.php b/src/Product/Resume/ResumeV1Certificate.php deleted file mode 100644 index 48e12144..00000000 --- a/src/Product/Resume/ResumeV1Certificate.php +++ /dev/null @@ -1,100 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->grade = $rawPrediction["grade"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->provider = $rawPrediction["provider"] ?? null; - $this->year = $rawPrediction["year"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["grade"] = SummaryHelper::formatForDisplay($this->grade, 10); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 30); - $outArr["provider"] = SummaryHelper::formatForDisplay($this->provider, 25); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["grade"] = SummaryHelper::formatForDisplay($this->grade); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["provider"] = SummaryHelper::formatForDisplay($this->provider); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["grade"], 10); - $outStr .= SummaryHelper::padString($printable["name"], 30); - $outStr .= SummaryHelper::padString($printable["provider"], 25); - $outStr .= SummaryHelper::padString($printable["year"], 4); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Resume/ResumeV1Education.php b/src/Product/Resume/ResumeV1Education.php deleted file mode 100644 index 00600645..00000000 --- a/src/Product/Resume/ResumeV1Education.php +++ /dev/null @@ -1,124 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->degreeDomain = $rawPrediction["degree_domain"] ?? null; - $this->degreeType = $rawPrediction["degree_type"] ?? null; - $this->endMonth = $rawPrediction["end_month"] ?? null; - $this->endYear = $rawPrediction["end_year"] ?? null; - $this->school = $rawPrediction["school"] ?? null; - $this->startMonth = $rawPrediction["start_month"] ?? null; - $this->startYear = $rawPrediction["start_year"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["degreeDomain"] = SummaryHelper::formatForDisplay($this->degreeDomain, 15); - $outArr["degreeType"] = SummaryHelper::formatForDisplay($this->degreeType, 25); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelper::formatForDisplay($this->school, 25); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["degreeDomain"] = SummaryHelper::formatForDisplay($this->degreeDomain); - $outArr["degreeType"] = SummaryHelper::formatForDisplay($this->degreeType); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelper::formatForDisplay($this->school); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["degreeDomain"], 15); - $outStr .= SummaryHelper::padString($printable["degreeType"], 25); - $outStr .= SummaryHelper::padString($printable["endMonth"], 9); - $outStr .= SummaryHelper::padString($printable["endYear"], 8); - $outStr .= SummaryHelper::padString($printable["school"], 25); - $outStr .= SummaryHelper::padString($printable["startMonth"], 11); - $outStr .= SummaryHelper::padString($printable["startYear"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Resume/ResumeV1Language.php b/src/Product/Resume/ResumeV1Language.php deleted file mode 100644 index 2cf6d711..00000000 --- a/src/Product/Resume/ResumeV1Language.php +++ /dev/null @@ -1,84 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->language = $rawPrediction["language"] ?? null; - $this->level = $rawPrediction["level"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["language"] = SummaryHelper::formatForDisplay($this->language); - $outArr["level"] = SummaryHelper::formatForDisplay($this->level, 20); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["language"] = SummaryHelper::formatForDisplay($this->language); - $outArr["level"] = SummaryHelper::formatForDisplay($this->level); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["language"], 8); - $outStr .= SummaryHelper::padString($printable["level"], 20); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Resume/ResumeV1ProfessionalExperience.php b/src/Product/Resume/ResumeV1ProfessionalExperience.php deleted file mode 100644 index 9d4cb0e0..00000000 --- a/src/Product/Resume/ResumeV1ProfessionalExperience.php +++ /dev/null @@ -1,140 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->contractType = $rawPrediction["contract_type"] ?? null; - $this->department = $rawPrediction["department"] ?? null; - $this->description = $rawPrediction["description"] ?? null; - $this->employer = $rawPrediction["employer"] ?? null; - $this->endMonth = $rawPrediction["end_month"] ?? null; - $this->endYear = $rawPrediction["end_year"] ?? null; - $this->role = $rawPrediction["role"] ?? null; - $this->startMonth = $rawPrediction["start_month"] ?? null; - $this->startYear = $rawPrediction["start_year"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["contractType"] = SummaryHelper::formatForDisplay($this->contractType, 15); - $outArr["department"] = SummaryHelper::formatForDisplay($this->department, 10); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["employer"] = SummaryHelper::formatForDisplay($this->employer, 25); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelper::formatForDisplay($this->role, 20); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["contractType"] = SummaryHelper::formatForDisplay($this->contractType); - $outArr["department"] = SummaryHelper::formatForDisplay($this->department); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["employer"] = SummaryHelper::formatForDisplay($this->employer); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelper::formatForDisplay($this->role); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["contractType"], 15); - $outStr .= SummaryHelper::padString($printable["department"], 10); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["employer"], 25); - $outStr .= SummaryHelper::padString($printable["endMonth"], 9); - $outStr .= SummaryHelper::padString($printable["endYear"], 8); - $outStr .= SummaryHelper::padString($printable["role"], 20); - $outStr .= SummaryHelper::padString($printable["startMonth"], 11); - $outStr .= SummaryHelper::padString($printable["startYear"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Resume/ResumeV1SocialNetworksUrl.php b/src/Product/Resume/ResumeV1SocialNetworksUrl.php deleted file mode 100644 index 16bbf5fb..00000000 --- a/src/Product/Resume/ResumeV1SocialNetworksUrl.php +++ /dev/null @@ -1,84 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->name = $rawPrediction["name"] ?? null; - $this->url = $rawPrediction["url"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 20); - $outArr["url"] = SummaryHelper::formatForDisplay($this->url, 50); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["url"] = SummaryHelper::formatForDisplay($this->url); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["name"], 20); - $outStr .= SummaryHelper::padString($printable["url"], 50); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/Product/Us/HealthcareCard/HealthcareCardV1.php deleted file mode 100644 index 0aa6d05f..00000000 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new HealthcareCardV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(HealthcareCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php deleted file mode 100644 index 8fc4287a..00000000 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ /dev/null @@ -1,85 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->serviceFees = isset($rawPrediction["service_fees"]) ? - floatval($rawPrediction["service_fees"]) : null; - $this->serviceName = $rawPrediction["service_name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["serviceFees"] = SummaryHelper::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelper::formatForDisplay($this->serviceName, 20); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["serviceFees"] = SummaryHelper::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelper::formatForDisplay($this->serviceName); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["serviceFees"], 12); - $outStr .= SummaryHelper::padString($printable["serviceName"], 20); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php deleted file mode 100644 index 0722d305..00000000 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ /dev/null @@ -1,62 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::copaysSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::copaysSeparator('-') . "\n "; - $outStr .= " | Service Fees"; - $outStr .= " | Service Name "; - $outStr .= " |\n" . self::copaysSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Document.php b/src/Product/Us/HealthcareCard/HealthcareCardV1Document.php deleted file mode 100644 index 0e28bb15..00000000 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Document.php +++ /dev/null @@ -1,207 +0,0 @@ -companyName = new StringField( - $rawPrediction["company_name"], - $pageId - ); - if (!isset($rawPrediction["copays"])) { - throw new MindeeUnsetException(); - } - $this->copays = new HealthcareCardV1Copays( - $rawPrediction["copays"], - $pageId - ); - if (!isset($rawPrediction["dependents"])) { - throw new MindeeUnsetException(); - } - $this->dependents = $rawPrediction["dependents"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), - $rawPrediction["dependents"] - ); - if (!isset($rawPrediction["enrollment_date"])) { - throw new MindeeUnsetException(); - } - $this->enrollmentDate = new DateField( - $rawPrediction["enrollment_date"], - $pageId - ); - if (!isset($rawPrediction["group_number"])) { - throw new MindeeUnsetException(); - } - $this->groupNumber = new StringField( - $rawPrediction["group_number"], - $pageId - ); - if (!isset($rawPrediction["issuer_80840"])) { - throw new MindeeUnsetException(); - } - $this->issuer80840 = new StringField( - $rawPrediction["issuer_80840"], - $pageId - ); - if (!isset($rawPrediction["member_id"])) { - throw new MindeeUnsetException(); - } - $this->memberId = new StringField( - $rawPrediction["member_id"], - $pageId - ); - if (!isset($rawPrediction["member_name"])) { - throw new MindeeUnsetException(); - } - $this->memberName = new StringField( - $rawPrediction["member_name"], - $pageId - ); - if (!isset($rawPrediction["payer_id"])) { - throw new MindeeUnsetException(); - } - $this->payerId = new StringField( - $rawPrediction["payer_id"], - $pageId - ); - if (!isset($rawPrediction["plan_name"])) { - throw new MindeeUnsetException(); - } - $this->planName = new StringField( - $rawPrediction["plan_name"], - $pageId - ); - if (!isset($rawPrediction["rx_bin"])) { - throw new MindeeUnsetException(); - } - $this->rxBin = new StringField( - $rawPrediction["rx_bin"], - $pageId - ); - if (!isset($rawPrediction["rx_grp"])) { - throw new MindeeUnsetException(); - } - $this->rxGrp = new StringField( - $rawPrediction["rx_grp"], - $pageId - ); - if (!isset($rawPrediction["rx_id"])) { - throw new MindeeUnsetException(); - } - $this->rxId = new StringField( - $rawPrediction["rx_id"], - $pageId - ); - if (!isset($rawPrediction["rx_pcn"])) { - throw new MindeeUnsetException(); - } - $this->rxPcn = new StringField( - $rawPrediction["rx_pcn"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $dependents = implode( - "\n ", - $this->dependents - ); - $copaysSummary = strval($this->copays); - - $outStr = ":Company Name: $this->companyName -:Plan Name: $this->planName -:Member Name: $this->memberName -:Member ID: $this->memberId -:Issuer 80840: $this->issuer80840 -:Dependents: $dependents -:Group Number: $this->groupNumber -:Payer ID: $this->payerId -:RX BIN: $this->rxBin -:RX ID: $this->rxId -:RX GRP: $this->rxGrp -:RX PCN: $this->rxPcn -:Copays: $copaysSummary -:Enrollment Date: $this->enrollmentDate -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Us/UsMail/UsMailV3.php b/src/Product/Us/UsMail/UsMailV3.php deleted file mode 100644 index eee81dd3..00000000 --- a/src/Product/Us/UsMail/UsMailV3.php +++ /dev/null @@ -1,40 +0,0 @@ -prediction = new UsMailV3Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(UsMailV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { - } - } - } -} diff --git a/src/Product/Us/UsMail/UsMailV3Document.php b/src/Product/Us/UsMail/UsMailV3Document.php deleted file mode 100644 index c83f9bcb..00000000 --- a/src/Product/Us/UsMail/UsMailV3Document.php +++ /dev/null @@ -1,100 +0,0 @@ -isReturnToSender = new BooleanField( - $rawPrediction["is_return_to_sender"], - $pageId - ); - if (!isset($rawPrediction["recipient_addresses"])) { - throw new MindeeUnsetException(); - } - $this->recipientAddresses = new UsMailV3RecipientAddresses( - $rawPrediction["recipient_addresses"], - $pageId - ); - if (!isset($rawPrediction["recipient_names"])) { - throw new MindeeUnsetException(); - } - $this->recipientNames = $rawPrediction["recipient_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), - $rawPrediction["recipient_names"] - ); - if (!isset($rawPrediction["sender_address"])) { - throw new MindeeUnsetException(); - } - $this->senderAddress = new UsMailV3SenderAddress( - $rawPrediction["sender_address"], - $pageId - ); - if (!isset($rawPrediction["sender_name"])) { - throw new MindeeUnsetException(); - } - $this->senderName = new StringField( - $rawPrediction["sender_name"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $senderAddressToFieldList = $this->senderAddress != null ? $this->senderAddress->toFieldList() : ""; - $recipientNames = implode( - "\n ", - $this->recipientNames - ); - $recipientAddressesSummary = strval($this->recipientAddresses); - - $outStr = ":Sender Name: $this->senderName -:Sender Address: $senderAddressToFieldList -:Recipient Names: $recipientNames -:Recipient Addresses: $recipientAddressesSummary -:Return to Sender: $this->isReturnToSender -"; - return SummaryHelper::cleanOutString($outStr); - } -} diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/Product/Us/UsMail/UsMailV3RecipientAddress.php deleted file mode 100644 index 472de2ef..00000000 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ /dev/null @@ -1,132 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->city = $rawPrediction["city"] ?? null; - $this->complete = $rawPrediction["complete"] ?? null; - $this->isAddressChange = $rawPrediction["is_address_change"] ?? null; - $this->postalCode = $rawPrediction["postal_code"] ?? null; - $this->privateMailboxNumber = $rawPrediction["private_mailbox_number"] ?? null; - $this->state = $rawPrediction["state"] ?? null; - $this->street = $rawPrediction["street"] ?? null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city, 15); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete, 35); - $outArr["isAddressChange"] = SummaryHelper::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelper::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street, 25); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit, 15); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete); - $outArr["isAddressChange"] = SummaryHelper::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelper::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in an rST table. - * - * @return string - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["city"], 15); - $outStr .= SummaryHelper::padString($printable["complete"], 35); - $outStr .= SummaryHelper::padString($printable["isAddressChange"], 17); - $outStr .= SummaryHelper::padString($printable["postalCode"], 11); - $outStr .= SummaryHelper::padString($printable["privateMailboxNumber"], 22); - $outStr .= SummaryHelper::padString($printable["state"], 5); - $outStr .= SummaryHelper::padString($printable["street"], 25); - $outStr .= SummaryHelper::padString($printable["unit"], 15); - return rtrim(SummaryHelper::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toTableLine()); - } -} diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php deleted file mode 100644 index 42e4c573..00000000 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ /dev/null @@ -1,74 +0,0 @@ -getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::recipientAddressesSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::recipientAddressesSeparator('-') . "\n "; - $outStr .= " | City "; - $outStr .= " | Complete Address "; - $outStr .= " | Is Address Change"; - $outStr .= " | Postal Code"; - $outStr .= " | Private Mailbox Number"; - $outStr .= " | State"; - $outStr .= " | Street "; - $outStr .= " | Unit "; - $outStr .= " |\n" . self::recipientAddressesSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/Product/Us/UsMail/UsMailV3SenderAddress.php b/src/Product/Us/UsMail/UsMailV3SenderAddress.php deleted file mode 100644 index 24287a5a..00000000 --- a/src/Product/Us/UsMail/UsMailV3SenderAddress.php +++ /dev/null @@ -1,108 +0,0 @@ -setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->city = $rawPrediction["city"] ?? null; - $this->complete = $rawPrediction["complete"] ?? null; - $this->postalCode = $rawPrediction["postal_code"] ?? null; - $this->state = $rawPrediction["state"] ?? null; - $this->street = $rawPrediction["street"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city, 15); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete, 35); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street, 25); - return $outArr; - } - - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - * @return string - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :City: " . $printable["city"]; - $outStr .= "\n :Complete Address: " . $printable["complete"]; - $outStr .= "\n :Postal Code: " . $printable["postalCode"]; - $outStr .= "\n :State: " . $printable["state"]; - $outStr .= "\n :Street: " . $printable["street"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelper::cleanOutString($this->toFieldList()); - } -} diff --git a/src/Client.php b/src/V1/Client.php similarity index 60% rename from src/Client.php rename to src/V1/Client.php index 05ea05e1..a5fdc433 100644 --- a/src/Client.php +++ b/src/V1/Client.php @@ -1,40 +1,38 @@ apiKey = $apiKey ?: getenv('MINDEE_API_KEY'); } - /** - * Load a document from an absolute path, as a string. - * - * @param string $filePath Path of the file. - * @param boolean $fixPDF Whether the PDF should be fixed or not. - * @return PathInput - */ - public function sourceFromPath(string $filePath, bool $fixPDF = false): PathInput - { - $input = new PathInput($filePath); - if ($fixPDF) { - $input->fixPDF(); - } - return $input; - } - - /** - * Load a document from a normal PHP file object. - * - * @param mixed $file File object as created from the file() function. - * @param boolean $fixPDF Whether the PDF should be fixed or not. - * @return FileInput - */ - public function sourceFromFile(mixed $file, bool $fixPDF = false): FileInput - { - $input = new FileInput($file); - if ($fixPDF) { - $input->fixPDF(); - } - return $input; - } - - /** - * Load a document from raw bytes. - * - * @param string $fileBytes File object in raw bytes. - * @param string $fileName File name, mandatory. - * @param boolean $fixPDF Whether the PDF should be fixed or not. - * @return BytesInput - */ - public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPDF = false): BytesInput - { - $input = new BytesInput($fileBytes, $fileName); - if ($fixPDF) { - $input->fixPDF(); - } - return $input; - } - - /** - * Load a document from a base64 encoded string. - * - * @param string $fileB64 File object in Base64. - * @param string $fileName File name, mandatory. - * @param boolean $fixPDF Whether the PDF should be fixed or not. - * @return Base64Input - */ - public function sourceFromB64String(string $fileB64, string $fileName, bool $fixPDF = false): Base64Input - { - $input = new Base64Input($fileB64, $fileName); - if ($fixPDF) { - $input->fixPDF(); - } - return $input; - } - - /** - * Load a document from an URL. - * - * @param string $url File URL. Must start with "https://". - * @return URLInputSource - */ - public function sourceFromUrl(string $url): URLInputSource - { - return new URLInputSource($url); - } - /** * Builds a custom endpoint. * - * @param string $endpointName URL of the endpoint. - * @param string $endpointOwner Name of the endpoint's owner. + * @param string $endpointName URL of the endpoint. + * @param string $endpointOwner Name of the endpoint's owner. * @param string $endpointVersion Version of the endpoint. - * @return Endpoint */ private function constructEndpoint( string $endpointName, 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); @@ -167,7 +87,6 @@ private function constructEndpoint( * Cleans the account name. * * @param string $accountName Name of the endpoint's owner. Replaced by self::DEFAULT_OWNER if absent. - * @return string */ private function cleanAccountName(string $accountName): string { @@ -184,7 +103,6 @@ private function cleanAccountName(string $accountName): string * Builds an off-the-shelf endpoint. * * @param string $product Name of the product's class. - * @return Endpoint * @throws MindeeApiException Throws if the product isn't recognized. */ private function constructOTSEndpoint(string $product): Endpoint @@ -196,10 +114,11 @@ 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') { + if ($endpointName === 'custom') { throw new MindeeApiException( 'Please create an endpoint manually before sending requests to a custom build.', ErrorCode::USER_INPUT_ERROR @@ -213,22 +132,21 @@ private function constructOTSEndpoint(string $product): Endpoint /** * Adds a custom endpoint, created using the Mindee API Builder. * - * @param string $endpointName URL of the endpoint. - * @param string $accountName Name of the endpoint's owner. - * @param string|null $version Version of the endpoint. - * @return Endpoint - * @throws MindeeClientException Throws if a custom endpoint name isn't provided. + * @param string $endpointName URL of the endpoint. + * @param string $accountName Name of the endpoint's owner. + * @param string|null $version Version of the endpoint. + * @throws MindeeV1ClientException Throws if a custom endpoint name isn't provided. */ public function createEndpoint(string $endpointName, string $accountName, ?string $version = null): Endpoint { - if (mb_strlen($endpointName, "UTF-8") == 0) { - throw new MindeeClientException( + if (mb_strlen($endpointName, "UTF-8") === 0) { + throw new MindeeV1ClientException( "Custom endpoint requires a valid 'endpoint_name'.", ErrorCode::USER_INPUT_ERROR ); } $accountName = $this->cleanAccountName($accountName); - if (!$version || strlen($version) < 1) { + if (empty($version)) { error_log("Notice: no version provided for a custom build, will attempt to poll version 1 by default."); $version = "1"; } @@ -238,11 +156,10 @@ public function createEndpoint(string $endpointName, string $accountName, ?strin /** * Cut the pages of a PDF following the detailed operations. * - * @param LocalInputSource $inputDoc Input PDF file. - * @param PageOptions $pageOptions Options to apply to the PDF file. - * @return void + * @param LocalInputSource $inputDoc Input PDF file. + * @param PageOptions $pageOptions Options to apply to the PDF file. */ - private function cutDocPages(LocalInputSource $inputDoc, PageOptions $pageOptions) + private function cutDocPages(LocalInputSource $inputDoc, PageOptions $pageOptions): void { $inputDoc->applyPageOptions($pageOptions); } @@ -250,11 +167,10 @@ private function cutDocPages(LocalInputSource $inputDoc, PageOptions $pageOption /** * Makes the request to retrieve an async document. * - * @param string $predictionType Name of the product's class. - * @param string $queueId ID of the queue. - * @param Endpoint $endpoint Endpoint to poll. - * @return AsyncPredictResponse - * @throws MindeeHttpException Throws if the API sent an error. + * @param string $predictionType Name of the product's class. + * @param string $queueId ID of the queue. + * @param Endpoint $endpoint Endpoint to poll. + * @throws MindeeV1HttpException Throws if the API sent an error. */ private function makeParseQueuedRequest( string $predictionType, @@ -263,7 +179,7 @@ private function makeParseQueuedRequest( ): AsyncPredictResponse { $queuedResponse = ResponseValidation::cleanRequestData($endpoint->documentQueueReqGet($queueId)); if (!ResponseValidation::isValidAsyncResponse($queuedResponse)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $endpoint->settings->endpointName, $queuedResponse ); @@ -274,11 +190,10 @@ private function makeParseQueuedRequest( /** * Makes the request to send a document to an asynchronous endpoint. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input file. - * @param PredictMethodOptions $options Prediction Options. - * @return AsyncPredictResponse - * @throws MindeeHttpException Throws if the API sent an error. + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions $options Prediction Options. + * @throws MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ private function makeEnqueueRequest( @@ -303,7 +218,7 @@ private function makeEnqueueRequest( ) ); if (!ResponseValidation::isValidAsyncResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $options->endpoint->settings->endpointName, $response ); @@ -314,14 +229,13 @@ private function makeEnqueueRequest( /** * Makes the request to send a document to a workflow. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input file. - * @param string $workflowId ID of the workflow. - * @param PredictMethodOptions $options Prediction Options. - * @return WorkflowResponse - * @throws MindeeHttpException Throws if the API sent an error. + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param string $workflowId ID of the workflow. + * @param PredictMethodOptions $options Prediction Options. + * @throws MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if the API sent an error, - * or if the prediction type isn't recognized or if a field can't be deserialized. + * or if the prediction type isn't recognized or if a field can't be deserialized. */ private function makeWorkflowExecutionRequest( string $predictionType, @@ -346,7 +260,7 @@ private function makeWorkflowExecutionRequest( $options->workflowOptions )); if (!ResponseValidation::isValidWorkflowResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( "workflows/$workflowId/executions", $response ); @@ -356,7 +270,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 ); } } @@ -364,11 +279,10 @@ private function makeWorkflowExecutionRequest( /** * Makes the request to send a document to a synchronous endpoint. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input file. - * @param PredictMethodOptions $options Prediction Options. - * @return PredictResponse - * @throws MindeeHttpException Throws if the API sent an error. + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions $options Prediction Options. + * @throws MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ private function makeParseRequest( @@ -391,7 +305,7 @@ private function makeParseRequest( $options, )); if (!ResponseValidation::isValidSyncResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $options->endpoint->settings->endpointName, $response ); @@ -403,11 +317,10 @@ private function makeParseRequest( /** * Call prediction API on the document and parse the results. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input file. - * @param PredictMethodOptions|null $options Prediction options. - * @param PageOptions|null $pageOptions Options to apply to the PDF file. - * @return PredictResponse + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions|null $options Prediction options. + * @param PageOptions|null $pageOptions Options to apply to the PDF file. */ public function parse( string $predictionType, @@ -415,13 +328,13 @@ 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()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } - $options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint( + $options->endpoint ??= $this->constructOTSEndpoint( $predictionType, ); @@ -431,12 +344,11 @@ public function parse( /** * Enqueues a document and automatically polls the response. Asynchronous calls only. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input file. - * @param PredictMethodOptions|null $options Prediction Options. - * @param PollingOptions|null $asyncOptions Async Options. Manages timers. - * @param PageOptions|null $pageOptions Options to apply to the PDF file. - * @return AsyncPredictResponse + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions|null $options Prediction Options. + * @param PollingOptions|null $asyncOptions Async Options. Manages timers. + * @param PageOptions|null $pageOptions Options to apply to the PDF file. * @throws MindeeApiException Throws if the document couldn't be retrieved in time. */ public function enqueueAndParse( @@ -446,14 +358,14 @@ 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(); } - $options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint( + $options->endpoint ??= $this->constructOTSEndpoint( $predictionType, ); @@ -470,7 +382,7 @@ public function enqueueAndParse( $pollResults = $this->parseQueued($predictionType, $enqueueResponse->job->id, $options->endpoint); while ($retryCounter < $asyncOptions->maxRetries) { - if ($pollResults->job->status == "completed") { + if ($pollResults->job->status === "completed") { break; } error_log("Polling server for parsing result with job id: " . $enqueueResponse->job->id); @@ -478,7 +390,7 @@ public function enqueueAndParse( $this->customSleep($asyncOptions->delaySec); $pollResults = $this->parseQueued($predictionType, $enqueueResponse->job->id, $options->endpoint); } - if ($pollResults->job->status != "completed") { + if ($pollResults->job->status !== "completed") { throw new MindeeApiException( "Couldn't retrieve document " . $enqueueResponse->job->id . " after $retryCounter tries.", ErrorCode::API_TIMEOUT, @@ -490,11 +402,10 @@ public function enqueueAndParse( /** * Enqueue a document to an asynchronous endpoint. * - * @param string $predictionType Name of the product's class. - * @param InputSource $inputDoc Input File. - * @param PredictMethodOptions|null $options Prediction Options. - * @param PageOptions|null $pageOptions Options to apply to the PDF file. - * @return AsyncPredictResponse + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input File. + * @param PredictMethodOptions|null $options Prediction Options. + * @param PageOptions|null $pageOptions Options to apply to the PDF file. */ public function enqueue( string $predictionType, @@ -502,13 +413,13 @@ 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()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } - $options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint( + $options->endpoint ??= $this->constructOTSEndpoint( $predictionType, ); return $this->makeEnqueueRequest($predictionType, $inputDoc, $options); @@ -517,25 +428,24 @@ public function enqueue( /** * Parses a queued document. * - * @param string $predictionType Name of the product's class. - * @param string $queueId ID of the queue. - * @param Endpoint|null $endpoint Endpoint to poll. - * @return AsyncPredictResponse + * @param string $predictionType Name of the product's class. + * @param string $queueId ID of the queue. + * @param Endpoint|null $endpoint Endpoint to poll. */ public function parseQueued( string $predictionType, string $queueId, ?Endpoint $endpoint = null ): AsyncPredictResponse { - $endpoint = $endpoint ?? $this->constructOTSEndpoint( + $endpoint ??= $this->constructOTSEndpoint( $predictionType, ); return $this->makeParseQueuedRequest($predictionType, $queueId, $endpoint); } /** - * @param string $predictionType Name of the product's class. - * @param LocalResponse $localResponse Local response to load. + * @param string $predictionType Name of the product's class. + * @param LocalResponse $localResponse Local response to load. * @return AsyncPredictResponse|PredictResponse A valid prediction response. * @throws MindeeException Throws if the loaded response isn't a valid prediction. */ @@ -552,7 +462,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 ); } } @@ -560,11 +471,10 @@ public function loadPrediction( /** * Sends a document to a workflow. * - * @param InputSource $inputDoc Input File. - * @param string $workflowId ID of the workflow. - * @param WorkflowOptions|null $options Prediction Options. - * @param PageOptions|null $pageOptions Options to apply to the PDF file. - * @return WorkflowResponse + * @param InputSource $inputDoc Input File. + * @param string $workflowId ID of the workflow. + * @param WorkflowOptions|null $options Prediction Options. + * @param PageOptions|null $pageOptions Options to apply to the PDF file. */ public function executeWorkflow( InputSource $inputDoc, @@ -572,10 +482,10 @@ 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()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } diff --git a/src/V1/ClientOptions/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php new file mode 100644 index 00000000..e6493c76 --- /dev/null +++ b/src/V1/ClientOptions/CommonOptions.php @@ -0,0 +1,27 @@ +fullText = $fullText; + return $this; + } +} diff --git a/src/Input/PredictMethodOptions.php b/src/V1/ClientOptions/PredictMethodOptions.php similarity index 82% rename from src/Input/PredictMethodOptions.php rename to src/V1/ClientOptions/PredictMethodOptions.php index 29623083..360215b4 100644 --- a/src/Input/PredictMethodOptions.php +++ b/src/V1/ClientOptions/PredictMethodOptions.php @@ -1,10 +1,12 @@ predictOptions = $predictOptions; return $this; @@ -64,7 +66,7 @@ public function setPredictOptions(PredictOptions $predictOptions): PredictMethod * @param WorkflowOptions $workflowOptions Prediction Options. * @return $this */ - public function setWorkflowOptions(WorkflowOptions $workflowOptions): PredictMethodOptions + public function setWorkflowOptions(WorkflowOptions $workflowOptions): self { $this->workflowOptions = $workflowOptions; return $this; @@ -74,7 +76,7 @@ public function setWorkflowOptions(WorkflowOptions $workflowOptions): PredictMet * @param PageOptions $pageOptions Page Options. * @return $this */ - public function setPageOptions(PageOptions $pageOptions): PredictMethodOptions + public function setPageOptions(PageOptions $pageOptions): self { $this->pageOptions = $pageOptions; return $this; @@ -84,7 +86,7 @@ public function setPageOptions(PageOptions $pageOptions): PredictMethodOptions * @param Endpoint $customEndpoint Endpoint. * @return $this */ - public function setEndpoint(Endpoint $customEndpoint): PredictMethodOptions + public function setEndpoint(Endpoint $customEndpoint): self { $this->endpoint = $customEndpoint; return $this; @@ -94,7 +96,7 @@ public function setEndpoint(Endpoint $customEndpoint): PredictMethodOptions * @param boolean $rag Whether to enable Retrieval-Augmented Generation. * @return $this */ - public function setRag(bool $rag): PredictMethodOptions + public function setRag(bool $rag): self { $this->rag = $rag; return $this; @@ -106,7 +108,7 @@ public function setRag(bool $rag): PredictMethodOptions * @param string $workflowId The unique workflow ID to be set. * @return $this */ - public function setWorkflowId(string $workflowId): PredictMethodOptions + public function setWorkflowId(string $workflowId): self { $this->workflowId = $workflowId; return $this; diff --git a/src/V1/ClientOptions/PredictOptions.php b/src/V1/ClientOptions/PredictOptions.php new file mode 100644 index 00000000..26276199 --- /dev/null +++ b/src/V1/ClientOptions/PredictOptions.php @@ -0,0 +1,48 @@ +includeWords = $includeWords; + return $this; + } + + /** + * @param boolean $cropper Whether to include the Cropper. + * @return $this + */ + public function setCropper(bool $cropper): self + { + $this->cropper = $cropper; + return $this; + } +} diff --git a/src/V1/ClientOptions/WorkflowOptions.php b/src/V1/ClientOptions/WorkflowOptions.php new file mode 100644 index 00000000..45d70e63 --- /dev/null +++ b/src/V1/ClientOptions/WorkflowOptions.php @@ -0,0 +1,28 @@ +>|null API details field as sent by the server. */ - public $apiDetails; + public string|array|null $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 string|array|null $apiMessage; /** - * @param array $httpError Array containing the error data. - * @param string $url Remote URL the error was found on. - * @param integer $code Error code. + * @param array> $httpError Array containing the error data. + * @param string $url Remote URL the error was found on. + * @param integer $statusCode Error code. */ - public function __construct(array $httpError, string $url, int $code) + public function __construct(array $httpError, string $url, public int $statusCode) { - $this->statusCode = $code; if (array_key_exists('code', $httpError)) { $this->apiCode = $httpError['code']; } else { @@ -57,7 +61,7 @@ public function __construct(array $httpError, string $url, int $code) if (is_array($this->apiDetails)) { $details = "\n" . json_encode($this->apiDetails, JSON_PRETTY_PRINT) . "\n"; } else { - $details = strval($this->apiDetails); + $details = (string) ($this->apiDetails); } parent::__construct("$url $this->statusCode HTTP error: $details - $this->apiMessage"); } @@ -65,11 +69,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(array|string|null $response): array { if (is_string($response)) { if (str_contains($response, 'Maximum pdf pages')) { @@ -113,13 +117,13 @@ public static function createErrorObj($response): array return $errorArray; } if ( - is_array($response) && - array_key_exists('api_request', $response) && - array_key_exists('error', $response['api_request']) + is_array($response) + && array_key_exists('api_request', $response) + && array_key_exists('error', $response['api_request']) ) { return $response['api_request']['error']; } - if (!$response) { + if (!isset($response)) { throw new MindeeException( "Request to the API failed.", ErrorCode::API_REQUEST_FAILED @@ -132,30 +136,29 @@ public static function createErrorObj($response): array } /** - * @param string $url Remote URL the error was found on. - * @param array|string|boolean $response Raw server response. - * @return MindeeHttpException + * @param string $url Remote URL the error was found on. + * @param array|string|null $response Raw server response. */ - public static function handleError(string $url, $response): MindeeHttpException + public static function handleError(string $url, array|string|null $response): self { if (is_array($response)) { $dataResponse = $response['data'] ?? ["data" => null]; } else { $dataResponse = ["data" => null]; } - $errorObj = MindeeHttpException::createErrorObj($dataResponse); + $errorObj = self::createErrorObj($dataResponse); if (array_key_exists("code", $response) && is_numeric($response['code'])) { - $code = intval($response['code']); + $code = (int) ($response['code']); } else { $code = 500; } if ($code >= 400 && $code <= 499) { - return new MindeeHttpClientException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } if ($code >= 500 && $code <= 599) { - return new MindeeHttpClientException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } - return new MindeeHttpException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } } diff --git a/src/Http/BaseApi.php b/src/V1/Http/BaseApi.php similarity index 73% rename from src/Http/BaseApi.php rename to src/V1/Http/BaseApi.php index a9bdad22..a16a91c8 100644 --- a/src/Http/BaseApi.php +++ b/src/V1/Http/BaseApi.php @@ -1,10 +1,12 @@ "macos", + default => strtolower(PHP_OS_FAMILY), + }; return 'mindee-api-php@v' . VERSION . ' php-v' . PHP_VERSION . ' ' . $os; } @@ -59,7 +60,7 @@ abstract class BaseApi /** * @var string|null API key. */ - public ?string $apiKey; + public ?string $apiKey = null; /** * @var integer Timeout for the request, in ms. */ @@ -77,7 +78,6 @@ abstract class BaseApi * Sets the base url. * * @param string $value Value for the base Url. - * @return void */ protected function setBaseUrl(string $value): void { @@ -87,27 +87,25 @@ protected function setBaseUrl(string $value): void /** * Sets the default timeout. * - * @param string $value Value for the CURL timeout. - * @return void + * @param integer $value Value for the CURL timeout. */ - protected function setTimeout(string $value) + protected function setTimeout(int $value): void { $this->requestTimeout = $value; } /** - * Sets values from environment, if needed. + * Sets values from the environment, if needed. * - * @return void */ - protected function setFromEnv() + protected function setFromEnv(): void { $envVars = [ - BASE_URL_ENV_NAME => [$this, 'setBaseUrl'], - REQUEST_TIMEOUT_ENV_NAME => [$this, 'setTimeout'], + BASE_URL_ENV_NAME => $this->setBaseUrl(...), + REQUEST_TIMEOUT_ENV_NAME => $this->setTimeout(...), ]; foreach ($envVars as $key => $func) { - $envVal = getenv($key) ? getenv($key) : ''; + $envVal = getenv($key) ?: ''; if ($envVal) { call_user_func($func, $envVal); error_log('Value ' . $key . ' was set from env.'); @@ -119,9 +117,8 @@ protected function setFromEnv() * Sets the API key. * * @param string|null $apiKey Optional API key. - * @return void */ - protected function setApiKey(?string $apiKey = null) + protected function setAPIKey(?string $apiKey = null): void { $envVal = !getenv(API_KEY_ENV_NAME) ? '' : getenv(API_KEY_ENV_NAME); if (!$apiKey) { @@ -138,7 +135,7 @@ protected function setApiKey(?string $apiKey = null) public function __construct( ?string $apiKey ) { - $this->setApiKey($apiKey); + $this->setAPIKey($apiKey); $this->baseUrl = BASE_URL_DEFAULT; $this->requestTimeout = TIMEOUT_DEFAULT; $this->setFromEnv(); diff --git a/src/Http/BaseEndpoint.php b/src/V1/Http/BaseEndpoint.php similarity index 76% rename from src/Http/BaseEndpoint.php rename to src/V1/Http/BaseEndpoint.php index 06cdcaff..da2b61d6 100644 --- a/src/Http/BaseEndpoint.php +++ b/src/V1/Http/BaseEndpoint.php @@ -1,30 +1,26 @@ settings = $settings; - } + public function __construct(public MindeeApi|MindeeWorkflowApi $settings) {} /** - * Starts a CURL session, using GET. + * Starts a CURL session using GET. * * @param string $queueId ID of the queue to poll. - * @return array + * @return array{data: string|bool, code: int} */ protected function initCurlSessionGet(string $queueId): array { @@ -55,20 +51,20 @@ protected function initCurlSessionGet(string $queueId): array } /** - * @param resource $ch Curl Channel. - * @param string $suffix Optional suffix for the url call. - * @param array|null $postFields Post fields. + * @param CurlHandle $ch Curl Channel. + * @param string $suffix Optional suffix for the url call. + * @param array|boolean>|null $postFields Post fields. * @param string|null $workflowId Optional ID of the workflow. - * @return array + * @return array{data: string|bool, code: int} Final response. */ public function setFinalCurlOpts( - $ch, + CurlHandle $ch, string $suffix, ?array $postFields, ?string $workflowId = null ): array { if (isset($workflowId)) { - $url = $this->settings->baseUrl . "/workflows/" . $workflowId . $suffix; + $url = $this->settings->baseUrl . "/v1/workflows/" . $workflowId . $suffix; } else { $url = $this->settings->urlRoot . $suffix; } diff --git a/src/Http/Endpoint.php b/src/V1/Http/Endpoint.php similarity index 66% rename from src/Http/Endpoint.php rename to src/V1/Http/Endpoint.php index d4a04d82..94a87c6e 100644 --- a/src/Http/Endpoint.php +++ b/src/V1/Http/Endpoint.php @@ -1,11 +1,14 @@ urlName = $urlName; - $this->owner = $owner; - $this->version = $version; } /** * Retrieves a document from its queue ID. * * @param string $queueId ID of the queue to poll. - * @return array + * @return array{data: string|bool, code: int} Final response. */ public function documentQueueReqGet(string $queueId): array { @@ -57,9 +44,9 @@ public function documentQueueReqGet(string $queueId): array /** * Sends a document for asynchronous enqueuing. * - * @param InputSource $fileCurl File to upload. - * @param PredictMethodOptions $options Prediction Options. - * @return array + * @param InputSource $fileCurl File to upload. + * @param PredictMethodOptions $options Prediction Options. + * @return array{data: string|bool, code: int} Final response. */ public function predictRequestPost( InputSource $fileCurl, @@ -71,9 +58,9 @@ public function predictRequestPost( /** * Sends a document for synchronous enqueuing. * - * @param InputSource $fileCurl File to upload. - * @param PredictMethodOptions $options Prediction Options. - * @return array + * @param InputSource $fileCurl File to upload. + * @param PredictMethodOptions $options Prediction Options. + * @return array{data: string|bool, code: int} Final response. */ public function predictAsyncRequestPost( InputSource $fileCurl, @@ -88,12 +75,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 + * @param InputSource $inputSource File to upload. + * @param PredictMethodOptions $options Prediction Options. + * @param boolean $async Whether to use the async endpoint. + * @return array{data: string|bool, code: int} Final response. + * @throws MindeeException Throws if the CURL session couldn't be initialized. */ private function initCurlSessionPost( InputSource $inputSource, @@ -115,7 +103,7 @@ private function initCurlSessionPost( curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); $postFields = null; - if ($inputSource instanceof URLInputSource) { + if ($inputSource instanceof UrlInputSource) { $postFields = ['document' => $inputSource->url]; } elseif ($inputSource instanceof LocalInputSource) { $inputSource->checkNeedsFix(); @@ -140,6 +128,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/Http/MindeeApi.php b/src/V1/Http/MindeeApi.php similarity index 67% rename from src/Http/MindeeApi.php rename to src/V1/Http/MindeeApi.php index bf206b66..57983b22 100644 --- a/src/Http/MindeeApi.php +++ b/src/V1/Http/MindeeApi.php @@ -1,14 +1,16 @@ apiKey || strlen($this->apiKey) == 0) { + 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 " . - API_KEY_ENV_NAME . ' environment variable.', + "Missing API key for '$endpointName v$version' (belonging to $accountName)," + . " check your Client configuration.You can set this using the " + . API_KEY_ENV_NAME . ' environment variable.', ErrorCode::USER_INPUT_ERROR ); } @@ -56,6 +58,6 @@ public function __construct( $this->urlRoot = rtrim( $this->baseUrl, "/" - ) . "/products/$this->accountName/$this->endpointName/v$this->version"; + ) . "/v1/products/$this->accountName/$this->endpointName/v$this->version"; } } diff --git a/src/Http/MindeeWorkflowApi.php b/src/V1/Http/MindeeWorkflowApi.php similarity index 58% rename from src/Http/MindeeWorkflowApi.php rename to src/V1/Http/MindeeWorkflowApi.php index 0e0a6f2d..d74f271e 100644 --- a/src/Http/MindeeWorkflowApi.php +++ b/src/V1/Http/MindeeWorkflowApi.php @@ -1,10 +1,12 @@ apiKey || strlen($this->apiKey) == 0) { + 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.', + "Missing API key. Please check your Client configuration.You can set this using the " + . API_KEY_ENV_NAME . ' environment variable.', ErrorCode::USER_INPUT_ERROR ); } - $this->workflowId = $workflowId; $this->urlRoot = rtrim( $this->baseUrl, "/" - ) . "/workflows/$this->workflowId/executions"; + ) . "/v1/workflows/$this->workflowId/executions"; } } diff --git a/src/Http/ResponseValidation.php b/src/V1/Http/ResponseValidation.php similarity index 74% rename from src/Http/ResponseValidation.php rename to src/V1/Http/ResponseValidation.php index 74d3518d..7a3c585e 100644 --- a/src/Http/ResponseValidation.php +++ b/src/V1/Http/ResponseValidation.php @@ -1,10 +1,15 @@ > $response A response object. * @return boolean */ public static function isValidSyncResponse(array $response): bool @@ -24,9 +29,9 @@ public static function isValidSyncResponse(array $response): bool } $statusCode = $response['code']; return !( - is_nan($statusCode) || - intval($statusCode) < 200 || - intval($statusCode) > 302 + is_nan($statusCode) + || (int) $statusCode < 200 + || (int) $statusCode > 302 ); } @@ -35,12 +40,12 @@ 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 { - if (!ResponseValidation::isValidSyncResponse($response)) { + if (!self::isValidSyncResponse($response)) { return false; } if (isset($response["code"])) { @@ -60,12 +65,12 @@ 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 { - if (!ResponseValidation::isValidSyncResponse($response)) { + if (!self::isValidSyncResponse($response)) { return false; } if (isset($response["code"])) { @@ -84,8 +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. - * @return array + * @param array> $response An endpoint response array. + * @return array> A cleaned response array. */ public static function cleanRequestData(array $response): array { @@ -97,10 +102,10 @@ public static function cleanRequestData(array $response): array } if (isset($response["data"])) { if ( - isset($response["data"]["api_request"]["status_code"]) && - intval($response["data"]["api_request"]["status_code"]) > 399 + isset($response["data"]["api_request"]["status_code"]) + && (int) ($response["data"]["api_request"]["status_code"]) > 399 ) { - $response["code"] = intval($response["data"]["api_request"]["status_code"]); + $response["code"] = (int) ($response["data"]["api_request"]["status_code"]); } if (isset($response["data"]["job"]["error"]) && count($response["data"]["job"]["error"]) > 0) { $response["code"] = 500; diff --git a/src/Http/WorkflowEndpoint.php b/src/V1/Http/WorkflowEndpoint.php similarity index 81% rename from src/Http/WorkflowEndpoint.php rename to src/V1/Http/WorkflowEndpoint.php index 219a70e1..cb8120fa 100644 --- a/src/Http/WorkflowEndpoint.php +++ b/src/V1/Http/WorkflowEndpoint.php @@ -1,11 +1,14 @@ settings->requestTimeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); - if ($fileCurl instanceof URLInputSource) { + if ($fileCurl instanceof UrlInputSource) { $postFields = ['document' => $fileCurl->url]; } elseif ($fileCurl instanceof LocalInputSource) { $postFields = ['document' => $fileCurl->fileObject]; @@ -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/Image/ImageExtractor.php b/src/V1/Image/ImageExtractor.php index 72656282..9a71af84 100644 --- a/src/V1/Image/ImageExtractor.php +++ b/src/V1/Image/ImageExtractor.php @@ -1,12 +1,105 @@ > $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 + */ + public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array + { + $outputName ??= $this->filename; + return $this->extractFromPage($fields, $pageIndex, $outputName); + } + + /** + * Extracts a single image from a Position field. + * + * @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. + * @param string $format The output format. + * + * @return null|ExtractedImage The extracted image, or null if the field does not have valid position data. + * + * @throws MindeeGeometryException Throws if a field does not contain positional data. + */ + public function extractImage( + BaseField $field, + int $pageIndex, + int $index, + string $filename, + string $format + ): ?ExtractedImage { + $polygon = null; + + if (!empty($field->polygon)) { + $polygon = $field->polygon; + } elseif (!empty($field->boundingBox)) { + $polygon = $field->boundingBox; + } elseif (!empty($field->quadrangle)) { + $polygon = $field->quadrangle; + } elseif (!empty($field->rectangle)) { + $polygon = $field->rectangle; + } + + if (null === $polygon) { + throw new MindeeGeometryException( + 'Provided field has no valid position data.', + ErrorCode::GEOMETRIC_OPERATION_FAILED + ); + } + + return $this->extractPolygonFromPage($polygon, $pageIndex, $index, $filename, $format); + } + + /** + * Extracts images from a page. + * + * @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 + */ + protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array + { + $extractedImages = []; + + $i = 0; + foreach ($fields as $field) { + $filename = sprintf('%s_page%d-%d.%s', $outputName, $pageIndex, $i, $format); + $extractedImage = $this->extractImage($field, $pageIndex, $i, $filename, $format); + if (null !== $extractedImage) { + $extractedImages[] = $extractedImage; + } + ++$i; + } + + return $extractedImages; + } + } diff --git a/src/V1/Parsing/Common/ApiRequest.php b/src/V1/Parsing/Common/ApiRequest.php new file mode 100644 index 00000000..de86e822 --- /dev/null +++ b/src/V1/Parsing/Common/ApiRequest.php @@ -0,0 +1,44 @@ +>|string|null Error content, if any. + */ + public array|string|null $error; + /** + * @var array>|string|null Information on the target resources + */ + public array|string|null $resources; + /** + * @var array>|string Status as sent back by the API. + */ + public array|string|null $status; + /** + * @var integer HTTP status code. + */ + public int $statusCode; + /** + * @var string|null URL of the request. + */ + public ?string $url; + + /** + * @param array> $rawResponse Raw HTTP response. + */ + public function __construct(array $rawResponse) + { + $this->url = $rawResponse['url']; + $this->error = $rawResponse['error']; + $this->resources = $rawResponse['resources']; + $this->status = $rawResponse['status']; + $this->statusCode = $rawResponse['status_code']; + } +} diff --git a/src/Parsing/Common/ApiResponse.php b/src/V1/Parsing/Common/ApiResponse.php similarity index 58% rename from src/Parsing/Common/ApiResponse.php rename to src/V1/Parsing/Common/ApiResponse.php index 96d2be1a..f09cb7b5 100644 --- a/src/Parsing/Common/ApiResponse.php +++ b/src/V1/Parsing/Common/ApiResponse.php @@ -1,6 +1,8 @@ > Raw http result. Used for debugging purposes. */ - private array $rawHttp; + private readonly array $rawHttp; /** - * @param array $rawResponse Raw prediction array. + * @param array> $rawResponse Raw prediction array. */ public function __construct(array $rawResponse) { diff --git a/src/Parsing/Common/AsyncPredictResponse.php b/src/V1/Parsing/Common/AsyncPredictResponse.php similarity index 62% rename from src/Parsing/Common/AsyncPredictResponse.php rename to src/V1/Parsing/Common/AsyncPredictResponse.php index 8670f814..68577d52 100644 --- a/src/Parsing/Common/AsyncPredictResponse.php +++ b/src/V1/Parsing/Common/AsyncPredictResponse.php @@ -1,6 +1,10 @@ > $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/Parsing/Common/Document.php b/src/V1/Parsing/Common/Document.php similarity index 60% rename from src/Parsing/Common/Document.php rename to src/V1/Parsing/Common/Document.php index 991acf4f..0a5075fb 100644 --- a/src/Parsing/Common/Document.php +++ b/src/V1/Parsing/Common/Document.php @@ -1,46 +1,53 @@ > $rawResponse Raw HTTP response. + * @throws MindeeApiException Throws if the prediction type isn't recognized. */ public function __construct(string $predictionType, array $rawResponse) { @@ -48,9 +55,9 @@ public function __construct(string $predictionType, array $rawResponse) $this->nPages = $rawResponse['n_pages']; $this->filename = $rawResponse['name']; try { - $reflection = new \ReflectionClass($predictionType); + $reflection = new ReflectionClass($predictionType); $this->inference = $reflection->newInstance($rawResponse['inference']); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new MindeeApiException( "Unable to create custom product " . $predictionType, ErrorCode::INTERNAL_LIBRARY_ERROR, @@ -83,28 +90,23 @@ public function __toString(): string /** * Injects the results from pages' "full_text_ocr", if present. * - * @param array $rawResponse Raw HTTP response. - * @return void + * @param array> $rawResponse Raw HTTP response. */ private function injectFullTextOcr(array $rawResponse): void { $pages = $rawResponse['inference']['pages'] ?? []; if ( - empty($pages) || - !isset($pages[0]['extras']) || - !isset($pages[0]['extras']['full_text_ocr']) + empty($pages) + || !isset($pages[0]['extras']) + || !isset($pages[0]['extras']['full_text_ocr']) ) { return; } $fullTextContent = implode("\n", array_map( - function ($page) { - return $page['extras']['full_text_ocr']['content'] ?? ''; - }, - array_filter($pages, function ($page) { - return isset($page['extras']['full_text_ocr']); - }) + static fn($page) => $page['extras']['full_text_ocr']['content'] ?? '', + array_filter($pages, static fn($page) => isset($page['extras']['full_text_ocr'])) )); $artificialTextObj = ['content' => $fullTextContent]; diff --git a/src/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php similarity index 75% rename from src/Parsing/Common/Execution.php rename to src/V1/Parsing/Common/Execution.php index 7fb83ab8..ec0e24e2 100644 --- a/src/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -1,41 +1,40 @@ > $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) @@ -117,27 +108,26 @@ public function __construct(string $predictionType, array $rawResponse) } } $this->priority = $rawResponse['priority'] ?? null; - $this->reviewedAt = isset($rawResponse['reviewed_at']) ? - new DateTimeImmutable($rawResponse['reviewed_at']) : null; - $this->availableAt = isset($rawResponse['available_at']) ? - new DateTimeImmutable($rawResponse['available_at']) : null; - $this->reviewedPrediction = isset($rawResponse['reviewed_prediction']) ? - new GeneratedV1Document($rawResponse['reviewed_prediction']) : null; + $this->reviewedAt = isset($rawResponse['reviewed_at']) + ? new DateTimeImmutable($rawResponse['reviewed_at']) : null; + $this->availableAt = isset($rawResponse['available_at']) + ? new DateTimeImmutable($rawResponse['available_at']) : null; + $this->reviewedPrediction = isset($rawResponse['reviewed_prediction']) + ? new GeneratedV1Document($rawResponse['reviewed_prediction']) : null; $this->status = $rawResponse['status'] ?? null; $this->type = $rawResponse['type'] ?? null; - $this->uploadedAt = isset($rawResponse['uploaded_at']) ? - new DateTimeImmutable($rawResponse['uploaded_at']) : null; + $this->uploadedAt = isset($rawResponse['uploaded_at']) + ? new DateTimeImmutable($rawResponse['uploaded_at']) : null; $this->workflowId = $rawResponse['workflow_id'] ?? null; } /** - * @return string */ public function __toString(): string { $objAsArray = get_object_vars($this); ksort($objAsArray); - return json_encode($objAsArray, JSON_PRETTY_PRINT); + return (string) json_encode($objAsArray, JSON_PRETTY_PRINT); } } diff --git a/src/Parsing/Common/ExecutionFile.php b/src/V1/Parsing/Common/ExecutionFile.php similarity index 72% rename from src/Parsing/Common/ExecutionFile.php rename to src/V1/Parsing/Common/ExecutionFile.php index 6f675660..35eddf20 100644 --- a/src/Parsing/Common/ExecutionFile.php +++ b/src/V1/Parsing/Common/ExecutionFile.php @@ -1,6 +1,8 @@ > $rawResponse Raw HTTP response. */ public function __construct(array $rawResponse) { diff --git a/src/Parsing/Common/Extras/CropperExtra.php b/src/V1/Parsing/Common/Extras/CropperExtra.php similarity index 60% rename from src/Parsing/Common/Extras/CropperExtra.php rename to src/V1/Parsing/Common/Extras/CropperExtra.php index 38a7de20..112bf18b 100644 --- a/src/Parsing/Common/Extras/CropperExtra.php +++ b/src/V1/Parsing/Common/Extras/CropperExtra.php @@ -1,22 +1,27 @@ List of all croppings coordiantes. */ public array $croppings; /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -35,7 +40,7 @@ public function __toString(): string { $croppingsStr = []; foreach ($this->croppings as $cropping) { - $croppingsStr[] = strval($cropping); + $croppingsStr[] = (string) $cropping; } return implode("\n ", $croppingsStr); } diff --git a/src/Parsing/Common/Extras/Extras.php b/src/V1/Parsing/Common/Extras/Extras.php similarity index 55% rename from src/Parsing/Common/Extras/Extras.php rename to src/V1/Parsing/Common/Extras/Extras.php index 1fdccbec..4e51521e 100644 --- a/src/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -1,22 +1,26 @@ > Other extras. */ private array $data; @@ -32,26 +36,25 @@ class Extras * Sets a field. * * @param string $varName Name of the field to set. - * @param mixed $value Value to set the field with. - * @return void + * @param integer|float|string|boolean|null|array $value Value to set the field with. */ - public function __set(string $varName, mixed $value) + public function __set(string $varName, int|float|string|bool|array|null $value): void { $this->data[$varName] = $value; } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { foreach ($rawPrediction as $key => $extra) { - if ($key == 'cropper' && isset($rawPrediction['cropper'])) { + if ($key === 'cropper' && isset($rawPrediction['cropper'])) { $this->cropper = new CropperExtra($rawPrediction['cropper']); - } elseif ($key == 'full_text_ocr' && isset($rawPrediction['full_text_ocr'])) { + } 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->rag = new RAGExtra($rawPrediction['rag']); + } elseif ($key === 'rag' && isset($rawPrediction['rag'])) { + $this->rag = new RagExtra($rawPrediction['rag']); } else { $this->__set($key, $extra); } @@ -62,25 +65,23 @@ 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. - * @return void + * @param array> $rawPrediction Raw HTTP response. */ - public function addArtificialExtra(array $rawPrediction) + public function addArtificialExtra(array $rawPrediction): void { - if (isset($rawPrediction["full_text_ocr"]) && !isEmpty($rawPrediction['full_text_ocr'])) { + if (!empty($rawPrediction['full_text_ocr'])) { $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); } } /** - * @return string */ - public function __toString() + public function __toString(): string { $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/Parsing/Common/Extras/FullTextOcrExtra.php b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php similarity index 66% rename from src/Parsing/Common/Extras/FullTextOcrExtra.php rename to src/V1/Parsing/Common/Extras/FullTextOcrExtra.php index 1cf40065..05635db3 100644 --- a/src/Parsing/Common/Extras/FullTextOcrExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php @@ -1,13 +1,15 @@ > $rawPrediction Raw HTTP response. */ public function __construct(array $rawPrediction) { @@ -34,9 +36,8 @@ public function __construct(array $rawPrediction) } /** - * @return string */ - public function __toString() + public function __toString(): string { return $this->content ?? ''; } diff --git a/src/Parsing/Common/Extras/RAGExtra.php b/src/V1/Parsing/Common/Extras/RagExtra.php similarity index 71% rename from src/Parsing/Common/Extras/RAGExtra.php rename to src/V1/Parsing/Common/Extras/RagExtra.php index 8e79dd40..351ea48b 100644 --- a/src/Parsing/Common/Extras/RAGExtra.php +++ b/src/V1/Parsing/Common/Extras/RagExtra.php @@ -1,11 +1,15 @@ > $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/Parsing/Common/Inference.php b/src/V1/Parsing/Common/Inference.php similarity index 54% rename from src/Parsing/Common/Inference.php rename to src/V1/Parsing/Common/Inference.php index 9d8b5957..ca2713c9 100644 --- a/src/Parsing/Common/Inference.php +++ b/src/V1/Parsing/Common/Inference.php @@ -1,16 +1,22 @@ A document's pages. */ public array $pages; /** @@ -38,27 +44,27 @@ abstract class Inference */ public ?int $pageId; /** - * @var \Mindee\Parsing\Common\Extras\Extras|null Potential Extras fields sent back along with the prediction. + * @var Extras|null Potential Extras fields sent back along with the prediction. */ public ?Extras $extras; /** - * @param array $rawInference Raw inference array. - * @param integer|null $pageId Page number for multi pages document. + * @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']); } } @@ -73,7 +79,7 @@ public function __toString(): string if (count($this->pages)) { $pagesStr = "\nPage Predictions\n================\n\n" . implode( "\n", - array_map(fn ($page) => strval($page), $this->pages) + array_map(static fn($page) => (string) $page, $this->pages) ); } diff --git a/src/Parsing/Common/Job.php b/src/V1/Parsing/Common/Job.php similarity index 59% rename from src/Parsing/Common/Job.php rename to src/V1/Parsing/Common/Job.php index 3bc4e949..e21f711f 100644 --- a/src/Parsing/Common/Job.php +++ b/src/V1/Parsing/Common/Job.php @@ -1,17 +1,23 @@ >|null Information about an error that occurred during the job processing. */ - public ?array $error; + public ?array $error = null; /** - * @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 ); } } $this->id = $rawResponse['id']; $this->status = $rawResponse['status']; if ( - array_key_exists('available_at', $rawResponse) && - $rawResponse['available_at'] !== null && strtotime($rawResponse['available_at']) + array_key_exists('available_at', $rawResponse) + && $rawResponse['available_at'] !== null && strtotime($rawResponse['available_at']) ) { try { $this->availableAt = new DateTimeImmutable($rawResponse['available_at']); - } catch (\Exception $e) { + } catch (Exception $e) { try { - $this->availableAt = new DateTimeImmutable(strtotime($rawResponse['available_at'])); - } catch (\Exception $e2) { + $timestamp = strtotime($rawResponse['available_at']); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->availableAt = new DateTimeImmutable('@' . $timestamp); + } catch (Exception) { throw new MindeeApiException( "Could not create date from " . $rawResponse['available_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, @@ -76,8 +90,8 @@ public function __construct(array $rawResponse) ); } } - $ts1 = (int)$this->availableAt->format('Uv'); - $ts2 = (int)$this->issuedAt->format('Uv'); + $ts1 = (int) $this->availableAt->format('Uv'); + $ts2 = (int) $this->issuedAt->format('Uv'); $this->millisecsTaken = $ts2 - $ts1; } else { $this->availableAt = null; @@ -86,13 +100,12 @@ public function __construct(array $rawResponse) } /** - * @return string */ public function __toString(): string { $objAsJson = get_object_vars($this); ksort($objAsJson); - return json_encode($objAsJson, JSON_PRETTY_PRINT); + return (string) json_encode($objAsJson, JSON_PRETTY_PRINT); } } diff --git a/src/Parsing/Common/Ocr/MVisionV1.php b/src/V1/Parsing/Common/Ocr/MVisionV1.php similarity index 61% rename from src/Parsing/Common/Ocr/MVisionV1.php rename to src/V1/Parsing/Common/Ocr/MVisionV1.php index 1d1c357e..95f23d62 100644 --- a/src/Parsing/Common/Ocr/MVisionV1.php +++ b/src/V1/Parsing/Common/Ocr/MVisionV1.php @@ -1,19 +1,23 @@ List of pages. */ public array $pages; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -24,13 +28,12 @@ public function __construct(array $rawPrediction) } /** - * @return string */ public function __toString(): string { $pagesStr = []; foreach ($this->pages as $page) { - $pagesStr[] = strval($page); + $pagesStr[] = (string) $page; } return implode("\n", $pagesStr); } diff --git a/src/Parsing/Common/Ocr/Ocr.php b/src/V1/Parsing/Common/Ocr/Ocr.php similarity index 58% rename from src/Parsing/Common/Ocr/Ocr.php rename to src/V1/Parsing/Common/Ocr/Ocr.php index 6cefb57d..c0b5bbfc 100644 --- a/src/Parsing/Common/Ocr/Ocr.php +++ b/src/V1/Parsing/Common/Ocr/Ocr.php @@ -1,19 +1,26 @@ > $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -21,18 +28,17 @@ public function __construct(array $rawPrediction) } /** - * @return string */ public function __toString(): string { - return strval($this->mvisionV1); + return (string) ($this->mvisionV1); } /** - * Finds all lines matching the given regex in the OCR data, indexed by their page. + * 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 { @@ -40,7 +46,7 @@ public function findLineByRegex(string $regex): array for ($i = 0; $i < count($this->mvisionV1->pages); $i++) { $page = $this->mvisionV1->pages[$i]; foreach ($page->getAllLines() as $line) { - if (preg_match($regex, strval($line))) { + if (preg_match($regex, (string) $line)) { if (!array_key_exists($i, $matches)) { $matches[$i] = []; } diff --git a/src/Parsing/Common/Ocr/OcrLine.php b/src/V1/Parsing/Common/Ocr/OcrLine.php similarity index 57% rename from src/Parsing/Common/Ocr/OcrLine.php rename to src/V1/Parsing/Common/Ocr/OcrLine.php index 5626de3d..c86672da 100644 --- a/src/Parsing/Common/Ocr/OcrLine.php +++ b/src/V1/Parsing/Common/Ocr/OcrLine.php @@ -1,42 +1,38 @@ $words Words to insert in the line. */ - public function __construct(array $words = []) - { - $this->words = $words; - } + public function __construct(private array $words = []) {} /** * Sort the words on the line from left to right. * - * @return void */ - public function sortOnX() + public function sortOnX(): void { - usort($this->words, "Mindee\\Parsing\\Common\\Ocr\\OcrPage::getMinMaxX"); + usort($this->words, OcrPage::getMinMaxX(...)); } /** * Appends a word to the line. * - * @param \Mindee\Parsing\Common\Ocr\OcrWord $word Word to add. - * @return void + * @param OcrWord $word Word to add. */ - public function add(OcrWord $word) + public function add(OcrWord $word): void { $this->words[] = $word; } diff --git a/src/Parsing/Common/Ocr/OcrPage.php b/src/V1/Parsing/Common/Ocr/OcrPage.php similarity index 77% rename from src/Parsing/Common/Ocr/OcrPage.php rename to src/V1/Parsing/Common/Ocr/OcrPage.php index 8cee1982..37a8478a 100644 --- a/src/Parsing/Common/Ocr/OcrPage.php +++ b/src/V1/Parsing/Common/Ocr/OcrPage.php @@ -1,18 +1,25 @@ List of all words. */ private array $allWords; /** - * @var array List of lines. + * @var array List of lines. */ private array $lines; @@ -20,7 +27,7 @@ class OcrPage * Checks whether the words are on the same line. * * @param OcrWord $currentWord Reference word to compare. - * @param OcrWord $nextWord Next word to compare. + * @param OcrWord $nextWord Next word to compare. * @return boolean */ private static function areWordsOnSameLine(OcrWord $currentWord, OcrWord $nextWord): bool @@ -41,10 +48,7 @@ public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int { $word1X = $word1->polygon->getMinMaxX()->getMin(); $word2X = $word2->polygon->getMinMaxX()->getMin(); - if ($word1X == $word2X) { - return 0; - } - return $word1X < $word2X ? -1 : 1; + return $word1X <=> $word2X; } /** @@ -58,34 +62,30 @@ public static function getMinMaxY(OcrWord $word1, OcrWord $word2): int { $word1Y = $word1->polygon->getMinMaxY()->getMin(); $word2Y = $word2->polygon->getMinMaxY()->getMin(); - if ($word1Y == $word2Y) { - return 0; - } - return $word1Y < $word2Y ? -1 : 1; + return $word1Y <=> $word2Y; } /** * Puts all words on the page into an array of lines. - * - * @return array + * @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)) { - if ($current == null) { + if (!in_array($idx, $indexes, true)) { + if (null === $current) { $current = $word; $indexes[] = $idx; $line = new OcrLine(); $line->add($word); } else { - if ($this->areWordsOnSameLine($current, $word)) { + if (self::areWordsOnSameLine($current, $word)) { $line->add($word); $indexes[] = $idx; } @@ -103,8 +103,7 @@ private function toLines(): array /** * Retrieves all lines on the page. - * - * @return array + * @return array */ public function getAllLines(): array { @@ -116,8 +115,7 @@ public function getAllLines(): array /** * Retrieves all words on the page. - * - * @return array + * @return array */ public function getAllWords(): array { @@ -125,7 +123,7 @@ public function getAllWords(): array } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -133,7 +131,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['all_words'] as $wordPrediction) { $this->allWords[] = new OcrWord($wordPrediction); } - usort($this->allWords, "self::getMinMaxY"); + usort($this->allWords, self::getMinMaxY(...)); } /** @@ -143,7 +141,7 @@ public function __toString(): string { $linesStr = []; foreach ($this->getAllLines() as $line) { - $linesStr[] = strval($line); + $linesStr[] = (string) $line; } return implode("\n", $linesStr) . "\n"; } diff --git a/src/Parsing/Common/Ocr/OcrWord.php b/src/V1/Parsing/Common/Ocr/OcrWord.php similarity index 59% rename from src/Parsing/Common/Ocr/OcrWord.php rename to src/V1/Parsing/Common/Ocr/OcrWord.php index 197862a1..622b4c2d 100644 --- a/src/Parsing/Common/Ocr/OcrWord.php +++ b/src/V1/Parsing/Common/Ocr/OcrWord.php @@ -1,29 +1,32 @@ > $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 new file mode 100644 index 00000000..c720702b --- /dev/null +++ b/src/V1/Parsing/Common/OrientationField.php @@ -0,0 +1,39 @@ + + */ +class OrientationField extends BaseField +{ + /** + * @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. + */ + public function __construct( + array $rawPrediction, + ?int $pageId = null, + bool $reconstructed = false, + string $valueKey = 'value' + ) { + parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); + $this->value = 0; + if (array_key_exists($valueKey, $rawPrediction) && is_numeric($rawPrediction[$valueKey])) { + $this->value = (int) ($rawPrediction[$valueKey]); + if (!in_array($this->value, [0, 90, 180, 270], true)) { + $this->value = 0; + } + } + } +} diff --git a/src/Parsing/Common/Page.php b/src/V1/Parsing/Common/Page.php similarity index 51% rename from src/Parsing/Common/Page.php rename to src/V1/Parsing/Common/Page.php index 61db09ad..bdef85fc 100644 --- a/src/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -1,20 +1,25 @@ > $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) { $this->id = $rawPrediction['id']; - try { - $reflection = new ReflectionClass($predictionType); - $this->prediction = $reflection->newInstance($rawPrediction['prediction'], $this->id); - } catch (ReflectionException $e) { + if (!is_subclass_of($predictionType, Prediction::class)) { throw new MindeeApiException( - "Unable to create custom product " . $predictionType, - ErrorCode::INTERNAL_LIBRARY_ERROR, - $e + "Invalid prediction type " . $predictionType . ", must extend " . Prediction::class, + ErrorCode::INTERNAL_LIBRARY_ERROR ); } + $this->prediction = self::createPrediction($predictionType, $rawPrediction['prediction'], $this->id); if (array_key_exists('orientation', $rawPrediction)) { $this->orientation = new OrientationField($rawPrediction['orientation'], $this->id, false, 'value'); } @@ -56,6 +60,15 @@ public function __construct(string $predictionType, array $rawPrediction) } } + /** + * @param class-string $predictionType Type of prediction. + * @param array> $rawPrediction Raw prediction array. + */ + private static function createPrediction(string $predictionType, array $rawPrediction, int $pageId): Prediction + { + return new $predictionType($rawPrediction, $pageId); + } + /** * @return string String representation. */ diff --git a/src/Parsing/Common/PredictResponse.php b/src/V1/Parsing/Common/PredictResponse.php similarity index 65% rename from src/Parsing/Common/PredictResponse.php rename to src/V1/Parsing/Common/PredictResponse.php index 410d50eb..a6278d27 100644 --- a/src/Parsing/Common/PredictResponse.php +++ b/src/V1/Parsing/Common/PredictResponse.php @@ -1,6 +1,8 @@ > $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/Parsing/Common/Prediction.php b/src/V1/Parsing/Common/Prediction.php similarity index 60% rename from src/Parsing/Common/Prediction.php rename to src/V1/Parsing/Common/Prediction.php index 5c0b0230..94d4c8a0 100644 --- a/src/Parsing/Common/Prediction.php +++ b/src/V1/Parsing/Common/Prediction.php @@ -1,11 +1,15 @@ > $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -28,7 +32,7 @@ public function __construct(array $rawPrediction) /** * @return string String representation. */ - public function __toString() + public function __toString(): string { return "$this->name v$this->version"; } diff --git a/src/Parsing/Common/WorkflowResponse.php b/src/V1/Parsing/Common/WorkflowResponse.php similarity index 76% rename from src/Parsing/Common/WorkflowResponse.php rename to src/V1/Parsing/Common/WorkflowResponse.php index 4eb58371..d2cbed59 100644 --- a/src/Parsing/Common/WorkflowResponse.php +++ b/src/V1/Parsing/Common/WorkflowResponse.php @@ -1,9 +1,11 @@ > $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/Parsing/Generated/GeneratedListField.php b/src/V1/Parsing/Generated/GeneratedListField.php similarity index 57% rename from src/Parsing/Generated/GeneratedListField.php rename to src/V1/Parsing/Generated/GeneratedListField.php index 47c77326..2ed9b6b0 100644 --- a/src/Parsing/Generated/GeneratedListField.php +++ b/src/V1/Parsing/Generated/GeneratedListField.php @@ -1,32 +1,33 @@ List of values */ public array $values = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. - * @param integer|null $pageId ID of the page. + * @param list>> $rawPrediction Array containing the list elements. + * @param integer|null $pageId ID of the page. */ - public function __construct(array $rawPrediction, ?int $pageId = null) + public function __construct(array $rawPrediction, public ?int $pageId = null) { - $this->pageId = $pageId; - foreach ($rawPrediction as $value) { - if (isset($value['page_id'])) { + if (isset($value['page_id']) && is_int($value['page_id'])) { $this->pageId = $value['page_id']; } @@ -36,12 +37,15 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $valueStr = $value; if (isset($valueStr['value'])) { if ( - (is_int($valueStr['value']) || (is_float($value) && floor($value) == $value)) && - $value != 0.0 + ( + is_int($valueStr['value']) + || (is_float($valueStr['value']) && floor($valueStr['value']) === $valueStr['value']) + ) + && (float) $value['value'] !== 0.0 ) { $valueStr['value'] = $value['value'] . ".0"; } else { - $valueStr['value'] = strval($value['value']); + $valueStr['value'] = (string) ($value['value']); } } $this->values[] = new StringField($valueStr, $this->pageId); @@ -52,13 +56,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(function ($v) { - return (string)($v ?: ""); - }, $this->values); + return array_map(static fn($v) => (string) $v, $this->values); } /** diff --git a/src/Parsing/Generated/GeneratedObjectField.php b/src/V1/Parsing/Generated/GeneratedObjectField.php similarity index 58% rename from src/Parsing/Generated/GeneratedObjectField.php rename to src/V1/Parsing/Generated/GeneratedObjectField.php index 4660f5a5..28f05842 100644 --- a/src/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -1,13 +1,27 @@ List of all printable field names */ private array $printableValues; + /** + * @var array|integer|float|string|bool|null> + * Storage for dynamically generated properties. + */ + private array $dynamicProperties = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. - * @param integer|null $pageId ID of the page. + * @param array> $rawPrediction Raw prediction data. + * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -44,13 +63,13 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $this->rawValue = $value; } else { if (isset($value)) { - if ((is_int($value) || (is_float($value) && floor($value) == $value)) && $value != 0.0) { + if ((is_int($value) || (is_float($value) && floor($value) === $value)) && (float) $value !== 0.0) { $this->{$fieldName} = $value . ".0"; } else { if (is_array($value)) { $this->{$fieldName} = implode(", ", $value); } else { - $this->{$fieldName} = strval($value); + $this->{$fieldName} = (string) $value; } } } else { @@ -62,6 +81,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 BaseField|string|integer|boolean|float|null $value Property value. + */ + public function __set(string $name, BaseField|string|int|bool|float|null $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. * @@ -86,8 +138,8 @@ public function strLevel(int $level = 0): string $outStr = ""; foreach ($this->printableValues as $attr) { $value = $this->{$attr}; - $strValue = $value !== null ? (string)$value : ""; - $outStr .= "\n{$indent}:{$attr}: {$strValue}"; + $strValue = $value !== null ? (string) $value : ""; + $outStr .= "\n$indent:$attr: $strValue"; } return "\n" . $indent . trim($outStr); } @@ -95,7 +147,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 @@ -111,7 +163,7 @@ public static function isGeneratedObject(array $strDict): bool "raw_value", ]; foreach (array_keys($strDict) as $key) { - if (!in_array($key, $commonKeys)) { + if (!in_array($key, $commonKeys, true)) { return true; } } diff --git a/src/Parsing/Standard/AddressField.php b/src/V1/Parsing/Standard/AddressField.php similarity index 80% rename from src/Parsing/Standard/AddressField.php rename to src/V1/Parsing/Standard/AddressField.php index e7eae1ff..d57a5957 100644 --- a/src/Parsing/Standard/AddressField.php +++ b/src/V1/Parsing/Standard/AddressField.php @@ -1,6 +1,8 @@ > $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. */ public function __construct( array $rawPrediction, @@ -50,7 +52,6 @@ public function __construct( /** * Prettier string representation (same semantics as StringField). * - * @return string */ public function __toString(): string { diff --git a/src/Parsing/Standard/AmountField.php b/src/V1/Parsing/Standard/AmountField.php similarity index 56% rename from src/Parsing/Standard/AmountField.php rename to src/V1/Parsing/Standard/AmountField.php index 3daf5f30..ebdb830d 100644 --- a/src/Parsing/Standard/AmountField.php +++ b/src/V1/Parsing/Standard/AmountField.php @@ -1,25 +1,24 @@ */ class AmountField extends BaseField { - use FieldPositionMixin; use FieldConfidenceMixin; + use FieldPositionMixin; /** - * @var float|null The amount value as a float. - */ - public $value; - - - /** - * @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 array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. + * @param boolean $reconstructed Whether the field was reconstructed. */ public function __construct( array $rawPrediction, @@ -28,7 +27,7 @@ public function __construct( ) { parent::__construct($rawPrediction, $pageId, $reconstructed, 'value'); if (array_key_exists('value', $rawPrediction) && is_numeric($rawPrediction['value'])) { - $this->value = number_format(floatval($rawPrediction['value']), 2, ".", ""); + $this->value = (float) ($rawPrediction['value']); } else { $this->value = null; $this->confidence = 0.0; @@ -41,6 +40,6 @@ public function __construct( */ public function __toString(): string { - return strval($this->value); + return isset($this->value) ? number_format((float) $this->value, 2, ".", "") : ''; } } diff --git a/src/V1/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php new file mode 100644 index 00000000..0118e142 --- /dev/null +++ b/src/V1/Parsing/Standard/BaseField.php @@ -0,0 +1,72 @@ +> $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. + */ + public function __construct( + array $rawPrediction, + ?int $pageId = null, + public bool $reconstructed = false, + string $valueKey = 'value' + ) { + if (!isset($pageId) && (array_key_exists('page_id', $rawPrediction) && isset($rawPrediction['page_id']))) { + $this->pageId = $rawPrediction['page_id']; + } else { + $this->pageId = $pageId; + } + if (array_key_exists($valueKey, $rawPrediction) && $rawPrediction[$valueKey] !== 'N/A') { + $this->value = $rawPrediction[$valueKey]; + $this->setConfidence($rawPrediction); + } else { + $this->value = null; + } + } + + /** + * Compares with the value of another field. + * + * @param BaseField $obj Field to compare. + * @return boolean + */ + public function __compare(self $obj): bool + { + return $this->value === $obj->value; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return isset($this->value) ? (string) ($this->value) : ''; + } +} diff --git a/src/Parsing/Standard/BooleanField.php b/src/V1/Parsing/Standard/BooleanField.php similarity index 53% rename from src/Parsing/Standard/BooleanField.php rename to src/V1/Parsing/Standard/BooleanField.php index ee907974..b353fabe 100644 --- a/src/Parsing/Standard/BooleanField.php +++ b/src/V1/Parsing/Standard/BooleanField.php @@ -1,28 +1,25 @@ */ class BooleanField extends BaseField { - use FieldPositionMixin; use FieldConfidenceMixin; + use FieldPositionMixin; /** - * @var boolean|null Value as string. - */ - public $value; - - - /** - * @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. + * @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. */ public function __construct( array $rawPrediction, @@ -40,6 +37,6 @@ public function __construct( */ public function __toString(): string { - return SummaryHelper::formatForDisplay($this->value); + return SummaryHelperV1::formatForDisplay($this->value); } } diff --git a/src/V1/Parsing/Standard/ClassificationField.php b/src/V1/Parsing/Standard/ClassificationField.php new file mode 100644 index 00000000..41e04227 --- /dev/null +++ b/src/V1/Parsing/Standard/ClassificationField.php @@ -0,0 +1,32 @@ + + */ +class ClassificationField extends BaseField +{ + /** + * @var float The confidence score. + */ + public float $confidence; + + /** + * @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. + */ + public function __construct( + array $rawPrediction, + ?int $pageId = null, + bool $reconstructed = false, + string $valueKey = 'value' + ) { + parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); + } +} diff --git a/src/Parsing/Standard/CompanyRegistrationField.php b/src/V1/Parsing/Standard/CompanyRegistrationField.php similarity index 63% rename from src/Parsing/Standard/CompanyRegistrationField.php rename to src/V1/Parsing/Standard/CompanyRegistrationField.php index 2591f93d..87116f31 100644 --- a/src/Parsing/Standard/CompanyRegistrationField.php +++ b/src/V1/Parsing/Standard/CompanyRegistrationField.php @@ -1,27 +1,32 @@ */ 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 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. + * @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. */ public function __construct( array $rawPrediction, @@ -37,7 +42,6 @@ public function __construct( /** * Return as a table line for RST display. * - * @return string */ public function toTableLine(): string { @@ -48,7 +52,6 @@ public function toTableLine(): string /** * String representation. * - * @return string */ public function __toString(): string { @@ -58,14 +61,13 @@ public function __toString(): string /** * Returns an array of proper values for the formatting. - * - * @return array + * @return array */ private function printableValues(): array { $printable = []; - $printable['type'] = SummaryHelper::formatForDisplay($this->type); - $printable['value'] = SummaryHelper::formatForDisplay($this->value); + $printable['type'] = SummaryHelperV1::formatForDisplay($this->type); + $printable['value'] = SummaryHelperV1::formatForDisplay($this->value); return $printable; } } diff --git a/src/Parsing/Standard/DateField.php b/src/V1/Parsing/Standard/DateField.php similarity index 71% rename from src/Parsing/Standard/DateField.php rename to src/V1/Parsing/Standard/DateField.php index 356ae224..d1b50cfd 100644 --- a/src/Parsing/Standard/DateField.php +++ b/src/V1/Parsing/Standard/DateField.php @@ -1,6 +1,8 @@ */ class DateField extends BaseField { @@ -21,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. */ @@ -33,10 +31,10 @@ class DateField extends BaseField /** - * @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. + * @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. * @throws MindeeApiException Throws if the date can't be created from the given value. */ public function __construct( @@ -55,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/Parsing/Standard/FieldConfidenceMixin.php b/src/V1/Parsing/Standard/FieldConfidenceMixin.php similarity index 62% rename from src/Parsing/Standard/FieldConfidenceMixin.php rename to src/V1/Parsing/Standard/FieldConfidenceMixin.php index 6a89b9eb..91d742da 100644 --- a/src/Parsing/Standard/FieldConfidenceMixin.php +++ b/src/V1/Parsing/Standard/FieldConfidenceMixin.php @@ -1,6 +1,10 @@ > $rawPrediction Raw prediction array. */ - protected function setConfidence(array $rawPrediction) + protected function setConfidence(array $rawPrediction): void { if (array_key_exists('confidence', $rawPrediction) && $rawPrediction['confidence']) { $this->confidence = $rawPrediction['confidence']; diff --git a/src/Parsing/Standard/FieldPositionMixin.php b/src/V1/Parsing/Standard/FieldPositionMixin.php similarity index 74% rename from src/Parsing/Standard/FieldPositionMixin.php rename to src/V1/Parsing/Standard/FieldPositionMixin.php index 9be9acc9..5397eacd 100644 --- a/src/Parsing/Standard/FieldPositionMixin.php +++ b/src/V1/Parsing/Standard/FieldPositionMixin.php @@ -1,11 +1,14 @@ > $rawPrediction Raw prediction array. */ protected function setPosition(array $rawPrediction): void { $this->boundingBox = null; $this->polygon = new Polygon(); - if (array_key_exists('polygon', $rawPrediction) and isset($rawPrediction['polygon'])) { + if (array_key_exists('polygon', $rawPrediction) && isset($rawPrediction['polygon'])) { $this->polygon = new Polygon($rawPrediction['polygon']); } if ($this->polygon->getCoordinates()) { diff --git a/src/Parsing/Standard/LocaleField.php b/src/V1/Parsing/Standard/LocaleField.php similarity index 67% rename from src/Parsing/Standard/LocaleField.php rename to src/V1/Parsing/Standard/LocaleField.php index 4e66795f..60919abd 100644 --- a/src/Parsing/Standard/LocaleField.php +++ b/src/V1/Parsing/Standard/LocaleField.php @@ -1,9 +1,14 @@ */ class LocaleField extends BaseField { @@ -21,13 +26,12 @@ class LocaleField extends BaseField public ?string $currency; /** - * @param array $localePrediction Raw locale prediction. - * @param string $key Name of the prediction key. - * @return string|null + * @param array> $localePrediction Raw locale prediction. + * @param string $key Name of the prediction key. */ private static function getValue(array $localePrediction, string $key): ?string { - if (!array_key_exists($key, $localePrediction) || $localePrediction[$key] == 'N/A') { + if (!array_key_exists($key, $localePrediction) || $localePrediction[$key] === 'N/A') { return null; } @@ -35,9 +39,9 @@ private static function getValue(array $localePrediction, string $key): ?string } /** - * @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 array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. + * @param boolean $reconstructed Whether the field was reconstructed. */ public function __construct( array $rawPrediction, @@ -50,9 +54,9 @@ public function __construct( $valueKey = 'language'; } parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); - $this->language = LocaleField::getValue($rawPrediction, 'language'); - $this->country = LocaleField::getValue($rawPrediction, 'country'); - $this->currency = LocaleField::getValue($rawPrediction, 'currency'); + $this->language = self::getValue($rawPrediction, 'language'); + $this->country = self::getValue($rawPrediction, 'country'); + $this->currency = self::getValue($rawPrediction, 'currency'); } /** diff --git a/src/Parsing/Standard/PaymentDetailsField.php b/src/V1/Parsing/Standard/PaymentDetailsField.php similarity index 66% rename from src/Parsing/Standard/PaymentDetailsField.php rename to src/V1/Parsing/Standard/PaymentDetailsField.php index e9096f8a..d584a587 100644 --- a/src/Parsing/Standard/PaymentDetailsField.php +++ b/src/V1/Parsing/Standard/PaymentDetailsField.php @@ -1,9 +1,15 @@ */ class PaymentDetailsField extends BaseField { @@ -29,21 +35,20 @@ class PaymentDetailsField extends BaseField /** * Gets the value of any given key. * - * @param array $rawPrediction Raw prediction array. - * @param string $key Key to get the value of. - * @return string|null + * @param array> $rawPrediction Raw prediction array. + * @param string $key Key to get the value of. */ private function getValue(array $rawPrediction, string $key): ?string { if ( - array_key_exists($key, $rawPrediction) && - is_scalar($rawPrediction[$key]) + array_key_exists($key, $rawPrediction) + && is_scalar($rawPrediction[$key]) ) { - $value = strval($rawPrediction[$key]); + $value = (string) ($rawPrediction[$key]); } else { $value = null; } - if ($value == 'N/A') { + if ($value === 'N/A') { $value = null; } @@ -51,14 +56,14 @@ private function getValue(array $rawPrediction, string $key): ?string } /** - * @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. - * @param string $accountNumberKey Key to use for the account number. - * @param string $ibanKey Key to use for the IBAN. - * @param string $routingNumberKey Key to use for the routing number. - * @param string $swiftKey Key to use for the SWIFT code. + * @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. + * @param string $accountNumberKey Key to use for the account number. + * @param string $ibanKey Key to use for the IBAN. + * @param string $routingNumberKey Key to use for the routing number. + * @param string $swiftKey Key to use for the SWIFT code. */ public function __construct( array $rawPrediction, diff --git a/src/V1/Parsing/Standard/PositionField.php b/src/V1/Parsing/Standard/PositionField.php new file mode 100644 index 00000000..61453cfc --- /dev/null +++ b/src/V1/Parsing/Standard/PositionField.php @@ -0,0 +1,108 @@ + + */ +class PositionField extends BaseField +{ + /** + * @var Polygon|null Polygon of cropped area. + */ + public ?Polygon $polygon; + /** + * @var Polygon|null Quadrangle of cropped area (does not exceed the canvas). + */ + public ?Polygon $quadrangle; + /** + * @var Polygon|null Oriented rectangle of cropped area (may exceed the canvas). + */ + public ?Polygon $rectangle; + /** + * @var Polygon|null Straight rectangle of cropped area (does not exceed the canvas). + */ + public ?Polygon $boundingBox; + + /** + * Retrieves the quadrilateral of a prediction. + * + * @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 (empty($rawPrediction[$key])) { + return null; + } + + return PolygonUtils::quadrilateralFromPrediction($rawPrediction[$key]); + } + + /** + * Retrieves the polygon of a prediction. + * + * @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 null; + } + + return new Polygon($rawPrediction[$key]); + } + + /** + * @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. + */ + public function __construct( + array $rawPrediction, + ?int $pageId = null, + bool $reconstructed = false, + string $valueKey = 'polygon' + ) { + parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); + + $this->boundingBox = self::getQuadrilateral($rawPrediction, 'bounding_box'); + $this->quadrangle = self::getQuadrilateral($rawPrediction, 'quadrangle'); + $this->rectangle = self::getQuadrilateral($rawPrediction, 'rectangle'); + $this->polygon = self::getPolygon($rawPrediction, 'polygon'); + + $this->value = $this->polygon; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + if ($this->polygon) { + return 'Polygon with ' . count($this->polygon->getCoordinates()) . ' points.'; + } + if ($this->boundingBox) { + return 'Polygon with ' . count($this->boundingBox->getCoordinates()) . ' points.'; + } + if ($this->rectangle) { + return 'Polygon with ' . count($this->rectangle->getCoordinates()) . ' points.'; + } + if ($this->quadrangle) { + return 'Polygon with ' . count($this->quadrangle->getCoordinates()) . ' points.'; + } + + return ''; + } +} diff --git a/src/Parsing/Standard/StringField.php b/src/V1/Parsing/Standard/StringField.php similarity index 58% rename from src/Parsing/Standard/StringField.php rename to src/V1/Parsing/Standard/StringField.php index f0319e87..e4463011 100644 --- a/src/Parsing/Standard/StringField.php +++ b/src/V1/Parsing/Standard/StringField.php @@ -1,30 +1,31 @@ */ class StringField extends BaseField { - use FieldPositionMixin; use FieldConfidenceMixin; + use FieldPositionMixin; - /** - * @var string|null Value as string. - */ - public $value; /** * @var string|null The value as it appears on the document. */ - public string|null $rawValue; + public ?string $rawValue; /** - * @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. + * @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. */ public function __construct( array $rawPrediction, diff --git a/src/Parsing/Standard/TaxField.php b/src/V1/Parsing/Standard/TaxField.php similarity index 61% rename from src/Parsing/Standard/TaxField.php rename to src/V1/Parsing/Standard/TaxField.php index 5400a77f..8225131e 100644 --- a/src/Parsing/Standard/TaxField.php +++ b/src/V1/Parsing/Standard/TaxField.php @@ -1,18 +1,19 @@ */ class TaxField extends BaseField { use FieldPositionMixin; - - /** - * @var float|null The amount of the tax line. - */ - public $value; /** * @var float|null The tax rate. */ @@ -27,10 +28,10 @@ class TaxField extends BaseField public ?float $basis; /** - * @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. + * @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. */ public function __construct( array $rawPrediction, @@ -41,27 +42,27 @@ public function __construct( parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); $this->setPosition($rawPrediction); if (array_key_exists('value', $rawPrediction) && is_numeric($rawPrediction['value'])) { - $this->value = floatval($rawPrediction['value']); + $this->value = (float) ($rawPrediction['value']); } else { $this->value = null; $this->confidence = 0.0; } if (array_key_exists('rate', $rawPrediction) && is_numeric($rawPrediction['rate'])) { - $this->rate = floatval($rawPrediction['rate']); + $this->rate = (float) ($rawPrediction['rate']); } else { $this->rate = null; } if ( array_key_exists('code', $rawPrediction) && is_scalar( $rawPrediction['code'] - ) && $rawPrediction['code'] != 'N/A' + ) && $rawPrediction['code'] !== 'N/A' ) { - $this->code = strval($rawPrediction['code']); + $this->code = (string) ($rawPrediction['code']); } else { $this->code = null; } if (array_key_exists('base', $rawPrediction) && is_numeric($rawPrediction['base'])) { - $this->basis = floatval($rawPrediction['base']); + $this->basis = (float) ($rawPrediction['base']); } else { $this->basis = null; } @@ -70,15 +71,15 @@ 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 { return [ 'code' => $this->code ?? '', - 'basis' => isset($this->basis) ? number_format((float)$this->basis, 2, ".", "") : '', - 'rate' => isset($this->rate) ? number_format((float)$this->rate, 2, ".", "") : '', - 'value' => isset($this->value) ? number_format((float)$this->value, 2, ".", "") : '', + 'basis' => isset($this->basis) ? number_format((float) $this->basis, 2, ".", "") : '', + 'rate' => isset($this->rate) ? number_format((float) $this->rate, 2, ".", "") : '', + 'value' => isset($this->value) ? number_format((float) $this->value, 2, ".", "") : '', ]; } @@ -91,10 +92,10 @@ public function toTableLine(): string { $printable = $this->printableValues(); - return '| ' . mb_str_pad($printable['basis'], 13, ' ', STR_PAD_RIGHT, "UTF-8") . - ' | ' . mb_str_pad($printable['code'], 6, ' ', STR_PAD_RIGHT, "UTF-8") . - ' | ' . mb_str_pad($printable['rate'], 8, ' ', STR_PAD_RIGHT, "UTF-8") . - ' | ' . mb_str_pad($printable['value'], 13, ' ', STR_PAD_RIGHT, "UTF-8") . ' |'; + return '| ' . mb_str_pad($printable['basis'], 13, ' ', STR_PAD_RIGHT, "UTF-8") + . ' | ' . mb_str_pad($printable['code'], 6, ' ', STR_PAD_RIGHT, "UTF-8") + . ' | ' . mb_str_pad($printable['rate'], 8, ' ', STR_PAD_RIGHT, "UTF-8") + . ' | ' . mb_str_pad($printable['value'], 13, ' ', STR_PAD_RIGHT, "UTF-8") . ' |'; } /** @@ -105,10 +106,10 @@ public function __toString(): string $printable = $this->printableValues(); return rtrim( - 'Base: ' . $printable['basis'] . ', ' . - 'Code: ' . $printable['code'] . ', ' . - 'Rate (%): ' . $printable['rate'] . ', ' . - 'Amount: ' . $printable['value'] + 'Base: ' . $printable['basis'] . ', ' + . 'Code: ' . $printable['code'] . ', ' + . 'Rate (%): ' . $printable['rate'] . ', ' + . 'Amount: ' . $printable['value'] ); } } diff --git a/src/Parsing/Standard/Taxes.php b/src/V1/Parsing/Standard/Taxes.php similarity index 66% rename from src/Parsing/Standard/Taxes.php rename to src/V1/Parsing/Standard/Taxes.php index d07a5712..496aceba 100644 --- a/src/Parsing/Standard/Taxes.php +++ b/src/V1/Parsing/Standard/Taxes.php @@ -1,15 +1,21 @@ */ -class Taxes extends \ArrayObject +class Taxes extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId) * Creates a string of rst line separators. * * @param string $char Character to use as a separator. - * @return string */ private static function lineSeparator(string $char): string { @@ -39,11 +44,11 @@ private static function lineSeparator(string $char): string /** * @return string String representation. */ - public function __toString() + public function __toString(): string { - $outStr = "\n" . Taxes::lineSeparator('-') . "\n"; + $outStr = "\n" . self::lineSeparator('-') . "\n"; $outStr .= " | Base | Code | Rate (%) | Amount |\n"; - $outStr .= Taxes::lineSeparator('='); + $outStr .= self::lineSeparator('='); $arr = []; $iterator = $this->getIterator(); if (!$iterator->valid()) { @@ -51,7 +56,7 @@ public function __toString() } while ($iterator->valid()) { $entry = $iterator->current(); - $arr[] = "\n " . $entry->toTableLine() . "\n" . Taxes::lineSeparator('-'); + $arr[] = "\n " . $entry->toTableLine() . "\n" . self::lineSeparator('-'); $iterator->next(); } $outStr .= implode("\n", $arr); diff --git a/src/V1/Parsing/SummaryHelperV1.php b/src/V1/Parsing/SummaryHelperV1.php new file mode 100644 index 00000000..60a06730 --- /dev/null +++ b/src/V1/Parsing/SummaryHelperV1.php @@ -0,0 +1,26 @@ +>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * + * @return ExtractedPdf[] list of extracted documents + * + * @throws MindeePdfException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. + * @throws InvalidArgumentException Throws if invalid indexes are provided. + */ + public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes): array + { + if (is_array($pageIndexes[0])) { + $indexes = $pageIndexes; + } else { + $indexes = array_map(static fn($pageIndex) => $pageIndex->pageIndexes, (array) $pageIndexes); + } + return parent::extractSubDocuments($indexes); + } + + + /** + * Extracts invoices as complete PDFs from the document. + * + * @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 + */ + public function extractInvoices(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes, bool $strict = false): array + { + if (empty($pageIndexes)) { + return []; + } + if (!$strict) { + $indexes = array_map(static fn($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); + + return $this->extractSubDocuments($indexes); + } + if (is_array($pageIndexes[0])) { + return parent::extractInvoices($pageIndexes, $strict); + } + + $correctPageIndexes = []; + $currentList = []; + $previousConfidence = null; + + $i = 0; + foreach ($pageIndexes as $pageIndex) { + $confidence = $pageIndex->confidence; + $pageList = $pageIndex->pageIndexes; + + if ($confidence >= 0.5 && null === $previousConfidence) { + $currentList = $pageList; + } elseif ($confidence >= 0.5 && $i !== count($pageIndexes) - 1) { + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + $currentList = $pageList; + } elseif ($confidence < 0.5 && $i === count($pageIndexes) - 1) { + $currentList = array_merge($currentList, $pageList); + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + } else { + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + $correctPageIndexes[] = $pageList; + } + + $previousConfidence = $confidence; + ++$i; + } + + return $this->extractSubDocuments($correctPageIndexes); + } +} diff --git a/src/Product/BarcodeReader/BarcodeReaderV1.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php similarity index 71% rename from src/Product/BarcodeReader/BarcodeReaderV1.php rename to src/V1/Product/BarcodeReader/BarcodeReaderV1.php index b9922ded..15dc1256 100644 --- a/src/Product/BarcodeReader/BarcodeReaderV1.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BarcodeReaderV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BarcodeReader/BarcodeReaderV1Document.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php similarity index 64% rename from src/Product/BarcodeReader/BarcodeReaderV1Document.php rename to src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php index 82d9a6ef..22ce3d83 100644 --- a/src/Product/BarcodeReader/BarcodeReaderV1Document.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php @@ -1,11 +1,13 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -30,15 +33,15 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["codes_1d"])) { throw new MindeeUnsetException(); } - $this->codes1D = $rawPrediction["codes_1d"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $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( - fn ($prediction) => new StringField($prediction, $pageId), + $this->codes2D = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_2d"] ); } @@ -60,6 +63,6 @@ public function __toString(): string $outStr = ":Barcodes 1D: $codes1D :Barcodes 2D: $codes2D "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/BusinessCard/BusinessCardV1.php b/src/V1/Product/BusinessCard/BusinessCardV1.php similarity index 71% rename from src/Product/BusinessCard/BusinessCardV1.php rename to src/V1/Product/BusinessCard/BusinessCardV1.php index f5697c46..d892d12f 100644 --- a/src/Product/BusinessCard/BusinessCardV1.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BusinessCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BusinessCard/BusinessCardV1Document.php b/src/V1/Product/BusinessCard/BusinessCardV1Document.php similarity index 88% rename from src/Product/BusinessCard/BusinessCardV1Document.php rename to src/V1/Product/BusinessCard/BusinessCardV1Document.php index 711ea6f7..7b273910 100644 --- a/src/Product/BusinessCard/BusinessCardV1Document.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1Document.php @@ -1,11 +1,13 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -129,8 +131,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["social_media"])) { throw new MindeeUnsetException(); } - $this->socialMedia = $rawPrediction["social_media"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->socialMedia = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["social_media"] ); if (!isset($rawPrediction["website"])) { @@ -164,6 +166,6 @@ public function __toString(): string :Website: $this->website :Social Media: $socialMedia "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Cropper/CropperV1.php b/src/V1/Product/Cropper/CropperV1.php similarity index 65% rename from src/Product/Cropper/CropperV1.php rename to src/V1/Product/Cropper/CropperV1.php index e3863ffa..5cccfdc3 100644 --- a/src/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -1,12 +1,14 @@ > $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 { $this->pages[] = new Page(CropperV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Cropper/CropperV1Document.php b/src/V1/Product/Cropper/CropperV1Document.php similarity index 54% rename from src/Product/Cropper/CropperV1Document.php rename to src/V1/Product/Cropper/CropperV1Document.php index aecf0b65..684c422e 100644 --- a/src/Product/Cropper/CropperV1Document.php +++ b/src/V1/Product/Cropper/CropperV1Document.php @@ -1,14 +1,21 @@ > $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( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->cropping = null === $rawPrediction["cropping"] ? [] : array_map( + static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["cropping"] ); } @@ -39,6 +41,6 @@ public function __toString(): string $outStr = ":Document Cropper: $cropping "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/DriverLicense/DriverLicenseV1.php b/src/V1/Product/DriverLicense/DriverLicenseV1.php similarity index 71% rename from src/Product/DriverLicense/DriverLicenseV1.php rename to src/V1/Product/DriverLicense/DriverLicenseV1.php index 43c2468a..0963c0d8 100644 --- a/src/Product/DriverLicense/DriverLicenseV1.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(DriverLicenseV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/DriverLicense/DriverLicenseV1Document.php b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php similarity index 91% rename from src/Product/DriverLicense/DriverLicenseV1Document.php rename to src/V1/Product/DriverLicense/DriverLicenseV1Document.php index c3ddb431..bbcb3013 100644 --- a/src/Product/DriverLicense/DriverLicenseV1Document.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -185,6 +187,6 @@ public function __toString(): string :MRZ: $this->mrz :DD Number: $this->ddNumber "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php similarity index 72% rename from src/Product/FinancialDocument/FinancialDocumentV1.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1.php index 5c153e3e..f82c4ea6 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(FinancialDocumentV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1Document.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php similarity index 89% rename from src/Product/FinancialDocument/FinancialDocumentV1Document.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php index e070e7f6..7ce6dc94 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1Document.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php @@ -1,19 +1,21 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -184,8 +186,8 @@ 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( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->customerCompanyRegistrations = array_map( + static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); if (!isset($rawPrediction["customer_id"])) { @@ -282,8 +284,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->referenceNumbers = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); if (!isset($rawPrediction["shipping_address"])) { @@ -310,8 +312,8 @@ 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( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->supplierCompanyRegistrations = array_map( + static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); if (!isset($rawPrediction["supplier_email"])) { @@ -331,8 +333,8 @@ 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( - fn ($prediction) => new PaymentDetailsField($prediction, $pageId), + $this->supplierPaymentDetails = array_map( + static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); if (!isset($rawPrediction["supplier_phone_number"])) { @@ -414,7 +416,7 @@ public function __toString(): string "\n ", $this->customerCompanyRegistrations ); - $lineItemsSummary = strval($this->lineItems); + $lineItemsSummary = (string) ($this->lineItems); $outStr = ":Locale: $this->locale :Invoice Number: $this->invoiceNumber @@ -450,6 +452,6 @@ public function __toString(): string :Purchase Time: $this->time :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php new file mode 100644 index 00000000..665934ec --- /dev/null +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -0,0 +1,120 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->description = $rawPrediction["description"] ?? null; + $this->productCode = $rawPrediction["product_code"] ?? null; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; + $this->taxAmount = isset($rawPrediction["tax_amount"]) + ? (float) ($rawPrediction["tax_amount"]) : null; + $this->taxRate = isset($rawPrediction["tax_rate"]) + ? (float) ($rawPrediction["tax_rate"]) : null; + $this->totalAmount = isset($rawPrediction["total_amount"]) + ? (float) ($rawPrediction["total_amount"]) : null; + $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $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. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["productCode"], 12); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["taxAmount"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 12); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitMeasure"], 15); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php similarity index 81% rename from src/Product/FinancialDocument/FinancialDocumentV1LineItems.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index b9340c2c..cffcc2a2 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -1,15 +1,21 @@ */ -class FinancialDocumentV1LineItems extends \ArrayObject +class FinancialDocumentV1LineItems extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function lineItemsSeparator(string $char): string { @@ -44,7 +49,6 @@ public static function lineItemsSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php similarity index 72% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php index d15b52a1..291f4bfd 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BankAccountDetailsV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php similarity index 78% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php index ceb8cc30..dfc4666e 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php @@ -1,11 +1,13 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -64,6 +66,6 @@ public function __toString(): string :Account Holder's Name: $this->accountHolderName :SWIFT Code: $this->swift "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php similarity index 72% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php index 532eaf80..ab9dca19 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BankAccountDetailsV2Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php similarity index 55% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index 94297e1b..045676a7 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -1,18 +1,21 @@ > $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -45,39 +48,22 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bbanNumber = $rawPrediction["bban_number"] ?? null; } - /** - * Return values for printing inside an RST table. - * - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bbanBankCode"] = SummaryHelper::formatForDisplay($this->bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelper::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelper::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelper::formatForDisplay($this->bbanNumber); - return $outArr; - } - /** * Return values for printing as an array. - * - * @return array + * @return array */ private function printableValues(): array { $outArr = []; - $outArr["bbanBankCode"] = SummaryHelper::formatForDisplay($this->bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelper::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelper::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelper::formatForDisplay($this->bbanNumber); + $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; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -95,6 +81,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php similarity index 80% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php index dfc3043a..7b951977 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php @@ -1,11 +1,13 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -70,13 +72,13 @@ 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 :IBAN: $this->iban :SWIFT Code: $this->swiftCode "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/CarteGrise/CarteGriseV1.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php similarity index 71% rename from src/Product/Fr/CarteGrise/CarteGriseV1.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index ede84373..8b9a2ed7 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(CarteGriseV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/CarteGrise/CarteGriseV1Document.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php similarity index 96% rename from src/Product/Fr/CarteGrise/CarteGriseV1Document.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php index 9342649a..7fcd3fad 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1Document.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -521,6 +523,6 @@ public function __toString(): string :MRZ Line 1: $this->mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV1.php b/src/V1/Product/Fr/IdCard/IdCardV1.php similarity index 72% rename from src/Product/Fr/IdCard/IdCardV1.php rename to src/V1/Product/Fr/IdCard/IdCardV1.php index 16af405a..c992ed76 100644 --- a/src/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(IdCardV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/IdCard/IdCardV1Document.php b/src/V1/Product/Fr/IdCard/IdCardV1Document.php similarity index 87% rename from src/Product/Fr/IdCard/IdCardV1Document.php rename to src/V1/Product/Fr/IdCard/IdCardV1Document.php index b47a4705..d2a59608 100644 --- a/src/Product/Fr/IdCard/IdCardV1Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -98,8 +101,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["id_number"])) { @@ -153,6 +156,6 @@ public function __toString(): string :MRZ Line 1: $this->mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV1Page.php b/src/V1/Product/Fr/IdCard/IdCardV1Page.php similarity index 64% rename from src/Product/Fr/IdCard/IdCardV1Page.php rename to src/V1/Product/Fr/IdCard/IdCardV1Page.php index 4239fca1..0b86f4f9 100644 --- a/src/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -1,9 +1,11 @@ > $rawPrediction Raw prediction from HTTP response. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -36,6 +38,6 @@ public function __toString(): string $outStr = ":Document Side: $this->documentSide "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV2.php b/src/V1/Product/Fr/IdCard/IdCardV2.php similarity index 72% rename from src/Product/Fr/IdCard/IdCardV2.php rename to src/V1/Product/Fr/IdCard/IdCardV2.php index a4455598..42bf9428 100644 --- a/src/Product/Fr/IdCard/IdCardV2.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(IdCardV2Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/IdCard/IdCardV2Document.php b/src/V1/Product/Fr/IdCard/IdCardV2Document.php similarity index 90% rename from src/Product/Fr/IdCard/IdCardV2Document.php rename to src/V1/Product/Fr/IdCard/IdCardV2Document.php index 45b38d16..3e5582d8 100644 --- a/src/Product/Fr/IdCard/IdCardV2Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -139,8 +141,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["issue_date"])) { @@ -213,6 +215,6 @@ public function __toString(): string :Date of Issue: $this->issueDate :Issuing Authority: $this->authority "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV2Page.php b/src/V1/Product/Fr/IdCard/IdCardV2Page.php similarity index 71% rename from src/Product/Fr/IdCard/IdCardV2Page.php rename to src/V1/Product/Fr/IdCard/IdCardV2Page.php index e96774bf..0cb60a67 100644 --- a/src/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -1,9 +1,11 @@ > $rawPrediction Raw prediction from HTTP response. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -45,6 +47,6 @@ public function __toString(): string :Document Sides: $this->documentSide "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Generated/GeneratedV1.php b/src/V1/Product/Generated/GeneratedV1.php similarity index 74% rename from src/Product/Generated/GeneratedV1.php rename to src/V1/Product/Generated/GeneratedV1.php index 7f0bb884..c5bd5fff 100644 --- a/src/Product/Generated/GeneratedV1.php +++ b/src/V1/Product/Generated/GeneratedV1.php @@ -1,13 +1,15 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/Product/Generated/GeneratedV1Document.php b/src/V1/Product/Generated/GeneratedV1Document.php similarity index 53% rename from src/Product/Generated/GeneratedV1Document.php rename to src/V1/Product/Generated/GeneratedV1Document.php index d7c3d260..75711f43 100644 --- a/src/Product/Generated/GeneratedV1Document.php +++ b/src/V1/Product/Generated/GeneratedV1Document.php @@ -1,29 +1,35 @@ 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) { + /** @var list>> $fieldContents */ $this->fields[$fieldName] = new GeneratedListField($fieldContents); } elseif (is_array($fieldContents) && GeneratedObjectField::isGeneratedObject($fieldContents)) { $this->fields[$fieldName] = new GeneratedObjectField($fieldContents); @@ -31,14 +37,14 @@ public function __construct(array $rawPrediction) $fieldContentsStr = $fieldContents; if (isset($fieldContentsStr['value'])) { if ( - (is_int($fieldContentsStr['value']) || - (is_float($fieldContentsStr['value']) && - floor($fieldContentsStr['value']) == $fieldContentsStr['value'])) && - $fieldContentsStr['value'] != 0.0 + (is_int($fieldContentsStr['value']) + || (is_float($fieldContentsStr['value']) + && floor($fieldContentsStr['value']) === $fieldContentsStr['value'])) + && (float) $fieldContentsStr['value'] !== 0.0 ) { $this->{$fieldName} = $fieldContentsStr['value'] . ".0"; } else { - $fieldContentsStr['value'] = strval($fieldContents['value']); + $fieldContentsStr['value'] = (string) ($fieldContents['value']); } } else { $fieldContentsStr['value'] = null; diff --git a/src/Product/Generated/GeneratedV1Page.php b/src/V1/Product/Generated/GeneratedV1Page.php similarity index 52% rename from src/Product/Generated/GeneratedV1Page.php rename to src/V1/Product/Generated/GeneratedV1Page.php index 4a1cf546..fecb23bd 100644 --- a/src/Product/Generated/GeneratedV1Page.php +++ b/src/V1/Product/Generated/GeneratedV1Page.php @@ -1,30 +1,39 @@ Dictionary of all fields in the document. + */ public array $fields; /** * GeneratedV1Page constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. - * @param integer|null $pageId ID of the page. + * @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) { + /** @var list>> $fieldContents */ $this->fields[$fieldName] = new GeneratedListField($fieldContents, $pageId); } elseif (is_array($fieldContents) && GeneratedObjectField::isGeneratedObject($fieldContents)) { $this->fields[$fieldName] = new GeneratedObjectField($fieldContents, $pageId); @@ -32,14 +41,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $fieldContentsStr = $fieldContents; if (isset($fieldContentsStr['value'])) { if ( - (is_int($fieldContentsStr['value']) || - (is_float($fieldContentsStr['value']) && - floor($fieldContentsStr['value']) == $fieldContentsStr['value'])) && - $fieldContentsStr['value'] != 0.0 + (is_int($fieldContentsStr['value']) + || (is_float($fieldContentsStr['value']) + && floor($fieldContentsStr['value']) === $fieldContentsStr['value'])) + && (float) $fieldContentsStr['value'] !== 0.0 ) { $this->{$fieldName} = $fieldContentsStr['value'] . ".0"; } else { - $fieldContentsStr['value'] = strval($fieldContents['value']); + $fieldContentsStr['value'] = (string) ($fieldContents['value']); } } else { $fieldContentsStr['value'] = null; diff --git a/src/Product/Generated/GeneratedV1Prediction.php b/src/V1/Product/Generated/GeneratedV1Prediction.php similarity index 84% rename from src/Product/Generated/GeneratedV1Prediction.php rename to src/V1/Product/Generated/GeneratedV1Prediction.php index 44e83225..5b4680bf 100644 --- a/src/Product/Generated/GeneratedV1Prediction.php +++ b/src/V1/Product/Generated/GeneratedV1Prediction.php @@ -1,16 +1,20 @@ fields = []; } @@ -51,17 +54,17 @@ public function __toString(): string $strValue .= " " . str_repeat( " ", mb_strlen($fieldName, "UTF-8") + 2 - ) . - "{$fieldValue->values[$i]}\n"; + ) + . "{$fieldValue->values[$i]}\n"; } } $strValue = rtrim($strValue); } else { - $strValue = strval($fieldValue); + $strValue = (string) $fieldValue; } $outStr .= ":{$fieldName}: {$strValue}\n"; } - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } /** diff --git a/src/Product/InternationalId/InternationalIdV2.php b/src/V1/Product/InternationalId/InternationalIdV2.php similarity index 72% rename from src/Product/InternationalId/InternationalIdV2.php rename to src/V1/Product/InternationalId/InternationalIdV2.php index 361ee315..2f000d33 100644 --- a/src/Product/InternationalId/InternationalIdV2.php +++ b/src/V1/Product/InternationalId/InternationalIdV2.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(InternationalIdV2Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/InternationalId/InternationalIdV2Document.php b/src/V1/Product/InternationalId/InternationalIdV2Document.php similarity index 89% rename from src/Product/InternationalId/InternationalIdV2Document.php rename to src/V1/Product/InternationalId/InternationalIdV2Document.php index 238f52df..4c2b607d 100644 --- a/src/Product/InternationalId/InternationalIdV2Document.php +++ b/src/V1/Product/InternationalId/InternationalIdV2Document.php @@ -1,13 +1,15 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -141,8 +143,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["issue_date"])) { @@ -204,8 +206,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["surnames"])) { throw new MindeeUnsetException(); } - $this->surnames = $rawPrediction["surnames"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->surnames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); } @@ -242,6 +244,6 @@ public function __toString(): string :MRZ Line 2: $this->mrzLine2 :MRZ Line 3: $this->mrzLine3 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Invoice/InvoiceV4.php b/src/V1/Product/Invoice/InvoiceV4.php similarity index 71% rename from src/Product/Invoice/InvoiceV4.php rename to src/V1/Product/Invoice/InvoiceV4.php index dcdb975d..7368ef5b 100644 --- a/src/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(InvoiceV4Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Invoice/InvoiceV4Document.php b/src/V1/Product/Invoice/InvoiceV4Document.php similarity index 89% rename from src/Product/Invoice/InvoiceV4Document.php rename to src/V1/Product/Invoice/InvoiceV4Document.php index c485aa61..201f0a6d 100644 --- a/src/Product/Invoice/InvoiceV4Document.php +++ b/src/V1/Product/Invoice/InvoiceV4Document.php @@ -1,19 +1,21 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -167,8 +169,8 @@ 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( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->customerCompanyRegistrations = array_map( + static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); if (!isset($rawPrediction["customer_id"])) { @@ -251,8 +253,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->referenceNumbers = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); if (!isset($rawPrediction["shipping_address"])) { @@ -279,8 +281,8 @@ 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( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->supplierCompanyRegistrations = array_map( + static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); if (!isset($rawPrediction["supplier_email"])) { @@ -300,8 +302,8 @@ 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( - fn ($prediction) => new PaymentDetailsField($prediction, $pageId), + $this->supplierPaymentDetails = array_map( + static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); if (!isset($rawPrediction["supplier_phone_number"])) { @@ -369,7 +371,7 @@ public function __toString(): string "\n ", $this->customerCompanyRegistrations ); - $lineItemsSummary = strval($this->lineItems); + $lineItemsSummary = (string) ($this->lineItems); $outStr = ":Locale: $this->locale :Invoice Number: $this->invoiceNumber @@ -401,6 +403,6 @@ public function __toString(): string :Purchase Category: $this->category :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/V1/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php new file mode 100644 index 00000000..29cae4ca --- /dev/null +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -0,0 +1,120 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->description = $rawPrediction["description"] ?? null; + $this->productCode = $rawPrediction["product_code"] ?? null; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; + $this->taxAmount = isset($rawPrediction["tax_amount"]) + ? (float) ($rawPrediction["tax_amount"]) : null; + $this->taxRate = isset($rawPrediction["tax_rate"]) + ? (float) ($rawPrediction["tax_rate"]) : null; + $this->totalAmount = isset($rawPrediction["total_amount"]) + ? (float) ($rawPrediction["total_amount"]) : null; + $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $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. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["productCode"], 12); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["taxAmount"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 12); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitMeasure"], 15); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php similarity index 82% rename from src/Product/Invoice/InvoiceV4LineItems.php rename to src/V1/Product/Invoice/InvoiceV4LineItems.php index e3e399bc..fdc203c7 100644 --- a/src/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -1,15 +1,21 @@ */ -class InvoiceV4LineItems extends \ArrayObject +class InvoiceV4LineItems extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function lineItemsSeparator(string $char): string { @@ -44,7 +49,6 @@ public static function lineItemsSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php similarity index 72% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php index 2235ceee..8f9a4d5d 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(InvoiceSplitterV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php similarity index 64% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php index dccce3ad..d71e14c7 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php @@ -1,10 +1,12 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -37,10 +39,10 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $invoicePageGroupsSummary = strval($this->invoicePageGroups); + $invoicePageGroupsSummary = (string) ($this->invoicePageGroups); $outStr = ":Invoice Page Groups: $invoicePageGroupsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php similarity index 52% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index b0c83c20..acbcd207 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -1,18 +1,21 @@ > $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -32,8 +35,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * - * @return array + * @return array */ private function tablePrintableValues(): array { @@ -42,28 +44,16 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["pageIndexes"] = implode(", ", $this->pageIndexes); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["pageIndexes"], 72); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["pageIndexes"], 72); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -71,6 +61,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php similarity index 77% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index ea90083b..55cf7711 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -1,15 +1,21 @@ */ -class InvoiceSplitterV1InvoicePageGroups extends \ArrayObject +class InvoiceSplitterV1InvoicePageGroups extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function invoicePageGroupsSeparator(string $char): string { @@ -37,7 +42,6 @@ public static function invoicePageGroupsSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php similarity index 72% rename from src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php rename to src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php index 6f480b1d..11baf635 100644 --- a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(MultiReceiptsDetectorV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php similarity index 61% rename from src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php rename to src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php index 9df25cd1..208cc23c 100644 --- a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php @@ -1,11 +1,13 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -26,8 +28,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["receipts"])) { throw new MindeeUnsetException(); } - $this->receipts = $rawPrediction["receipts"] == null ? [] : array_map( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->receipts = array_map( + static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["receipts"] ); } @@ -44,6 +46,6 @@ public function __toString(): string $outStr = ":List of Receipts: $receipts "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php similarity index 71% rename from src/Product/Passport/PassportV1.php rename to src/V1/Product/Passport/PassportV1.php index 1a45b867..186113fe 100644 --- a/src/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(PassportV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Passport/PassportV1Document.php b/src/V1/Product/Passport/PassportV1Document.php similarity index 88% rename from src/Product/Passport/PassportV1Document.php rename to src/V1/Product/Passport/PassportV1Document.php index ed39a67e..a7646bf9 100644 --- a/src/Product/Passport/PassportV1Document.php +++ b/src/V1/Product/Passport/PassportV1Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -102,8 +104,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["id_number"])) { @@ -165,6 +167,6 @@ public function __toString(): string :MRZ Line 1: $this->mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Receipt/ReceiptV5.php b/src/V1/Product/Receipt/ReceiptV5.php similarity index 71% rename from src/Product/Receipt/ReceiptV5.php rename to src/V1/Product/Receipt/ReceiptV5.php index 681a87f4..e15354a1 100644 --- a/src/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(ReceiptV5Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Receipt/ReceiptV5Document.php b/src/V1/Product/Receipt/ReceiptV5Document.php similarity index 88% rename from src/Product/Receipt/ReceiptV5Document.php rename to src/V1/Product/Receipt/ReceiptV5Document.php index fca27398..318ac14d 100644 --- a/src/Product/Receipt/ReceiptV5Document.php +++ b/src/V1/Product/Receipt/ReceiptV5Document.php @@ -1,17 +1,19 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -152,8 +154,8 @@ 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( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->supplierCompanyRegistrations = array_map( + static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); if (!isset($rawPrediction["supplier_name"])) { @@ -223,7 +225,7 @@ public function __toString(): string "\n ", $this->supplierCompanyRegistrations ); - $lineItemsSummary = strval($this->lineItems); + $lineItemsSummary = (string) ($this->lineItems); $outStr = ":Expense Locale: $this->locale :Purchase Category: $this->category @@ -243,6 +245,6 @@ public function __toString(): string :Receipt Number: $this->receiptNumber :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/V1/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php new file mode 100644 index 00000000..0f50da48 --- /dev/null +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -0,0 +1,90 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->description = $rawPrediction["description"] ?? null; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; + $this->totalAmount = isset($rawPrediction["total_amount"]) + ? (float) ($rawPrediction["total_amount"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $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. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php similarity index 79% rename from src/Product/Receipt/ReceiptV5LineItems.php rename to src/V1/Product/Receipt/ReceiptV5LineItems.php index f684ff43..40171070 100644 --- a/src/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -1,15 +1,21 @@ */ -class ReceiptV5LineItems extends \ArrayObject +class ReceiptV5LineItems extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function lineItemsSeparator(string $char): string { @@ -40,7 +45,6 @@ public static function lineItemsSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/Resume/ResumeV1.php b/src/V1/Product/Resume/ResumeV1.php similarity index 71% rename from src/Product/Resume/ResumeV1.php rename to src/V1/Product/Resume/ResumeV1.php index 2c9f036f..69036333 100644 --- a/src/Product/Resume/ResumeV1.php +++ b/src/V1/Product/Resume/ResumeV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(ResumeV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/V1/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php new file mode 100644 index 00000000..deeeea2c --- /dev/null +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -0,0 +1,87 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->grade = $rawPrediction["grade"] ?? null; + $this->name = $rawPrediction["name"] ?? null; + $this->provider = $rawPrediction["provider"] ?? null; + $this->year = $rawPrediction["year"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade, 10); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 30); + $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider, 25); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); + return $outArr; + } + + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["grade"], 10); + $outStr .= SummaryHelperV1::padString($printable["name"], 30); + $outStr .= SummaryHelperV1::padString($printable["provider"], 25); + $outStr .= SummaryHelperV1::padString($printable["year"], 4); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php similarity index 80% rename from src/Product/Resume/ResumeV1Certificates.php rename to src/V1/Product/Resume/ResumeV1Certificates.php index c13366f1..c109db53 100644 --- a/src/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -1,15 +1,21 @@ */ -class ResumeV1Certificates extends \ArrayObject +class ResumeV1Certificates extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function certificatesSeparator(string $char): string { @@ -40,7 +45,6 @@ public static function certificatesSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/Resume/ResumeV1Document.php b/src/V1/Product/Resume/ResumeV1Document.php similarity index 84% rename from src/Product/Resume/ResumeV1Document.php rename to src/V1/Product/Resume/ResumeV1Document.php index d4c428b1..7eee91e7 100644 --- a/src/Product/Resume/ResumeV1Document.php +++ b/src/V1/Product/Resume/ResumeV1Document.php @@ -1,12 +1,14 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -133,15 +135,15 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $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( - fn ($prediction) => new StringField($prediction, $pageId), + $this->hardSkills = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["hard_skills"] ); if (!isset($rawPrediction["job_applied"])) { @@ -196,15 +198,15 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["soft_skills"])) { throw new MindeeUnsetException(); } - $this->softSkills = $rawPrediction["soft_skills"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $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( - fn ($prediction) => new StringField($prediction, $pageId), + $this->surnames = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); } @@ -222,8 +224,8 @@ public function __toString(): string "\n ", $this->surnames ); - $socialNetworksUrlsSummary = strval($this->socialNetworksUrls); - $languagesSummary = strval($this->languages); + $socialNetworksUrlsSummary = (string) ($this->socialNetworksUrls); + $languagesSummary = (string) ($this->languages); $hardSkills = implode( "\n ", $this->hardSkills @@ -232,9 +234,9 @@ public function __toString(): string "\n ", $this->softSkills ); - $educationSummary = strval($this->education); - $professionalExperiencesSummary = strval($this->professionalExperiences); - $certificatesSummary = strval($this->certificates); + $educationSummary = (string) ($this->education); + $professionalExperiencesSummary = (string) ($this->professionalExperiences); + $certificatesSummary = (string) ($this->certificates); $outStr = ":Document Language: $this->documentLanguage :Document Type: $this->documentType @@ -254,6 +256,6 @@ public function __toString(): string :Professional Experiences: $professionalExperiencesSummary :Certificates: $certificatesSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/V1/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php new file mode 100644 index 00000000..39e3ecc6 --- /dev/null +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -0,0 +1,108 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->degreeDomain = $rawPrediction["degree_domain"] ?? null; + $this->degreeType = $rawPrediction["degree_type"] ?? null; + $this->endMonth = $rawPrediction["end_month"] ?? null; + $this->endYear = $rawPrediction["end_year"] ?? null; + $this->school = $rawPrediction["school"] ?? null; + $this->startMonth = $rawPrediction["start_month"] ?? null; + $this->startYear = $rawPrediction["start_year"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain, 15); + $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType, 25); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school, 25); + $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. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["degreeDomain"], 15); + $outStr .= SummaryHelperV1::padString($printable["degreeType"], 25); + $outStr .= SummaryHelperV1::padString($printable["endMonth"], 9); + $outStr .= SummaryHelperV1::padString($printable["endYear"], 8); + $outStr .= SummaryHelperV1::padString($printable["school"], 25); + $outStr .= SummaryHelperV1::padString($printable["startMonth"], 11); + $outStr .= SummaryHelperV1::padString($printable["startYear"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php similarity index 82% rename from src/Product/Resume/ResumeV1Educations.php rename to src/V1/Product/Resume/ResumeV1Educations.php index 6549826c..a2635633 100644 --- a/src/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -1,15 +1,21 @@ */ -class ResumeV1Educations extends \ArrayObject +class ResumeV1Educations extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function educationSeparator(string $char): string { @@ -43,7 +48,6 @@ public static function educationSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/V1/Product/Resume/ResumeV1Language.php b/src/V1/Product/Resume/ResumeV1Language.php new file mode 100644 index 00000000..a05a6b72 --- /dev/null +++ b/src/V1/Product/Resume/ResumeV1Language.php @@ -0,0 +1,73 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->language = $rawPrediction["language"] ?? null; + $this->level = $rawPrediction["level"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); + $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level, 20); + return $outArr; + } + + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["language"], 8); + $outStr .= SummaryHelperV1::padString($printable["level"], 20); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php similarity index 78% rename from src/Product/Resume/ResumeV1Languages.php rename to src/V1/Product/Resume/ResumeV1Languages.php index 612a5ad7..a1a4e2a7 100644 --- a/src/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -1,15 +1,21 @@ */ -class ResumeV1Languages extends \ArrayObject +class ResumeV1Languages extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function languagesSeparator(string $char): string { @@ -38,7 +43,6 @@ public static function languagesSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php new file mode 100644 index 00000000..d9d2d1ee --- /dev/null +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php @@ -0,0 +1,122 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->contractType = $rawPrediction["contract_type"] ?? null; + $this->department = $rawPrediction["department"] ?? null; + $this->description = $rawPrediction["description"] ?? null; + $this->employer = $rawPrediction["employer"] ?? null; + $this->endMonth = $rawPrediction["end_month"] ?? null; + $this->endYear = $rawPrediction["end_year"] ?? null; + $this->role = $rawPrediction["role"] ?? null; + $this->startMonth = $rawPrediction["start_month"] ?? null; + $this->startYear = $rawPrediction["start_year"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType, 15); + $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department, 10); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer, 25); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role, 20); + $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. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["contractType"], 15); + $outStr .= SummaryHelperV1::padString($printable["department"], 10); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["employer"], 25); + $outStr .= SummaryHelperV1::padString($printable["endMonth"], 9); + $outStr .= SummaryHelperV1::padString($printable["endYear"], 8); + $outStr .= SummaryHelperV1::padString($printable["role"], 20); + $outStr .= SummaryHelperV1::padString($printable["startMonth"], 11); + $outStr .= SummaryHelperV1::padString($printable["startYear"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php similarity index 83% rename from src/Product/Resume/ResumeV1ProfessionalExperiences.php rename to src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index 84cfecca..8c470bd0 100644 --- a/src/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -1,15 +1,21 @@ */ -class ResumeV1ProfessionalExperiences extends \ArrayObject +class ResumeV1ProfessionalExperiences extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function professionalExperiencesSeparator(string $char): string { @@ -45,7 +50,6 @@ public static function professionalExperiencesSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php new file mode 100644 index 00000000..3fe6add7 --- /dev/null +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php @@ -0,0 +1,73 @@ +> $rawPrediction Array containing the JSON document response. + * @param integer|null $pageId Page number for multi pages document. + */ + public function __construct(array $rawPrediction, public ?int $pageId) + { + $this->setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->name = $rawPrediction["name"] ?? null; + $this->url = $rawPrediction["url"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * @return array + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); + $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url, 50); + return $outArr; + } + + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["name"], 20); + $outStr .= SummaryHelperV1::padString($printable["url"], 50); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php similarity index 78% rename from src/Product/Resume/ResumeV1SocialNetworksUrls.php rename to src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index 9b9b0a13..be9ff061 100644 --- a/src/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -1,15 +1,21 @@ */ -class ResumeV1SocialNetworksUrls extends \ArrayObject +class ResumeV1SocialNetworksUrls extends ArrayObject implements Stringable { /** - * @param array $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. + * @param array> $rawPrediction Raw prediction array. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -24,7 +30,6 @@ public function __construct(array $rawPrediction, ?int $pageId = null) * Creates a line of rST table-compliant string separators. * * @param string $char Character to use as a separator. - * @return string */ public static function socialNetworksUrlsSeparator(string $char): string { @@ -38,7 +43,6 @@ public static function socialNetworksUrlsSeparator(string $char): string /** * String representation. * - * @return string */ public function __toString(): string { diff --git a/src/Product/Us/BankCheck/BankCheckV1.php b/src/V1/Product/Us/BankCheck/BankCheckV1.php similarity index 71% rename from src/Product/Us/BankCheck/BankCheckV1.php rename to src/V1/Product/Us/BankCheck/BankCheckV1.php index de92c369..3bbdd107 100644 --- a/src/Product/Us/BankCheck/BankCheckV1.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1.php @@ -1,12 +1,14 @@ > $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { @@ -33,7 +35,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BankCheckV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/BankCheck/BankCheckV1Document.php b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php similarity index 80% rename from src/Product/Us/BankCheck/BankCheckV1Document.php rename to src/V1/Product/Us/BankCheck/BankCheckV1Document.php index 9bfe9113..d8e73b8c 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Document.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php @@ -1,13 +1,15 @@ > $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. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -76,8 +78,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["payees"])) { throw new MindeeUnsetException(); } - $this->payees = $rawPrediction["payees"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->payees = array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["payees"] ); if (!isset($rawPrediction["routing_number"])) { @@ -106,6 +108,6 @@ public function __toString(): string :Account Number: $this->accountNumber :Check Number: $this->checkNumber "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/BankCheck/BankCheckV1Page.php b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php similarity index 66% rename from src/Product/Us/BankCheck/BankCheckV1Page.php rename to src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 8642f35c..b70a8ac0 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -1,9 +1,11 @@ > $rawPrediction Raw prediction from HTTP response. + * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { @@ -29,8 +31,8 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $rawPrediction["check_position"], $pageId ); - $this->signaturesPositions = $rawPrediction["signatures_positions"] == null ? [] : array_map( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->signaturesPositions = array_map( + static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["signatures_positions"] ); } @@ -49,6 +51,6 @@ public function __toString(): string :Signature Positions: $signaturesPositions "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/ClientV2.php b/src/V2/Client.php similarity index 57% rename from src/ClientV2.php rename to src/V2/Client.php index fc0ab147..25de2e47 100644 --- a/src/ClientV2.php +++ b/src/V2/Client.php @@ -1,20 +1,23 @@ mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); - } - - /** - * Send the document to an asynchronous endpoint and return its ID in the queue. - * - * @param InputSource $inputSource File to parse. - * @param InferenceParameters $params Parameters relating to prediction options. - * @return JobResponse A JobResponse containing the job (queue) corresponding to a document. - * @throws MindeeException Throws if the input document is not provided. - * @category Asynchronous - */ - public function enqueueInference( - InputSource $inputSource, - InferenceParameters $params - ): JobResponse { - return $this->enqueue($inputSource, $params); + $this->mindeeApi = new MindeeApiV2($apiKey ?: (getenv('MINDEE_V2_API_KEY') ?: null)); } /** * Send the document to an asynchronous endpoint and return its ID in the queue. - * @param InputSource $inputSource File to parse. - * @param BaseParameters $params Parameters relating to prediction options. + * @param InputSource $inputSource File to parse. + * @param BaseParameters $params Parameters relating to prediction options. * @return JobResponse A JobResponse containing the job (queue) corresponding to a document. * @throws MindeeException Throws if the input document is not provided. * @category Asynchronous @@ -64,24 +51,13 @@ public function enqueue( return $this->mindeeApi->reqPostEnqueue($inputSource, $params); } - /** - * Retrieves an inference. - * - * @param string $inferenceId ID of the queue to poll. - * @return InferenceResponse An InferenceResponse containing a Job. - * @category Asynchronous - */ - public function getInference(string $inferenceId): InferenceResponse - { - return $this->mindeeApi->reqGetInference($inferenceId); - } /** * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param string $resultUrl URL of the result. - * @return T A response containing parsing results. + * @param string $resultUrl URL of the result. + * @return BaseResponse A response containing parsing results. */ public function getResultFromUrl( string $responseClass, @@ -94,8 +70,8 @@ public function getResultFromUrl( * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param string $resultId ID of the result. - * @return T A response containing parsing results. + * @param string $resultId ID of the result. + * @return BaseResponse A response containing parsing results. */ public function getResult( string $responseClass, @@ -117,40 +93,28 @@ public function getJob(string $jobId): JobResponse return $this->mindeeApi->reqGetJob($jobId); } - /** - * Send a document to an endpoint and poll the server until the result is sent or - * until the maximum number of tries is reached. - * - * @param InputSource $inputDoc Input document to parse. - * @param InferenceParameters $params Parameters relating to prediction options. - * @return InferenceResponse A response containing parsing results. - * @throws MindeeException Throws if enqueueing fails, job fails, or times out. - */ - public function enqueueAndGetInference( - InputSource $inputDoc, - InferenceParameters $params - ): InferenceResponse { - return $this->enqueueAndGetResult(InferenceResponse::class, $inputDoc, $params); - } - /** * Send a document to an endpoint and poll the server until the result is sent or * until the maximum number of tries is reached. * * @template T of BaseResponse - * @param string $responseClass The response class to construct. + * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param InputSource $inputDoc Input document to parse. - * @param BaseParameters $params Parameters relating to prediction options. - * @return T A response containing parsing results. + * @param InputSource $inputDoc Input document to parse. + * @param BaseParameters $params Parameters relating to prediction options. + * @param PollingOptions|null $pollingOptions Options to apply to the polling. + * @return BaseResponse A response containing parsing results. * @throws MindeeException Throws if enqueueing fails, job fails, or times out. */ public function enqueueAndGetResult( string $responseClass, InputSource $inputDoc, - BaseParameters $params + BaseParameters $params, + ?PollingOptions $pollingOptions = null ): BaseResponse { - $pollingOptions = $params->pollingOptions; + if (!$pollingOptions) { + $pollingOptions = new PollingOptions(); + } $enqueueResponse = $this->enqueue($inputDoc, $params); @@ -175,9 +139,9 @@ public function enqueueAndGetResult( } error_log( - "Polling server for parsing result with job ID: " . $jobId . - ". Attempt number " . $retryCounter . " of " . $pollingOptions->maxRetries . - ". Job status: " . $pollResults->job->status + "Polling server for parsing result with job ID: " . $jobId + . ". Attempt number " . $retryCounter . " of " . $pollingOptions->maxRetries + . ". Job status: " . $pollResults->job->status ); $this->customSleep($pollingOptions->delaySec); @@ -192,8 +156,19 @@ public function enqueueAndGetResult( } throw new MindeeException( - "Asynchronous parsing request timed out after " . - ($pollingOptions->delaySec * $retryCounter) . " seconds" + "Asynchronous parsing request timed out after " + . ($pollingOptions->delaySec * $retryCounter) . " seconds" ); } + + /** + * Searches for a list of available models for the given API key. + * @param string|null $modelName Optional model name to filter by. + * @param string|null $modelType Optional model type to filter by. + * @return SearchResponse The list of models matching the criteria. + */ + public function searchModels(?string $modelName = null, ?string $modelType = null): SearchResponse + { + return $this->mindeeApi->searchModels($modelName, $modelType); + } } diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index a156fb3e..f146d025 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -1,8 +1,8 @@ Optional webhook IDs. */ - public array $webhooksIds; + public array $webhookIds; /** - * @var PollingOptions Polling options. + * @var string Slug of the endpoint. */ - public PollingOptions $pollingOptions; + public static string $slug; /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhookIds List of webhook IDs. */ - public function __construct(string $modelId, ?string $alias, ?array $webhooksIds, ?PollingOptions $pollingOptions) + public function __construct(public string $modelId, ?string $alias, ?array $webhookIds) { - $this->modelId = $modelId; - if (isset($alias)) { $this->alias = $alias; } - if (isset($webhooksIds)) { - $this->webhooksIds = $webhooksIds; + if (isset($webhookIds)) { + $this->webhookIds = $webhookIds; } else { - $this->webhooksIds = []; - } - if (!$pollingOptions) { - $pollingOptions = new PollingOptions(); + $this->webhookIds = []; } - $this->pollingOptions = $pollingOptions; } /** - * @return array Hash representation. + * @return array Hash representation. */ public function asHash(): array { @@ -64,8 +52,8 @@ public function asHash(): array } - if (isset($this->webhooksIds) && count($this->webhooksIds) > 0) { - $outHash['webhook_ids'] = implode(',', $this->webhooksIds); + if (!empty($this->webhookIds)) { + $outHash['webhook_ids'] = implode(',', $this->webhookIds); } return $outHash; } diff --git a/src/Error/MindeeV2HttpException.php b/src/V2/Error/MindeeV2HttpException.php similarity index 75% rename from src/Error/MindeeV2HttpException.php rename to src/V2/Error/MindeeV2HttpException.php index d8146fba..3fe9c708 100644 --- a/src/Error/MindeeV2HttpException.php +++ b/src/V2/Error/MindeeV2HttpException.php @@ -1,8 +1,12 @@ List of associated errors. */ public array $errors; diff --git a/src/Error/MindeeV2HttpUnknownException.php b/src/V2/Error/MindeeV2HttpUnknownException.php similarity index 80% rename from src/Error/MindeeV2HttpUnknownException.php rename to src/V2/Error/MindeeV2HttpUnknownException.php index 3198c532..8ed4ea46 100644 --- a/src/Error/MindeeV2HttpUnknownException.php +++ b/src/V2/Error/MindeeV2HttpUnknownException.php @@ -1,8 +1,10 @@ -1, "detail" => "Couldn't deserialize server error. Found: $response", "title" => "Unknown error", - "code" => "000-000" + "code" => "000-000", ] ) ); diff --git a/src/V2/FileOperations/Crop.php b/src/V2/FileOperations/Crop.php index 56dc6d4f..ccc3514f 100644 --- a/src/V2/FileOperations/Crop.php +++ b/src/V2/FileOperations/Crop.php @@ -1,29 +1,25 @@ localInput = $localInput; - } + public function __construct(private readonly LocalInputSource $localInput) {} /** * Extracts a crop zone from a file. @@ -32,9 +28,9 @@ public function __construct(LocalInputSource $localInput) * * @return ExtractedImage extracted image */ - public function extractCrop(CropItem $crop): ExtractedImage + public function extractSingleCrop(CropItem $crop): ExtractedImage { - return $this->extractCrops([$crop])[0]; + return $this->extractMultipleCrops([$crop])[0]; } /** @@ -43,7 +39,7 @@ public function extractCrop(CropItem $crop): ExtractedImage * @param CropItem[] $crops List of crops to extract. * @return CropFiles list of extracted files */ - public function extractCrops(array $crops): CropFiles + public function extractMultipleCrops(array $crops): CropFiles { $imageExtractor = new ImageExtractor($this->localInput); $extractedImages = []; @@ -54,7 +50,7 @@ public function extractCrops(array $crops): CropFiles } foreach ($cropsPerPage as $page => $pageCrops) { - $polygons = array_map(fn ($c) => $c->location->polygon, $pageCrops); + $polygons = array_map(static fn($c) => $c->location->polygon, $pageCrops); $filenamePrefix = sprintf('%s_page%d', $this->localInput->fileName, $page); $images = $imageExtractor->extractPolygonsFromPage( diff --git a/src/V2/FileOperations/CropFiles.php b/src/V2/FileOperations/CropFiles.php index 14c5999f..c493a1c9 100644 --- a/src/V2/FileOperations/CropFiles.php +++ b/src/V2/FileOperations/CropFiles.php @@ -1,16 +1,21 @@ + * @extends ArrayObject */ -class CropFiles extends \ArrayObject +class CropFiles extends ArrayObject { /** * Builds a new CropFiles collection. @@ -25,13 +30,12 @@ public function __construct(ExtractedImage ...$items) /** * Save all extracted crops to disk. * - * @param string $path The directory path to save the extracted crops to. - * @param string $prefix Prefix to add to the filename. + * @param string $path The directory path to save the extracted crops to. + * @param string $prefix Prefix to add to the filename. * @param null|string $fileFormat File format to save the crops as. - * @param integer $quality Quality of the saved image. + * @param integer $quality Quality of the saved image. * * @throws MindeeException If directory creation fails. - * @return void */ public function saveAllToDisk( string $path, @@ -39,7 +43,6 @@ public function saveAllToDisk( ?string $fileFormat = null, int $quality = 100 ): void { - $format ??= $fileFormat; $idx = 1; foreach ($this as $crop) { @@ -48,8 +51,8 @@ public function saveAllToDisk( $crop->filename = $filename; try { - $crop->writeToFile($path, $format, $quality); - } catch (\ImagickException $e) { + $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/Split.php b/src/V2/FileOperations/Split.php index 43a076e2..8622e0bf 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -1,11 +1,14 @@ localInput = $inputSource; - } + public function __construct(private readonly LocalInputSource $localInput) {} /** * Expands a range to a list of integers. * * @param integer $start Start of the range. - * @param integer $end End of the range. + * @param integer $end End of the range. * * @return int[] * @@ -50,10 +45,11 @@ public static function expandRange(int $start, int $end): array * @param int[] $split Split range to extract. * * @return ExtractedPdf 2D array of extracted pages + * @throws ImagickException Throws if the image can't be processed. */ public function extractSingleSplit(array $split): ExtractedPdf { - return $this->extractSplits([$split])[0]; + return $this->extractMultipleSplits([$split])[0]; } /** @@ -62,11 +58,12 @@ public function extractSingleSplit(array $split): ExtractedPdf * @param int[][] $splits List of split ranges to extract. * * @return SplitFiles list of extracted files + * @throws ImagickException Throws if the image can't be processed. */ - public function extractSplits(array $splits): SplitFiles + public function extractMultipleSplits(array $splits): SplitFiles { $pdfExtractor = new PdfExtractor($this->localInput); - $expandedPageIndexes = array_map(fn (array $split) => self::expandRange($split[0], $split[1]), $splits); + $expandedPageIndexes = array_map(static fn(array $split) => self::expandRange($split[0], $split[1]), $splits); return new SplitFiles(...$pdfExtractor->extractSubDocuments($expandedPageIndexes)); } diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index b9fefd66..a8c2b1bd 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -1,16 +1,24 @@ + * @extends ArrayObject */ -class SplitFiles extends \ArrayObject +class SplitFiles extends ArrayObject { /** * Builds a new SplitFiles collection. @@ -25,11 +33,10 @@ public function __construct(ExtractedPdf ...$items) /** * Save all extracted splits to disk. * - * @param string $path The directory path to save the extracted splits to. + * @param string $path The directory path to save the extracted splits to. * @param string $prefix Prefix to add to the filename. * * @throws MindeeException If directory creation fails. - * @return void */ public function saveAllToDisk(string $path, string $prefix = 'split'): void { @@ -48,8 +55,8 @@ 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()); + } catch (Exception $e) { + throw new MindeeException('Failed to save split to disk.', 0, previous: $e); } ++$idx; diff --git a/src/Http/MindeeApiV2.php b/src/V2/Http/MindeeApiV2.php similarity index 74% rename from src/Http/MindeeApiV2.php rename to src/V2/Http/MindeeApiV2.php index 38c9957f..b1efefc4 100644 --- a/src/Http/MindeeApiV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -1,39 +1,42 @@ setApiKey($apiKey); + $this->setAPIKey($apiKey); $this->baseUrl = API_V2_BASE_URL_DEFAULT; $this->requestTimeout = API_V2_TIMEOUT_DEFAULT; $this->setFromEnv(); - if (!$this->apiKey || strlen($this->apiKey) == 0) { + if ($this->apiKey === '') { throw new MindeeException( - "Missing API key for call," . - " check your Client configuration.You can set this using the " . - API_KEY_ENV_NAME . ' environment variable.', + "Missing API key for call," + . " check your Client configuration.You can set this using the " + . API_V2_KEY_ENV_NAME . ' environment variable.', ErrorCode::USER_INPUT_ERROR ); } @@ -114,7 +116,6 @@ public function __construct(?string $apiKey) * Sets the base url. * * @param string $value Value for the base Url. - * @return void */ protected function setBaseUrl(string $value): void { @@ -124,16 +125,15 @@ protected function setBaseUrl(string $value): void /** * Sets values from environment, if needed. * - * @return void */ private function setFromEnv(): void { $envVars = [ - API_V2_BASE_URL_ENV_NAME => [$this, 'setBaseUrl'], + API_V2_BASE_URL_ENV_NAME => $this->setBaseUrl(...), API_V2_REQUEST_TIMEOUT_ENV_NAME => [$this, 'setTimeout'], ]; foreach ($envVars as $key => $func) { - $envVal = getenv($key) ? getenv($key) : ''; + $envVal = getenv($key) ?: ''; if ($envVal) { call_user_func($func, $envVal); error_log('Value ' . $key . ' was set from env.'); @@ -146,9 +146,8 @@ private function setFromEnv(): void * Sets the API key. * * @param string|null $apiKey Optional API key. - * @return void */ - protected function setApiKey(?string $apiKey = null): void + protected function setAPIKey(?string $apiKey = null): void { $envVal = !getenv(API_V2_KEY_ENV_NAME) ? '' : getenv(API_V2_KEY_ENV_NAME); if (!$apiKey) { @@ -160,9 +159,9 @@ protected function setApiKey(?string $apiKey = null): void } /** - * @param InputSource $inputDoc Input document. - * @param BaseParameters $params Parameters for the inference. - * @return JobResponse Server response wrapped in a JobResponse object. + * @param InputSource $inputDoc Input document. + * @param BaseParameters $params Parameters for the inference. + * @return JobResponse Server response wrapped in a JobResponse object. * @throws MindeeException Throws if the model ID is not provided. */ public function reqPostEnqueue(InputSource $inputDoc, BaseParameters $params): JobResponse @@ -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. @@ -232,22 +231,6 @@ private function processJobResponse(array $result): JobResponse } } - /** - * Requests the job of a queued document from the API. - * Throws an error if the server's response contains one. - * @param string $inferenceId ID of the inference. - * @return InferenceResponse - * @throws MindeeException Throws if the server's response contains an error. - * @throws MindeeException Throws if the inference ID is not provided. - */ - public function reqGetInference(string $inferenceId): InferenceResponse - { - if (!isset($inferenceId)) { - throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } - return $this->reqGetResult(InferenceResponse::class, $inferenceId); - } - /** * Requests the job of a queued document from the API. * Throws an error if the server's response contains one. @@ -258,11 +241,8 @@ public function reqGetInference(string $inferenceId): InferenceResponse */ 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); + $response = $this->sendGetRequest($this->baseUrl . "/v2/jobs/$jobId"); + return $this->processJobResponse($response); } @@ -270,7 +250,7 @@ public function reqGetJob(string $jobId): JobResponse * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param string $resultId URL of the result. + * @param string $resultId URL of the result. * @return T A response containing parsing results. * @throws MindeeException Throws if the server's response contains an error. * @throws MindeeApiException Throws if the response class is not valid. @@ -279,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) { @@ -292,7 +268,7 @@ public function reqGetResult( $e ); } - $url = $this->baseUrl . "/products/{$slugProperty->getValue()}/results/$resultId"; + $url = $this->baseUrl . "/v2/products/{$slugProperty->getValue()}/results/$resultId"; $response = $this->sendGetRequest($url); return $this->processResponse($responseClass, $response); } @@ -301,7 +277,7 @@ public function reqGetResult( * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param string $resultUrl URL of the result. + * @param string $resultUrl URL of the result. * @return T A response containing parsing results. * @throws MindeeException Throws if the server's response contains an error. */ @@ -309,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( @@ -342,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 { @@ -361,26 +334,25 @@ private function sendGetRequest(string $url): array /** * Starts a CURL session using POST. * - * @param InputSource $inputSource File to upload. - * @param BaseParameters $params Inference parameters. - * @return 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(); - if ($inputSource instanceof URLInputSource) { + if ($inputSource instanceof UrlInputSource) { $postFields['url'] = $inputSource->url; } elseif ($inputSource instanceof LocalInputSource) { $inputSource->checkNeedsFix(); $postFields['file'] = $inputSource->fileObject; } - $url = $this->baseUrl . "/products/{$params::$slug}/enqueue"; + $url = $this->baseUrl . "/v2/products/{$params::$slug}/enqueue"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); $resp = [ @@ -397,8 +369,7 @@ private function documentEnqueuePost( } /** - * @param array $result Raw HTTP response array with 'data' and 'code' keys. - * @return void + * @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. */ @@ -415,4 +386,44 @@ private function checkValidResponse(array $result): void throw new MindeeV2HttpUnknownException(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); } } + + /** + * @return array> Server response. + */ + private function reqGetSearchModels(?string $modelName = null, ?string $modelType = null): array + { + $url = $this->baseUrl . "/v2/search/models"; + $params = []; + if ($modelName) { + $params['name'] = $modelName; + } + if ($modelType) { + $params['model_type'] = $modelType; + } + if (!empty($params)) { + $url .= '?' . http_build_query($params); + } + + $ch = $this->initChannel(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HTTPGET, true); + + $resp = [ + 'data' => curl_exec($ch), + 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), + ]; + curl_close($ch); + return $resp; + } + + /** + * Retrieves a list of models based on criteria. + * @param string|null $modelName Optional model name to filter by. + * @param string|null $modelType Optional model type to filter by. + * @return SearchResponse The list of models matching the criteria. + */ + public function searchModels(?string $modelName = null, ?string $modelType = null): SearchResponse + { + return $this->processResponse(SearchResponse::class, $this->reqGetSearchModels($modelName, $modelType)); + } } diff --git a/src/Error/ErrorItem.php b/src/V2/Parsing/Error/ErrorItem.php similarity index 71% rename from src/Error/ErrorItem.php rename to src/V2/Parsing/Error/ErrorItem.php index fc2e96d8..2c85757d 100644 --- a/src/Error/ErrorItem.php +++ b/src/V2/Parsing/Error/ErrorItem.php @@ -1,6 +1,8 @@ > $rawResponse Raw error response from the API. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/Error/ErrorResponse.php b/src/V2/Parsing/Error/ErrorResponse.php new file mode 100644 index 00000000..9279eb70 --- /dev/null +++ b/src/V2/Parsing/Error/ErrorResponse.php @@ -0,0 +1,52 @@ +|null A list of explicit error details. + */ + public ?array $errors; + + /** + * @param array> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + $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/BaseInference.php b/src/V2/Parsing/Inference/BaseInference.php similarity index 78% rename from src/V2/Parsing/BaseInference.php rename to src/V2/Parsing/Inference/BaseInference.php index 27dcb0f9..38844531 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/Inference/BaseInference.php @@ -1,16 +1,16 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/Parsing/V2/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php similarity index 51% rename from src/Parsing/V2/BaseResponse.php rename to src/V2/Parsing/Inference/BaseResponse.php index 783f7c3e..94c2cdfc 100644 --- a/src/Parsing/V2/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -1,6 +1,8 @@ > $rawHttp Raw server response array. */ - protected function __construct(array $rawResponse) - { - $this->rawHttp = $rawResponse; - } + protected function __construct(private readonly array $rawHttp) {} /** * @return string Raw dump of the JSON response. diff --git a/src/Parsing/V2/Field/BaseField.php b/src/V2/Parsing/Inference/Field/BaseField.php similarity index 65% rename from src/Parsing/V2/Field/BaseField.php rename to src/V2/Parsing/Inference/Field/BaseField.php index c0271d12..f11d30d6 100644 --- a/src/Parsing/V2/Field/BaseField.php +++ b/src/V2/Parsing/Inference/Field/BaseField.php @@ -1,18 +1,20 @@ List of possible locations for a field. */ @@ -24,12 +26,11 @@ abstract class BaseField public ?FieldConfidence $confidence; /** - * @param array $rawPrediction Raw prediction array. - * @param integer $indentLevel Level of indentation for rst display. + * @param array> $rawPrediction Raw prediction array. + * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $rawPrediction, int $indentLevel = 0) + public function __construct(array $rawPrediction, protected int $indentLevel = 0) { - $this->indentLevel = $indentLevel; if (array_key_exists("locations", $rawPrediction) && $rawPrediction["locations"]) { $this->locations = []; foreach ($rawPrediction["locations"] as $location) { @@ -42,9 +43,8 @@ public function __construct(array $rawPrediction, int $indentLevel = 0) } /** - * @param array $rawPrediction Raw prediction array. - * @param integer $indentLevel Level of indentation for rst display. - * @return ListField|ObjectField|SimpleField + * @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. */ public static function createField(array $rawPrediction, int $indentLevel = 0): ListField|ObjectField|SimpleField @@ -62,4 +62,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/Parsing/V2/Field/FieldConfidence.php b/src/V2/Parsing/Inference/Field/FieldConfidence.php similarity index 96% rename from src/Parsing/V2/Field/FieldConfidence.php rename to src/V2/Parsing/Inference/Field/FieldConfidence.php index 24acb37f..055f329a 100644 --- a/src/Parsing/V2/Field/FieldConfidence.php +++ b/src/V2/Parsing/Inference/Field/FieldConfidence.php @@ -1,6 +1,8 @@ > $rawResponse Raw server response. + */ + public function __construct(array $rawResponse) + { + $this->polygon = isset($rawResponse['polygon']) ? new Polygon($rawResponse['polygon']) : null; + $this->page = isset($rawResponse['page']) && is_int($rawResponse['page']) + ? $rawResponse['page'] + : null; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return $this->polygon ? $this->polygon . " on page $this->page" : ''; + } +} diff --git a/src/Parsing/V2/Field/InferenceFields.php b/src/V2/Parsing/Inference/Field/InferenceFields.php similarity index 79% rename from src/Parsing/V2/Field/InferenceFields.php rename to src/V2/Parsing/Inference/Field/InferenceFields.php index 0b439a17..aa2018d9 100644 --- a/src/Parsing/V2/Field/InferenceFields.php +++ b/src/V2/Parsing/Inference/Field/InferenceFields.php @@ -1,12 +1,17 @@ */ class InferenceFields extends ArrayObject { @@ -16,19 +21,12 @@ class InferenceFields extends ArrayObject private array $fields = []; /** - * @var integer Indentation level. + * @param array> $rawResponse Raw server response array. + * @param integer $indentLevel Level of indentation. */ - private int $indentLevel; - - /** - * @param array $serverResponse Raw server response array. - * @param integer $indentLevel Level of indentation. - */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, private readonly 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); @@ -38,16 +36,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."); } /** @@ -102,7 +95,6 @@ public function getObjectField(string $fieldName) * Convert the fields to a string representation. * * @param integer|null $indent Optional indentation level. - * @return string */ public function toString(?int $indent = 0): string { @@ -110,7 +102,7 @@ public function toString(?int $indent = 0): string return ''; } - $indent = $indent ?? $this->indentLevel; + $indent ??= $this->indentLevel; $padding = str_repeat(' ', $indent); $lines = []; @@ -125,7 +117,7 @@ public function toString(?int $indent = 0): string $line .= $fieldValue->__toString(); } elseif ($fieldValue instanceof SimpleField) { $value = $fieldValue->__toString(); - if ($value != '') { + if ($value !== '') { $line .= ' ' . $value; } } diff --git a/src/Parsing/V2/Field/ListField.php b/src/V2/Parsing/Inference/Field/ListField.php similarity index 57% rename from src/Parsing/V2/Field/ListField.php rename to src/V2/Parsing/Inference/Field/ListField.php index 87676d28..c92034a5 100644 --- a/src/Parsing/V2/Field/ListField.php +++ b/src/V2/Parsing/Inference/Field/ListField.php @@ -1,44 +1,47 @@ + * @var array Items contained in the list. */ public array $items; /** - * @param array $serverResponse Raw server response array. - * @param integer $indentLevel Level of indentation for rst display. + * @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); } } /** - * @return string */ public function __toString(): string { @@ -48,7 +51,7 @@ public function __toString(): string $parts = ['']; foreach ($this->items as $item) { - if ($item === null) { + if (null === $item) { continue; } diff --git a/src/Parsing/V2/Field/ObjectField.php b/src/V2/Parsing/Inference/Field/ObjectField.php similarity index 83% rename from src/Parsing/V2/Field/ObjectField.php rename to src/V2/Parsing/Inference/Field/ObjectField.php index cfd440d0..3a156b39 100644 --- a/src/Parsing/V2/Field/ObjectField.php +++ b/src/V2/Parsing/Inference/Field/ObjectField.php @@ -1,6 +1,8 @@ > $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 ); } /** - * @return string */ public function __toString(): string { @@ -39,7 +39,6 @@ public function __toString(): string /** * Returns a string representation suitable for list display. * - * @return string */ public function toStringFromList(): string { @@ -50,7 +49,6 @@ public function toStringFromList(): string * Returns a ListField instance for the specified key. * * @param string $key The key of the list field to retrieve. - * @return ListField * @throws InvalidArgumentException When the field does not exist or is not a list field. */ public function getListField(string $key): ListField @@ -66,7 +64,6 @@ public function getListField(string $key): ListField * Returns a SimpleField instance for the specified key. * * @param string $key The key of the simple field to retrieve. - * @return SimpleField * @throws InvalidArgumentException When the field does not exist or is not a simple field. */ public function getSimpleField(string $key): SimpleField @@ -82,13 +79,12 @@ public function getSimpleField(string $key): SimpleField * Returns an ObjectField instance for the specified key. * * @param string $key The key of the simple field to retrieve. - * @return ObjectField * @throws InvalidArgumentException When the field does not exist or is not a simple field. */ - public function getObjectField(string $key): ObjectField + public function getObjectField(string $key): self { $field = $this->fields->get($key); - if (!($field instanceof ObjectField)) { + if (!($field instanceof self)) { throw new InvalidArgumentException("Field $key is not a simple field."); } return $field; @@ -138,7 +134,7 @@ public function getObjectFields(): array { $out = []; foreach ($this->fields->getArrayCopy() as $field) { - if ($field instanceof ObjectField) { + if ($field instanceof self) { $out[] = $field; } } diff --git a/src/V2/Parsing/Inference/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php new file mode 100644 index 00000000..a63fe087 --- /dev/null +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -0,0 +1,71 @@ +> $rawResponse Raw server response array. + * @param integer $indentLevel Level of indentation for rst display. + */ + public function __construct(array $rawResponse, int $indentLevel = 0) + { + parent::__construct($rawResponse, $indentLevel); + $this->value = array_key_exists('value', $rawResponse) ? $rawResponse['value'] : null; + if (is_int($this->value)) { + $this->value = (float) $this->value; + } + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + if (is_bool($this->value)) { + return $this->value ? 'True' : 'False'; + } + if (is_numeric($this->value)) { + return number_format((float) $this->value, 1, '.', ''); + } + return $this->value !== null ? (string) $this->value : ''; + } + + /** + * @return string|null String representation of the field value. + */ + public function getStringValue(): ?string + { + return null !== $this->value ? (string) $this->value : null; + } + + /** + * @return float|null Float representation of the field value. + */ + public function getFloatValue(): ?float + { + return null !== $this->value ? (float) $this->value : null; + } + + /** + * @return boolean|null Boolean representation of the field value. + */ + public function getBoolValue(): ?bool + { + return null !== $this->value ? (bool) $this->value : null; + } +} diff --git a/src/Parsing/V2/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php similarity index 57% rename from src/Parsing/V2/InferenceActiveOptions.php rename to src/V2/Parsing/Inference/InferenceActiveOptions.php index 743cc4c8..7d1e214e 100644 --- a/src/Parsing/V2/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -1,8 +1,12 @@ > $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/Parsing/V2/InferenceFile.php b/src/V2/Parsing/Inference/InferenceFile.php similarity index 60% rename from src/Parsing/V2/InferenceFile.php rename to src/V2/Parsing/Inference/InferenceFile.php index 20d1d0e1..e39bf6b0 100644 --- a/src/Parsing/V2/InferenceFile.php +++ b/src/V2/Parsing/Inference/InferenceFile.php @@ -1,11 +1,15 @@ > $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/Parsing/V2/InferenceJob.php b/src/V2/Parsing/Inference/InferenceJob.php similarity index 51% rename from src/Parsing/V2/InferenceJob.php rename to src/V2/Parsing/Inference/InferenceJob.php index 225c5697..4c288bd2 100644 --- a/src/Parsing/V2/InferenceJob.php +++ b/src/V2/Parsing/Inference/InferenceJob.php @@ -1,11 +1,15 @@ > $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/Parsing/V2/InferenceModel.php b/src/V2/Parsing/Inference/InferenceModel.php similarity index 50% rename from src/Parsing/V2/InferenceModel.php rename to src/V2/Parsing/Inference/InferenceModel.php index b11d1c64..d508b10d 100644 --- a/src/Parsing/V2/InferenceModel.php +++ b/src/V2/Parsing/Inference/InferenceModel.php @@ -1,11 +1,15 @@ > $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/Parsing/V2/RagMetadata.php b/src/V2/Parsing/Inference/RagMetadata.php similarity index 65% rename from src/Parsing/V2/RagMetadata.php rename to src/V2/Parsing/Inference/RagMetadata.php index a2dec186..b1916f3b 100644 --- a/src/Parsing/V2/RagMetadata.php +++ b/src/V2/Parsing/Inference/RagMetadata.php @@ -1,6 +1,8 @@ > $rawResponse Raw response from the server. */ public function __construct(array $rawResponse) { diff --git a/src/Parsing/V2/RawText.php b/src/V2/Parsing/Inference/RawText.php similarity index 55% rename from src/Parsing/V2/RawText.php rename to src/V2/Parsing/Inference/RawText.php index ac65075f..5b4be8f6 100644 --- a/src/Parsing/V2/RawText.php +++ b/src/V2/Parsing/Inference/RawText.php @@ -1,11 +1,17 @@ > $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 new file mode 100644 index 00000000..e0008988 --- /dev/null +++ b/src/V2/Parsing/Inference/RawTextPage.php @@ -0,0 +1,34 @@ +> $rawResponse JSON response from the server. + */ + public function __construct(array $rawResponse) + { + $this->content = $rawResponse['content']; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return $this->content ?? ''; + } +} diff --git a/src/Parsing/V2/Job.php b/src/V2/Parsing/Job/Job.php similarity index 60% rename from src/Parsing/V2/Job.php rename to src/V2/Parsing/Job/Job.php index d6701c73..982853c4 100644 --- a/src/Parsing/V2/Job.php +++ b/src/V2/Parsing/Job/Job.php @@ -1,9 +1,14 @@ > $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); } } @@ -103,17 +108,16 @@ public function __construct(array $serverResponse) * Parse a date string into a DateTime object. * * @param string|null $dateString Date string to parse. - * @return DateTime|null */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } try { return new DateTime($dateString); - } catch (Exception $e) { + } catch (Exception) { return null; } } diff --git a/src/Parsing/V2/JobResponse.php b/src/V2/Parsing/Job/JobResponse.php similarity index 59% rename from src/Parsing/V2/JobResponse.php rename to src/V2/Parsing/Job/JobResponse.php index 5f61841c..babc7259 100644 --- a/src/Parsing/V2/JobResponse.php +++ b/src/V2/Parsing/Job/JobResponse.php @@ -1,6 +1,10 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/Parsing/V2/JobWebhook.php b/src/V2/Parsing/Job/JobWebhook.php similarity index 56% rename from src/Parsing/V2/JobWebhook.php rename to src/V2/Parsing/Job/JobWebhook.php index 493ce67f..e12d5ccf 100644 --- a/src/Parsing/V2/JobWebhook.php +++ b/src/V2/Parsing/Job/JobWebhook.php @@ -1,9 +1,12 @@ > $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; } @@ -49,17 +52,16 @@ public function __construct(array $serverResponse) * Parse a date string into a DateTime object. * * @param string|null $dateString Date string to parse. - * @return DateTime|null */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } try { return new DateTime($dateString); - } catch (Exception $e) { + } catch (Exception) { return null; } } diff --git a/src/V2/Parsing/Search/ModelWebhook.php b/src/V2/Parsing/Search/ModelWebhook.php new file mode 100644 index 00000000..3ec8a33c --- /dev/null +++ b/src/V2/Parsing/Search/ModelWebhook.php @@ -0,0 +1,43 @@ +> $rawResponse + */ + public function __construct(array $rawResponse) + { + $this->id = $rawResponse['id']; + $this->name = $rawResponse['name']; + $this->url = $rawResponse['url']; + } + + public function __toString(): string + { + return ":Name: $this->name\n" + . ":ID: $this->id\n" + . ":URL: $this->url\n"; + } +} diff --git a/src/V2/Parsing/Search/Pagination.php b/src/V2/Parsing/Search/Pagination.php new file mode 100644 index 00000000..a3adf759 --- /dev/null +++ b/src/V2/Parsing/Search/Pagination.php @@ -0,0 +1,52 @@ +> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + $this->perPage = $rawResponse['per_page']; + $this->page = $rawResponse['page']; + $this->totalItems = $rawResponse['total_items']; + $this->totalPages = $rawResponse['total_pages']; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return ":Per Page: $this->perPage\n" + . ":Page: $this->page\n" + . ":Total Items: $this->totalItems\n" + . ":Total Pages: $this->totalPages\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchModel.php b/src/V2/Parsing/Search/SearchModel.php new file mode 100644 index 00000000..5a9d88a0 --- /dev/null +++ b/src/V2/Parsing/Search/SearchModel.php @@ -0,0 +1,55 @@ + List of webhooks associated with the model. + */ + public array $webhooks; + + /** + * @param array> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + $this->id = $rawResponse['id']; + $this->name = $rawResponse['name']; + $this->modelType = $rawResponse['model_type']; + $this->webhooks = array_map( + static fn($webhook) => new ModelWebhook($webhook), + $rawResponse['webhooks'] ?? [] + ); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return ":Name: $this->name\n" + . ":ID: $this->id\n" + . ":Model Type: $this->modelType\n" + . ":Webhooks: " . implode(', ', array_map(static fn($webhook) => $webhook->name, $this->webhooks)) . "\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchModels.php b/src/V2/Parsing/Search/SearchModels.php new file mode 100644 index 00000000..16d72a80 --- /dev/null +++ b/src/V2/Parsing/Search/SearchModels.php @@ -0,0 +1,47 @@ + + */ +class SearchModels extends ArrayObject implements Stringable +{ + /** + * @param array>> $prediction Raw prediction. + */ + public function __construct(array $prediction) + { + $models = array_map(static fn($entry) => new SearchModel($entry), $prediction); + + parent::__construct($models); + } + + /** + * Default string representation. + */ + public function __toString(): string + { + if ($this->count() === 0) { + return "\n"; + } + + $lines = []; + foreach ($this as $model) { + $lines[] = "* :Name: " . $model->name; + $lines[] = " :ID: " . $model->id; + $lines[] = " :Model Type: " . $model->modelType; + $lines[] = " :Webhooks: " . count($model->webhooks); + } + + return implode("\n", $lines) . "\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchResponse.php b/src/V2/Parsing/Search/SearchResponse.php new file mode 100644 index 00000000..6e0960ff --- /dev/null +++ b/src/V2/Parsing/Search/SearchResponse.php @@ -0,0 +1,50 @@ +> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + parent::__construct($rawResponse); + $this->models = new SearchModels($rawResponse['models']); + $this->pagination = new Pagination($rawResponse['pagination']); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return implode("\n", [ + 'Models', + '######', + (string) $this->models, + 'Pagination Metadata', + '###################', + (string) $this->pagination, + '', + ]); + } +} diff --git a/src/V2/Product/Classification/ClassificationClassifier.php b/src/V2/Product/Classification/ClassificationClassifier.php index 4e8d4be0..9e53fc91 100644 --- a/src/V2/Product/Classification/ClassificationClassifier.php +++ b/src/V2/Product/Classification/ClassificationClassifier.php @@ -1,13 +1,16 @@ > $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { $this->documentType = $rawPrediction['document_type']; - $this->extractionResponse = isset($rawPrediction['extraction_response']) ? - new InferenceResponse($rawPrediction['extraction_response']) : null; + $this->extractionResponse = isset($rawPrediction['extraction_response']) + ? new ExtractionResponse($rawPrediction['extraction_response']) : null; } /** diff --git a/src/V2/Product/Classification/ClassificationInference.php b/src/V2/Product/Classification/ClassificationInference.php index f559dc74..58fefb3a 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.php @@ -1,9 +1,11 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { @@ -30,7 +32,6 @@ public function __construct(array $rawResponse) */ /** * A prettier representation. - * @return string */ public function __toString(): string { diff --git a/src/V2/Product/Classification/ClassificationResponse.php b/src/V2/Product/Classification/ClassificationResponse.php index 95758c07..01d78391 100644 --- a/src/V2/Product/Classification/ClassificationResponse.php +++ b/src/V2/Product/Classification/ClassificationResponse.php @@ -1,8 +1,10 @@ > $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 9c9e8f7b..fda1e00b 100644 --- a/src/V2/Product/Classification/ClassificationResult.php +++ b/src/V2/Product/Classification/ClassificationResult.php @@ -1,11 +1,15 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Classification/Params/ClassificationParameters.php b/src/V2/Product/Classification/Params/ClassificationParameters.php index c3191c94..057f9e1c 100644 --- a/src/V2/Product/Classification/Params/ClassificationParameters.php +++ b/src/V2/Product/Classification/Params/ClassificationParameters.php @@ -1,8 +1,10 @@ |null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Crop/CropInference.php b/src/V2/Product/Crop/CropInference.php index 9eb13d07..d83717be 100644 --- a/src/V2/Product/Crop/CropInference.php +++ b/src/V2/Product/Crop/CropInference.php @@ -1,8 +1,10 @@ > $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 6a404012..49c5622a 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -1,18 +1,24 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { $this->location = new FieldLocation($rawResponse['location']); $this->objectType = $rawResponse['object_type']; - $this->extractionResponse = isset($rawResponse['extraction_response']) ? - new InferenceResponse($rawResponse['extraction_response']) : null; + $this->extractionResponse = isset($rawResponse['extraction_response']) + ? new ExtractionResponse($rawResponse['extraction_response']) : null; } /** * @return string String representation. */ - public function __toString() + public function __toString(): string { return "* :Location: $this->location\n :Object Type: $this->objectType"; } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the crop. + * @return ExtractedImage The extracted image. + */ + public function extractFromInputSource(LocalInputSource $inputSource): ExtractedImage + { + $cropper = new Crop($inputSource); + return $cropper->extractSingleCrop($this); + } } diff --git a/src/V2/Product/Crop/CropResponse.php b/src/V2/Product/Crop/CropResponse.php index cfd07e29..98b6b4f0 100644 --- a/src/V2/Product/Crop/CropResponse.php +++ b/src/V2/Product/Crop/CropResponse.php @@ -1,8 +1,10 @@ > $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 966b46af..ac6289e7 100644 --- a/src/V2/Product/Crop/CropResult.php +++ b/src/V2/Product/Crop/CropResult.php @@ -1,11 +1,18 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->crops = array_map(fn ($crop) => new CropItem($crop), $rawResponse['crops']); + $this->crops = array_map(static fn($crop) => new CropItem($crop), $rawResponse['crops']); } /** @@ -27,4 +34,14 @@ public function __toString(): string { return "Crops\n=====\n" . implode("\n", $this->crops); } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the pages. + * @return CropFiles The extracted PDFs. + */ + public function extractFromInputSource(LocalInputSource $inputSource): CropFiles + { + $cropper = new Crop($inputSource); + return $cropper->extractMultipleCrops($this->crops); + } } diff --git a/src/V2/Product/Crop/Params/CropParameters.php b/src/V2/Product/Crop/Params/CropParameters.php index f7547cc1..e7cdf652 100644 --- a/src/V2/Product/Crop/Params/CropParameters.php +++ b/src/V2/Product/Crop/Params/CropParameters.php @@ -1,8 +1,10 @@ |null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/Parsing/V2/Inference.php b/src/V2/Product/Extraction/ExtractionInference.php similarity index 55% rename from src/Parsing/V2/Inference.php rename to src/V2/Product/Extraction/ExtractionInference.php index 81dfecaa..bf4b5fb7 100644 --- a/src/Parsing/V2/Inference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -1,14 +1,17 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { parent::__construct($rawResponse); $this->activeOptions = new InferenceActiveOptions($rawResponse['active_options']); - $this->result = new InferenceResult($rawResponse['result']); + $this->result = new ExtractionResult($rawResponse['result']); } /** @@ -35,7 +38,6 @@ public function __construct(array $rawResponse) */ /** * A prettier representation. - * @return string */ public function __toString(): string { diff --git a/src/V2/Product/Extraction/ExtractionResponse.php b/src/V2/Product/Extraction/ExtractionResponse.php new file mode 100644 index 00000000..3705f419 --- /dev/null +++ b/src/V2/Product/Extraction/ExtractionResponse.php @@ -0,0 +1,32 @@ +> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + parent::__construct($rawResponse); + $this->inference = new ExtractionInference($rawResponse['inference']); + } +} diff --git a/src/Parsing/V2/InferenceResult.php b/src/V2/Product/Extraction/ExtractionResult.php similarity index 50% rename from src/Parsing/V2/InferenceResult.php rename to src/V2/Product/Extraction/ExtractionResult.php index 78ccaabd..2a1ae194 100644 --- a/src/Parsing/V2/InferenceResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -1,13 +1,18 @@ > $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/Input/DataSchema.php b/src/V2/Product/Extraction/Params/DataSchema.php similarity index 70% rename from src/Input/DataSchema.php rename to src/V2/Product/Extraction/Params/DataSchema.php index c86b1cb7..98d1a0b3 100644 --- a/src/Input/DataSchema.php +++ b/src/V2/Product/Extraction/Params/DataSchema.php @@ -1,13 +1,19 @@ >|string|DataSchema $dataSchema Raw server response array. * @throws InvalidArgumentException Throws if the data schema is invalid. */ - public function __construct(DataSchema|array|string $dataSchema) + public function __construct(self|array|string $dataSchema) { - if (gettype($dataSchema) == 'string') { + if (gettype($dataSchema) === 'string') { $jsonData = json_decode($dataSchema, true); - } elseif (gettype($dataSchema) == 'array') { + } elseif (gettype($dataSchema) === 'array') { $jsonData = $dataSchema; } else { - if (get_class($dataSchema) == DataSchema::class) { + if ($dataSchema::class === self::class) { $this->replace = $dataSchema->replace; return; } @@ -35,7 +41,7 @@ public function __construct(DataSchema|array|string $dataSchema) } /** - * @return array JSON representation. + * @return array> JSON representation. */ public function toJson(): array { @@ -54,7 +60,7 @@ private static function fixLineSpaces(string $line): string } $i = 0; foreach (str_split($line) as $char) { - if ($char == ' ') { + if ($char === ' ') { $i++; continue; } @@ -71,7 +77,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(self::fixLineSpaces(...), $lines)) . "\n"; } /** diff --git a/src/Parsing/V2/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php similarity index 53% rename from src/Parsing/V2/DataSchemaActiveOption.php rename to src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index 93235543..871d592a 100644 --- a/src/Parsing/V2/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -1,11 +1,15 @@ > $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/Input/DataSchemaField.php b/src/V2/Product/Extraction/Params/DataSchemaField.php similarity index 59% rename from src/Input/DataSchemaField.php rename to src/V2/Product/Extraction/Params/DataSchemaField.php index 0094d86d..a281ce68 100644 --- a/src/Input/DataSchemaField.php +++ b/src/V2/Product/Extraction/Params/DataSchemaField.php @@ -1,11 +1,15 @@ >|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 { @@ -101,7 +105,7 @@ public function toJson(): array public function __toString(): string { - return json_encode( + return (string) json_encode( $this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ); diff --git a/src/V2/Product/Extraction/Params/DataSchemaReplace.php b/src/V2/Product/Extraction/Params/DataSchemaReplace.php new file mode 100644 index 00000000..cc5bfd82 --- /dev/null +++ b/src/V2/Product/Extraction/Params/DataSchemaReplace.php @@ -0,0 +1,57 @@ +> $rawResponse Raw server response array. + * @throws InvalidArgumentException Throws if the fields array is empty or the Data schema is incorrect. + */ + public function __construct(array $rawResponse) + { + if ( + !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), $rawResponse['fields']); + } + + /** + * @return array> JSON representation. + */ + public function toJson(): array + { + return [ 'fields' => array_map(static fn($field) => $field->toJson(), $this->fields)]; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return (string) json_encode( + $this->toJson(), + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES + ); + } +} diff --git a/src/V2/Product/Extraction/Params/ExtractionParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php new file mode 100644 index 00000000..5deaf086 --- /dev/null +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -0,0 +1,91 @@ +|null $webhookIds 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. + */ + public function __construct( + string $modelId, + public ?bool $rag = null, + public ?bool $rawText = null, + public ?bool $polygon = null, + public ?bool $confidence = null, + ?string $alias = null, + ?array $webhookIds = null, + ?string $textContext = null, + DataSchema|string|array|null $dataSchema = null, + ) { + parent::__construct($modelId, $alias, $webhookIds); + if (isset($textContext)) { + $this->textContext = $textContext; + } + if (isset($dataSchema)) { + $this->dataSchema = new DataSchema($dataSchema); + } + } + + /** + * @return array> Hash representation. + */ + public function asHash(): array + { + $outHash = parent::asHash(); + if (isset($this->rag)) { + $outHash['rag'] = $this->rag ? 'true' : 'false'; + } + if (isset($this->rawText)) { + $outHash['raw_text'] = $this->rawText ? 'true' : 'false'; + } + if (isset($this->polygon)) { + $outHash['polygon'] = $this->polygon ? 'true' : 'false'; + } + if (isset($this->confidence)) { + $outHash['confidence'] = $this->confidence ? 'true' : 'false'; + } + if (isset($this->textContext)) { + $outHash['text_context'] = $this->textContext; + } + if (isset($this->dataSchema)) { + $outHash['data_schema'] = (string) ($this->dataSchema); + } + return $outHash; + } +} diff --git a/src/V2/Product/Ocr/OcrInference.php b/src/V2/Product/Ocr/OcrInference.php index 6c6a5e4c..d5dbaa44 100644 --- a/src/V2/Product/Ocr/OcrInference.php +++ b/src/V2/Product/Ocr/OcrInference.php @@ -1,11 +1,13 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Ocr/OcrPage.php b/src/V2/Product/Ocr/OcrPage.php index 55293240..29a96e73 100644 --- a/src/V2/Product/Ocr/OcrPage.php +++ b/src/V2/Product/Ocr/OcrPage.php @@ -1,14 +1,18 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->words = array_map(fn ($word) => new OcrWord($word), $rawResponse['words']); + $this->words = array_map(static fn($word) => new OcrWord($word), $rawResponse['words']); $this->content = $rawResponse['content']; } @@ -37,6 +41,6 @@ public function __toString(): string $ocrWords .= implode("\n\n", $this->words); } - return "OCR Words\n---------$ocrWords\n\n:Content: $this->content"; + return "Ocr Words\n---------$ocrWords\n\n:Content: $this->content"; } } diff --git a/src/V2/Product/Ocr/OcrResponse.php b/src/V2/Product/Ocr/OcrResponse.php index 1861964e..2ca6c8b0 100644 --- a/src/V2/Product/Ocr/OcrResponse.php +++ b/src/V2/Product/Ocr/OcrResponse.php @@ -1,16 +1,18 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Ocr/OcrResult.php b/src/V2/Product/Ocr/OcrResult.php index 56b60128..c0e39c72 100644 --- a/src/V2/Product/Ocr/OcrResult.php +++ b/src/V2/Product/Ocr/OcrResult.php @@ -1,11 +1,17 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->pages = array_map(fn ($page) => new OcrPage($page), $rawResponse['pages']); + $this->pages = array_map(static fn($page) => new OcrPage($page), $rawResponse['pages']); } /** @@ -25,7 +31,7 @@ public function __construct(array $rawResponse) */ public function __toString(): string { - $str = "OCR Result\n##########\n"; + $str = "Ocr Result\n##########\n"; $i = 1; foreach ($this->pages as $page) { diff --git a/src/V2/Product/Ocr/OcrWord.php b/src/V2/Product/Ocr/OcrWord.php index 48c070ab..37d8c6c8 100644 --- a/src/V2/Product/Ocr/OcrWord.php +++ b/src/V2/Product/Ocr/OcrWord.php @@ -1,13 +1,16 @@ > $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 index b86dd24e..51423730 100644 --- a/src/V2/Product/Ocr/Params/OcrParameters.php +++ b/src/V2/Product/Ocr/Params/OcrParameters.php @@ -1,8 +1,10 @@ |null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Split/Params/SplitParameters.php b/src/V2/Product/Split/Params/SplitParameters.php index 7d0d61f2..8de1262e 100644 --- a/src/V2/Product/Split/Params/SplitParameters.php +++ b/src/V2/Product/Split/Params/SplitParameters.php @@ -1,8 +1,10 @@ |null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Split/SplitInference.php b/src/V2/Product/Split/SplitInference.php index f1071710..3acdab73 100644 --- a/src/V2/Product/Split/SplitInference.php +++ b/src/V2/Product/Split/SplitInference.php @@ -1,8 +1,10 @@ > $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 284f1712..e89fec53 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -1,17 +1,23 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { $this->pageRange = $rawResponse['page_range']; $this->documentType = $rawResponse['document_type']; - $this->extractionResponse = isset($rawResponse['extraction_response']) ? - new InferenceResponse($rawResponse['extraction_response']) : null; + $this->extractionResponse = isset($rawResponse['extraction_response']) + ? new ExtractionResponse($rawResponse['extraction_response']) : null; } /** @@ -46,4 +52,16 @@ public function __toString(): string return "* :Page Range: $pageRangeStr\n :Document Type: $this->documentType"; } + + /** + * Extracts a single page from the input source based on the specified page range. + * + * @param LocalInputSource $inputSource The input source from which to extract the page. + * @return ExtractedPdf The extracted PDF. + */ + public function extractFromInputSource(LocalInputSource $inputSource): ExtractedPdf + { + $splitter = new Split($inputSource); + return $splitter->extractSingleSplit($this->pageRange); + } } diff --git a/src/V2/Product/Split/SplitResponse.php b/src/V2/Product/Split/SplitResponse.php index d012af8a..ee435b5e 100644 --- a/src/V2/Product/Split/SplitResponse.php +++ b/src/V2/Product/Split/SplitResponse.php @@ -1,8 +1,10 @@ > $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 aa61bb46..a34919e3 100644 --- a/src/V2/Product/Split/SplitResult.php +++ b/src/V2/Product/Split/SplitResult.php @@ -1,11 +1,20 @@ > $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->splits = array_map(fn ($split) => new SplitRange($split), $rawResponse['splits']); + $this->splits = array_map(static fn($split) => new SplitRange($split), $rawResponse['splits']); } /** @@ -29,4 +38,15 @@ public function __toString(): string return "Splits\n======\n$splitsStr"; } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the pages. + * @return SplitFiles The extracted PDFs. + * @throws ImagickException Throws if the image can't be processed. + */ + public function extractFromInputSource(LocalInputSource $inputSource): SplitFiles + { + $splitter = new Split($inputSource); + return $splitter->extractMultipleSplits(array_map(static fn(SplitRange $split) => $split->pageRange, $this->splits)); + } } diff --git a/src/version.php b/src/version.php index 2ba69ea7..56855b44 100644 --- a/src/version.php +++ b/src/version.php @@ -1,5 +1,7 @@ envClient = new Client(); $this->multiReceiptsDetectorPath = ( - \TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/response_v1/complete.json" + TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/response_v1/complete.json" ); $this->failedJobPath = ( - \TestingUtilities::getV1DataDir() . "/async/get_failed_job_error.json" + TestingUtilities::getV1DataDir() . "/async/get_failed_job_error.json" ); } @@ -47,45 +51,45 @@ protected function tearDown(): void putenv('MINDEE_API_KEY=' . $this->oldKey); } - public function testParsePathWithoutToken() + public function testParsePathWithoutToken(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->emptyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->emptyClient->parse(InvoiceV4::class, $inputDoc); } - public function testParsePathWithEnvToken() + public function testParsePathWithEnvToken(): void { - $this->expectException(MindeeHttpException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->envClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->envClient->parse(InvoiceV4::class, $inputDoc); } - public function testParsePathWithWrongFileType() + public function testParsePathWithWrongFileType(): void { - $this->expectException(Mindee\Error\MindeeMimeTypeException::class); + $this->expectException(MindeeMimeTypeException::class); - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() ."/receipt.txt"); + new PathInput(TestingUtilities::getFileTypesDir() . "/receipt.txt"); } - public function testParsePathWithWrongToken() + public function testParsePathWithWrongToken(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->dummyClient->parse(InvoiceV4::class, $inputDoc); } - public function testInterfaceVersion() + public function testInterfaceVersion(): void { $dummyEndpoint = $this->dummyClient->createEndpoint("dummy", "dummy", "1.1"); - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $predictOptions = new PredictMethodOptions(); - $this->assertEquals("1.1", $dummyEndpoint->settings->version); + self::assertSame("1.1", $dummyEndpoint->settings->version); - $this->expectException(MindeeHTTPClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse( GeneratedV1::class, $inputDoc, @@ -93,66 +97,66 @@ public function testInterfaceVersion() ); } - public function testCutOptions() + public function testCutOptions(): void { - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeeHttpClientException::class); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $this->expectException(MindeeV1HttpException::class); $pageOptions = new PageOptions(range(0, 4)); $this->dummyClient->parse(ReceiptV5::class, $inputDoc, null, $pageOptions); - $this->assertEquals(5, $inputDoc->getPageCount()); + self::assertSame(5, $inputDoc->getPageCount()); } - public function testAsyncWrongInitialDelay() + public function testAsyncWrongInitialDelay(): void { $this->expectException(MindeeApiException::class); $asyncParseOptions = new PollingOptions(); $asyncParseOptions->setInitialDelaySec(0); } - public function testAsyncWrongPollingDelay() + public function testAsyncWrongPollingDelay(): void { $this->expectException(MindeeApiException::class); $asyncParseOptions = new PollingOptions(); $asyncParseOptions->setDelaySec(0); } - public function testPredictOptionsWrongInputType() + public function testPredictOptionsWrongInputType(): void { $pageOptions = new PageOptions([0, 1]); - $this->assertFalse($pageOptions->isEmpty()); + self::assertFalse($pageOptions->isEmpty()); $predictOptions = new PredictMethodOptions(); $predictOptions->setPageOptions($pageOptions); - $urlInputSource = $this->dummyClient->sourceFromUrl("https://dummy"); + $urlInputSource = new UrlInputSource("https://dummy"); $this->expectException(MindeeApiException::class); $this->dummyClient->parse(InvoiceV4::class, $urlInputSource, $predictOptions); $this->expectException(MindeeApiException::class); $this->dummyClient->enqueue(InvoiceSplitterV1::class, $urlInputSource, $predictOptions); } - public function testPredictOptionsValidInputType() + public function testPredictOptionsValidInputType(): void { $predictOptions = new PredictMethodOptions(); - $this->assertTrue($predictOptions->pageOptions->isEmpty()); - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); - $this->expectException(MindeeHttpClientException::class); + self::assertTrue($predictOptions->pageOptions->isEmpty()); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse(InvoiceV4::class, $inputDoc, $predictOptions); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceSplitterV1::class, $inputDoc, $predictOptions); } - public function testLoadLocalResponse() + public function testLoadLocalResponse(): void { $localResponse = new LocalResponse($this->multiReceiptsDetectorPath); $res = $this->dummyClient->loadPrediction(MultiReceiptsDetectorV1::class, $localResponse); - $this->assertNotNull($res); - $this->assertEquals(1, $res->document->nPages); + self::assertNotNull($res); + self::assertSame(1, $res->document->nPages); } - public function testLoadFailedLocalResponse() + public function testLoadFailedLocalResponse(): void { $localResponse = new LocalResponse($this->failedJobPath); $res = $this->dummyClient->loadPrediction(InvoiceV4::class, $localResponse); - $this->assertNotNull($res); - $this->assertEquals("failed", $res->job->status); + self::assertNotNull($res); + self::assertSame("failed", $res->job->status); } } diff --git a/tests/CustomSleepMixinTest.php b/tests/CustomSleepMixinTest.php index 5e8cc0cf..508d835d 100644 --- a/tests/CustomSleepMixinTest.php +++ b/tests/CustomSleepMixinTest.php @@ -1,6 +1,9 @@ customSleep(1); $elapsed = microtime(true) - $start; - $this->assertGreaterThanOrEqual($lowerBound, $elapsed); - $this->assertLessThanOrEqual($upperBound, $elapsed); + self::assertGreaterThanOrEqual($lowerBound, $elapsed); + self::assertLessThanOrEqual($upperBound, $elapsed); } - public function testCustomSleep0dot33Seconds(): void { + public function testCustomSleep0dot33Seconds(): void + { $lowerBound = 0.33; $upperBound = 0.43; $start = microtime(true); $this->customSleep(0.33); $elapsed = microtime(true) - $start; - $this->assertGreaterThanOrEqual($lowerBound, $elapsed); - $this->assertLessThanOrEqual($upperBound, $elapsed); + self::assertGreaterThanOrEqual($lowerBound, $elapsed); + self::assertLessThanOrEqual($upperBound, $elapsed); } - public function testCustomSleep2Seconds(): void { + public function testCustomSleep2Seconds(): void + { $lowerBound = 2; $upperBound = 2.1; $start = microtime(true); $this->customSleep(2); $elapsed = microtime(true) - $start; - $this->assertGreaterThanOrEqual($lowerBound, $elapsed); - $this->assertLessThanOrEqual($upperBound, $elapsed); + self::assertGreaterThanOrEqual($lowerBound, $elapsed); + self::assertLessThanOrEqual($upperBound, $elapsed); } - public function testCustomSleep1dot5Seconds(): void { + public function testCustomSleep1dot5Seconds(): void + { $lowerBound = 1.5; $upperBound = 1.6; $start = microtime(true); $this->customSleep(1.5); $elapsed = microtime(true) - $start; - $this->assertGreaterThanOrEqual($lowerBound, $elapsed); - $this->assertLessThanOrEqual($upperBound, $elapsed); + self::assertGreaterThanOrEqual($lowerBound, $elapsed); + self::assertLessThanOrEqual($upperBound, $elapsed); } - public function testCustomSleep0Seconds(): void { + public function testCustomSleep0Seconds(): void + { $start = microtime(true); $this->customSleep(0); $elapsed = microtime(true) - $start; - $this->assertLessThanOrEqual(0.0001, $elapsed); + self::assertLessThanOrEqual(0.0001, $elapsed); } - public function testCustomSleepMinus1Seconds(): void { + public function testCustomSleepMinus1Seconds(): void + { $start = microtime(true); $this->customSleep(-1); $elapsed = microtime(true) - $start; - $this->assertLessThanOrEqual(0.0001, $elapsed); + self::assertLessThanOrEqual(0.0001, $elapsed); } } diff --git a/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php index 766d8016..09431aae 100644 --- a/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php +++ b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php @@ -1,40 +1,50 @@ expectException(MindeeUnhandledException::class); - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); new ImageExtractor($inputObj); } - public function testNoPdfExtractor() + public function testNoPdfExtractor(): void { $this->expectException(MindeeUnhandledException::class); - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); new PdfExtractor($inputObj); } - public function testNoExtractedImage() + public function testNoExtractedImage(): void { $this->expectException(MindeeUnhandledException::class); - $inputImage = ""; + if (!class_exists('Imagick')) { + class_alias(DummyImagick::class, 'Imagick'); + } + + $inputImage = new Imagick(); $filename = "dummy"; $saveFormat = "pdf"; new ExtractedImage($inputImage, $filename, $saveFormat, 0, 0); } - public function testNoExtractedPdf() + public function testNoExtractedPdf(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; diff --git a/tests/Dependencies/DependencyCheckerPdfTest.php b/tests/Dependencies/DependencyCheckerPdfTest.php index ff3f59b3..456f624f 100644 --- a/tests/Dependencies/DependencyCheckerPdfTest.php +++ b/tests/Dependencies/DependencyCheckerPdfTest.php @@ -1,22 +1,28 @@ expectNotToPerformAssertions(); DependencyChecker::isGhostscriptAvailable(); } - public function testImageMagickDependency() { + public function testImageMagickDependency(): void + { $this->expectNotToPerformAssertions(); DependencyChecker::isImageMagickAvailable(); } - public function testImageMagickPolicy() { + public function testImageMagickPolicy(): void + { $this->expectNotToPerformAssertions(); DependencyChecker::isImageMagickPolicyAllowed(); } diff --git a/tests/Geometry/BBoxTest.php b/tests/Geometry/BBoxTest.php index bb182887..1caa7fa2 100644 --- a/tests/Geometry/BBoxTest.php +++ b/tests/Geometry/BBoxTest.php @@ -1,5 +1,7 @@ assertNull($bbox); + self::assertNull($bbox); } - public function testWith1PolygonAndANullPolygonMustGetPolygon() + public function testWith1PolygonAndANullPolygonMustGetPolygon(): void { $polygons = []; $polygons[] = new Polygon( @@ -26,25 +28,25 @@ public function testWith1PolygonAndANullPolygonMustGetPolygon() $polygons[] = null; $bbox = BBoxUtils::generateBBoxFromPolygons($polygons); - $this->assertEquals(0.442, $bbox->getMinY()); - $this->assertEquals(0.081, $bbox->getMinX()); - $this->assertEquals(0.451, $bbox->getMaxY()); - $this->assertEquals(0.15, $bbox->getMaxX()); + self::assertSame(0.442, $bbox->getMinY()); + self::assertSame(0.081, $bbox->getMinX()); + self::assertSame(0.451, $bbox->getMaxY()); + self::assertSame(0.15, $bbox->getMaxX()); } - public function testWithOnePolygonMustGetValidBBox() + public function testWithOnePolygonMustGetValidBBox(): void { $polygon = new Polygon( [new Point(0.081, 0.442), new Point(0.15, 0.442), new Point(0.15, 0.451), new Point(0.081, 0.451)] ); $bbox = BBoxUtils::generateBBoxFromPolygon($polygon); - $this->assertEquals(0.442, $bbox->getMinY()); - $this->assertEquals(0.081, $bbox->getMinX()); - $this->assertEquals(0.451, $bbox->getMaxY()); - $this->assertEquals(0.15, $bbox->getMaxX()); + self::assertSame(0.442, $bbox->getMinY()); + self::assertSame(0.081, $bbox->getMinX()); + self::assertSame(0.451, $bbox->getMaxY()); + self::assertSame(0.15, $bbox->getMaxX()); } - public function testWithTwoPolygonsMustGetValidBBox() + public function testWithTwoPolygonsMustGetValidBBox(): void { $polygon1 = new Polygon( [new Point(0.081, 0.442), new Point(0.15, 0.442), new Point(0.15, 0.451), new Point(0.081, 0.451)] @@ -54,20 +56,20 @@ public function testWithTwoPolygonsMustGetValidBBox() ); $polygons = [$polygon1, $polygon2]; $bbox = BBoxUtils::generateBBoxFromPolygons($polygons); - $this->assertEquals(0.442, $bbox->getMinY()); - $this->assertEquals(0.081, $bbox->getMinX()); - $this->assertEquals(0.451, $bbox->getMaxY()); - $this->assertEquals(0.26, $bbox->getMaxX()); + self::assertSame(0.442, $bbox->getMinY()); + self::assertSame(0.081, $bbox->getMinX()); + self::assertSame(0.451, $bbox->getMaxY()); + self::assertSame(0.26, $bbox->getMaxX()); } - public function testMerge2BboxMustGetValidBBox() + public function testMerge2BboxMustGetValidBBox(): void { $bbox1 = new BBox(0.081, 0.15, 0.442, 0.451); $bbox2 = new BBox(0.157, 0.26, 0.442, 0.451); $mergedBBoxes = BBoxUtils::mergeBBoxes([$bbox1, $bbox2]); - $this->assertEquals(0.442, $mergedBBoxes->getMinY()); - $this->assertEquals(0.081, $mergedBBoxes->getMinX()); - $this->assertEquals(0.451, $mergedBBoxes->getMaxY()); - $this->assertEquals(0.26, $mergedBBoxes->getMaxX()); + self::assertSame(0.442, $mergedBBoxes->getMinY()); + self::assertSame(0.081, $mergedBBoxes->getMinX()); + self::assertSame(0.451, $mergedBBoxes->getMaxY()); + self::assertSame(0.26, $mergedBBoxes->getMaxX()); } } diff --git a/tests/Geometry/PolygonUtilsTest.php b/tests/Geometry/PolygonUtilsTest.php index ce5b3c2e..b338427e 100644 --- a/tests/Geometry/PolygonUtilsTest.php +++ b/tests/Geometry/PolygonUtilsTest.php @@ -1,5 +1,7 @@ assertEquals($this->polygonWhichIsNotRectangle->getCentroid(), new Point(0.149, 0.538)); + self::assertEquals(new Point(0.149, 0.538), $this->polygonWhichIsNotRectangle->getCentroid()); } - public function testGivenAValidPolygonMustGetTheMinX() + public function testGivenAValidPolygonMustGetTheMinX(): void { - $this->assertEquals(0.123, $this->polygonWhichIsNotRectangle->getMinX()); + self::assertSame(0.123, $this->polygonWhichIsNotRectangle->getMinX()); } - public function testGivenAValidPolygonMustGetTheMinY() + public function testGivenAValidPolygonMustGetTheMinY(): void { - $this->assertEquals(0.53, $this->polygonWhichIsNotRectangle->getMinY()); + self::assertSame(0.53, $this->polygonWhichIsNotRectangle->getMinY()); } - public function testGivenAValidPolygonMustGetTheMaxX() + public function testGivenAValidPolygonMustGetTheMaxX(): void { - $this->assertEquals(0.175, $this->polygonWhichIsNotRectangle->getMaxX()); + self::assertSame(0.175, $this->polygonWhichIsNotRectangle->getMaxX()); } - public function testGivenAValidPolygonMustGetTheMaxY() + public function testGivenAValidPolygonMustGetTheMaxY(): void { - $this->assertEquals(0.546, $this->polygonWhichIsNotRectangle->getMaxY()); + self::assertSame(0.546, $this->polygonWhichIsNotRectangle->getMaxY()); } - public function testMergePolygonsWithTwoNotNullMustGetAValidPolygon() + public function testMergePolygonsWithTwoNotNullMustGetAValidPolygon(): void { $mergedPolygon = PolygonUtils::merge($this->polygon1, $this->polygon2); - $this->assertEquals(0.442, $mergedPolygon->getMinY()); - $this->assertEquals(0.081, $mergedPolygon->getMinX()); - $this->assertEquals(0.451, $mergedPolygon->getMaxY()); - $this->assertEquals(0.26, $mergedPolygon->getMaxX()); + self::assertSame(0.442, $mergedPolygon->getMinY()); + self::assertSame(0.081, $mergedPolygon->getMinX()); + self::assertSame(0.451, $mergedPolygon->getMaxY()); + self::assertSame(0.26, $mergedPolygon->getMaxX()); } - public function testMergeWithNullPolygonMustThrow() + public function testMergeWithNullPolygonMustThrow(): void { $this->expectException(TypeError::class); PolygonUtils::merge(null, null); } - public function testMergeWith1PolygonAndANullPolygonMustGetPolygon() + public function testMergeWith1PolygonAndANullPolygonMustGetPolygon(): void { $mergedPolygon = PolygonUtils::merge($this->polygon1, new Polygon([])); - $this->assertEquals(0.442, $mergedPolygon->getMinY()); - $this->assertEquals(0.081, $mergedPolygon->getMinX()); - $this->assertEquals(0.451, $mergedPolygon->getMaxY()); - $this->assertEquals(0.15, $mergedPolygon->getMaxX()); + self::assertSame(0.442, $mergedPolygon->getMinY()); + self::assertSame(0.081, $mergedPolygon->getMinX()); + self::assertSame(0.451, $mergedPolygon->getMaxY()); + self::assertSame(0.15, $mergedPolygon->getMaxX()); } } diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 45130ca9..3a8daa95 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -1,25 +1,30 @@ oldKey); $filesToDelete = [ - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress100.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress85.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress50.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress10.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress1.jpg", - \TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", - \TestingUtilities::getRootDataDir() . "/output/not_compressed_multipage.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", - \TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf" + TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", + TestingUtilities::getRootDataDir() . "/output/compress100.jpg", + TestingUtilities::getRootDataDir() . "/output/compress85.jpg", + TestingUtilities::getRootDataDir() . "/output/compress50.jpg", + TestingUtilities::getRootDataDir() . "/output/compress10.jpg", + TestingUtilities::getRootDataDir() . "/output/compress1.jpg", + TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", + TestingUtilities::getRootDataDir() . "/output/not_compressed_multipage.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", + TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf", ]; foreach ($filesToDelete as $file) { @@ -64,62 +69,59 @@ protected function tearDown(): void } - public function testPDFCountPages() + public function testPdfCountPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->assertEquals(12, $inputObj->getPageCount()); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFReconstructOK() + public function testPdfReconstructOK(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); - $this->assertEquals(5, $inputObj->getPageCount()); + self::assertSame(5, $inputObj->getPageCount()); } - public function testPDFReadContents() + public function testPdfReadContents(): void { - $inputDoc = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $contents = $inputDoc->readContents(); - $this->assertEquals("multipage.pdf", $contents[0]); + self::assertSame("multipage.pdf", $contents[0]); } /** - * @dataProvider pageIndexesProvider + * @dataProvider providePdfCutNPagesCases */ - public function testPDFCutNPages(array $indexes) + public function testPdfCutNPages(array $indexes): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions($indexes, KEEP_ONLY, 2)); try { - $basePdf = new FPDI(); - $cutPdf = new FPDI(); + $basePdf = new Fpdi(); + $cutPdf = new Fpdi(); $pageCountCutPdf = $cutPdf->setSourceFile( - \TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf" + TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf" ); $pageCountBasePdf = $basePdf->setSourceFile($inputObj->fileObject->getFilename()); $basePdf->Close(); $cutPdf->Close(); - $this->assertEquals(count($indexes), $inputObj->getPageCount()); - $this->assertEquals($pageCountCutPdf, $pageCountBasePdf); + self::assertSame(count($indexes), $inputObj->getPageCount()); + self::assertSame($pageCountCutPdf, $pageCountBasePdf); - $basePdf = new FPDI(); - $cutPdf = new FPDI(); + $basePdf = new Fpdi(); + $cutPdf = new Fpdi(); for ($pageNumber = 0; $pageNumber < $pageCountBasePdf; $pageNumber++) { - $cutPdf->setSourceFile(\TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf"); + $cutPdf->setSourceFile(TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf"); $basePdf->setSourceFile($inputObj->fileObject->getFilename()); $cutPdf->AddPage(); $cutPdf->useTemplate($cutPdf->importPage($pageNumber + 1)); $basePdf->AddPage(); $basePdf->useTemplate($basePdf->importPage($pageNumber + 1)); - // TODO: comparing extracted page bytes content turns out to be unreliable when using FPDF. - // This will be left here until a better solution is found within the limitations of licensing. - // $this->assertEquals($cutPdf->Output('', 'S'), $basePdf->Output('', 'S')); } $basePdf->Close(); $cutPdf->Close(); - } catch (PdfParserException | PdfReaderException $e) { - throw new MindeePDFException( + } catch (PdfParserException|PdfReaderException $e) { + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -127,145 +129,148 @@ public function testPDFCutNPages(array $indexes) } } - public function pageIndexesProvider() + public static function providePdfCutNPagesCases(): iterable { return [[[0]], [[0, -2]], [[0, -2, -1]]]; } - public function testPDFKeep5FirstPages() + public function testPdfKeep5FirstPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); - $this->assertEquals(5, $inputObj->getPageCount()); + self::assertSame(5, $inputObj->getPageCount()); } - public function testPDFKeepInvalidPages() + public function testPdfKeepInvalidPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 17], KEEP_ONLY, 2)); - $this->assertEquals(2, $inputObj->getPageCount()); + self::assertSame(2, $inputObj->getPageCount()); } - public function testPDFRemove5LastPages() + public function testPdfRemove5LastPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([-5, -4, -3, -2, -1], REMOVE, 2)); - $this->assertEquals(7, $inputObj->getPageCount()); + self::assertSame(7, $inputObj->getPageCount()); } - public function testPDFRemove5FirstPages() + public function testPdfRemove5FirstPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], REMOVE, 2)); - $this->assertEquals(7, $inputObj->getPageCount()); + self::assertSame(7, $inputObj->getPageCount()); } - public function testPDFRemoveInvalidPages() + public function testPdfRemoveInvalidPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([16], REMOVE, 2)); - $this->assertEquals(12, $inputObj->getPageCount()); + self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFKeepNoPages() + public function testPdfKeepNoPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeePDFException::class); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $this->expectException(MindeePdfException::class); $inputObj->applyPageOptions(new PageOptions([], KEEP_ONLY, 2)); } - public function testPDFRemoveAllPages() + public function testPdfRemoveAllPages(): void { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeePDFException::class); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $this->expectException(MindeePdfException::class); $pageOptions = new PageOptions(range(0, $inputObj->getPageCount() - 1), REMOVE, 2); $inputObj->applyPageOptions(pageOptions: $pageOptions); } - public function testPDFInputFromFile() + public function testPdfInputFromFile(): void { - $fileContents = file_get_contents(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $fileRef = fopen(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf", "r"); + $fileContents = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $fileRef = fopen(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf", "r"); $inputDoc = new FileInput($fileRef); $contents = $inputDoc->readContents(); - $this->assertEquals("multipage.pdf", $contents[0]); - $this->assertEquals($fileContents, $contents[1]); + self::assertSame("multipage.pdf", $contents[0]); + self::assertSame($fileContents, $contents[1]); } - public function testPDFInputFromBytes() + public function testPdfInputFromBytes(): void { - $pdfBytes = file_get_contents(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $pdfBytes = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputDoc = new BytesInput($pdfBytes, "dummy.pdf"); $contents = $inputDoc->readContents(); - $this->assertEquals("dummy.pdf", $contents[0]); - $this->assertEquals($pdfBytes, $contents[1]); + self::assertSame("dummy.pdf", $contents[0]); + self::assertSame($pdfBytes, $contents[1]); } - public function testInputFromRawb64String() + public function testInputFromRawb64String(): void { - $pdfBytes = file_get_contents(\TestingUtilities::getFileTypesDir() . "/receipt.txt"); + $pdfBytes = file_get_contents(TestingUtilities::getFileTypesDir() . "/receipt.txt"); $inputDoc = new Base64Input($pdfBytes, "dummy.pdf"); $contents = $inputDoc->readContents(); - $this->assertEquals("dummy.pdf", $contents[0]); - $this->assertEquals(str_replace("\n", "", $pdfBytes), str_replace("\n", "", base64_encode($contents[1]))); + self::assertSame("dummy.pdf", $contents[0]); + self::assertSame(str_replace("\n", "", $pdfBytes), str_replace("\n", "", base64_encode($contents[1]))); } - public function testShouldNotRaiseMimeErrorForBrokenFixablePdf() + public function testShouldNotRaiseMimeErrorForBrokenFixablePdf(): void { $this->expectNotToPerformAssertions(); - $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); + $pathInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf'); + $pathInput->fixPdf(); } - public function testShouldRaiseErrorForBrokenUnfixablePdf() + public function testShouldRaiseErrorForBrokenUnfixablePdf(): void { $this->expectException(MindeeSourceException::class); - $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); + $pathInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf'); + $pathInput->fixPdf(); } - public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf() + public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf(): void { - $sourceDocOriginal = $this->dummyClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' + $sourceDocOriginal = new PathInput( + TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' ); - $sourceDocFixed = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); - $this->assertEquals($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); + $sourceDocFixed = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf'); + $sourceDocFixed->fixPdf(); + self::assertSame($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); } - public function testImageQualityCompressionFromInputSource() + public function testImageQualityCompressionFromInputSource(): void { - $receiptInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $receiptInput->compress(80); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", file_get_contents($receiptInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); - $sizeCompressed = filesize(\TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg"); - $this->assertGreaterThan($sizeCompressed, $sizeOriginal); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg"); + self::assertGreaterThan($sizeCompressed, $sizeOriginal); } - public function testDirectImageQualityCompression() + public function testDirectImageQualityCompression(): void { - $receiptInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $compresses = [ 100 => ImageCompressor::compress($receiptInput->fileObject, 100), 85 => ImageCompressor::compress($receiptInput->fileObject), 50 => ImageCompressor::compress($receiptInput->fileObject, 50), 10 => ImageCompressor::compress($receiptInput->fileObject, 10), - 1 => ImageCompressor::compress($receiptInput->fileObject, 1) + 1 => ImageCompressor::compress($receiptInput->fileObject, 1), ]; $outputFiles = [ - 100 => \TestingUtilities::getRootDataDir() . "/output/compress100.jpg", - 85 => \TestingUtilities::getRootDataDir() . "/output/compress85.jpg", - 50 => \TestingUtilities::getRootDataDir() . "/output/compress50.jpg", - 10 => \TestingUtilities::getRootDataDir() . "/output/compress10.jpg", - 1 => \TestingUtilities::getRootDataDir() . "/output/compress1.jpg", + 100 => TestingUtilities::getRootDataDir() . "/output/compress100.jpg", + 85 => TestingUtilities::getRootDataDir() . "/output/compress85.jpg", + 50 => TestingUtilities::getRootDataDir() . "/output/compress50.jpg", + 10 => TestingUtilities::getRootDataDir() . "/output/compress10.jpg", + 1 => TestingUtilities::getRootDataDir() . "/output/compress1.jpg", ]; $compressSize = []; @@ -276,66 +281,66 @@ public function testDirectImageQualityCompression() ); $compressSize[$key] = filesize($outputFiles[$key]); } - $this->assertGreaterThan($compressSize[85], $compressSize[100]); - $this->assertGreaterThan($sizeOriginal, $compressSize[85]); - $this->assertGreaterThan($compressSize[50], $sizeOriginal); - $this->assertGreaterThan($compressSize[10], $compressSize[50]); - $this->assertGreaterThan($compressSize[1], $compressSize[10]); + self::assertGreaterThan($compressSize[85], $compressSize[100]); + self::assertGreaterThan($sizeOriginal, $compressSize[85]); + self::assertGreaterThan($compressSize[50], $sizeOriginal); + self::assertGreaterThan($compressSize[10], $compressSize[50]); + self::assertGreaterThan($compressSize[1], $compressSize[10]); } - public function testPDFSourceText() + public function testPdfSourceText(): void { - $imageInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); - $pdfEmptyInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $pdfSourceText = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/multipage.pdf'); - $this->assertTrue($pdfSourceText->hasSourceText(), "Source text should be properly detected."); - $this->assertFalse($pdfEmptyInput->hasSourceText(), "Empty PDFs should not have source text detected."); - $this->assertFalse($imageInput->hasSourceText(), "An image should not have any text."); + $imageInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $pdfEmptyInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); + $pdfSourceText = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage.pdf'); + self::assertTrue($pdfSourceText->hasSourceText(), "Source text should be properly detected."); + self::assertFalse($pdfEmptyInput->hasSourceText(), "Empty PDFs should not have source text detected."); + self::assertFalse($imageInput->hasSourceText(), "An image should not have any text."); } - public function testCompressPDFFromInputSource() + public function testCompressPdfFromInputSource(): void { - $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" + $pdfInput = new PathInput( + TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" ); - $this->assertFalse($pdfInput->hasSourceText()); + self::assertFalse($pdfInput->hasSourceText()); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", + TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/pdf/not_blank_image_only.pdf'); - $sizeIgnored = filesize(\TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf"); - $this->assertEquals($sizeIgnored, $sizeOriginal); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/pdf/not_blank_image_only.pdf'); + $sizeIgnored = filesize(TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf"); + self::assertSame($sizeIgnored, $sizeOriginal); $pdfInput->compress(90, null, null, true, false); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeCompressed = filesize(\TestingUtilities::getRootDataDir() . '/output/compress_indirect.pdf'); - $this->assertLessThan($sizeOriginal, $sizeCompressed); + $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . '/output/compress_indirect.pdf'); + self::assertLessThan($sizeOriginal, $sizeCompressed); } - public function testCompressPDFFromCompressor() + public function testCompressPdfFromCompressor(): void { - $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' + $pdfInput = new PathInput( + TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' ); - $sizeOriginal = filesize(\TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf'); + $sizeOriginal = filesize(TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf'); - $this->assertFalse($pdfInput->hasSourceText()); + self::assertFalse($pdfInput->hasSourceText()); $pdfCompresses = [ - 85 => PDFCompressor::compress($pdfInput->fileObject), - 75 => PDFCompressor::compress($pdfInput->fileObject, 75), - 50 => PDFCompressor::compress($pdfInput->fileObject, 50), - 10 => PDFCompressor::compress($pdfInput->fileObject, 10), + 85 => PdfCompressor::compress($pdfInput->fileObject), + 75 => PdfCompressor::compress($pdfInput->fileObject, 75), + 50 => PdfCompressor::compress($pdfInput->fileObject, 50), + 10 => PdfCompressor::compress($pdfInput->fileObject, 10), ]; $outputFiles = [ - 85 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", - 75 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", - 50 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", - 10 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", + 85 => TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", + 75 => TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", + 50 => TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", + 10 => TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", ]; $compressSize = []; @@ -346,35 +351,33 @@ public function testCompressPDFFromCompressor() ); $compressSize[$key] = filesize($outputFiles[$key]); } - $this->assertGreaterThan($compressSize[85], $sizeOriginal); - $this->assertGreaterThan($compressSize[75], $compressSize[85]); - $this->assertGreaterThan($compressSize[50], $compressSize[75]); - $this->assertGreaterThan($compressSize[10], $compressSize[50]); + self::assertGreaterThan($compressSize[85], $sizeOriginal); + self::assertGreaterThan($compressSize[75], $compressSize[85]); + self::assertGreaterThan($compressSize[50], $compressSize[75]); + self::assertGreaterThan($compressSize[10], $compressSize[50]); } - public function testSourceTextPDFCompression() + public function testSourceTextPdfCompression(): void { - $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf" + $pdfInput = new PathInput( + TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf" ); - $this->assertTrue($pdfInput->hasSourceText()); + self::assertTrue($pdfInput->hasSourceText()); $pdfInput->compress(5, null, null, true, false); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf", + TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $sizeTextCompressed = filesize(\TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); - $this->assertEquals($sizeTextCompressed, $sizeOriginal); - // Note: Greater size when compressed is expected due to original not having any images, so the operation will - // be aborted. + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $sizeTextCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); + self::assertSame($sizeTextCompressed, $sizeOriginal); - $this->assertEquals( + self::assertSame( str_repeat('*', 650), - implode('', str_replace(" ", "", PDFUtils::extractPagesTextElements(\TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) + implode('', str_replace(" ", "", PdfUtils::extractPagesTextElements(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) ); } } diff --git a/tests/Input/URLInputSourceTest.php b/tests/Input/UrlInputSourceTest.php similarity index 57% rename from tests/Input/URLInputSourceTest.php rename to tests/Input/UrlInputSourceTest.php index bb43f4ae..c8ce60b5 100644 --- a/tests/Input/URLInputSourceTest.php +++ b/tests/Input/UrlInputSourceTest.php @@ -1,15 +1,17 @@ oldKey); } - public function testInputFromHTTPShouldNotThrow() + public function testInputFromHttpShouldNotThrow(): void { - $inputDoc = $this->dummyClient->sourceFromUrl("https://example.com/invoice.pdf"); - $this->assertInstanceOf(URLInputSource::class, $inputDoc); + $inputDoc = new UrlInputSource("https://example.com/invoice.pdf"); + self::assertInstanceOf(UrlInputSource::class, $inputDoc); } - public function testInputFromHTTPShouldThrow() + public function testInputFromHttpShouldThrow(): void { $this->expectException(MindeeSourceException::class); - new URLInputSource(url: "http://example.com/invoice.pdf"); + new UrlInputSource(url: "http://example.com/invoice.pdf"); } - public function testDownloadFileFails(){ + public function testDownloadFileFails(): void + { $dummyAddress = "addressthatdoesntworkforcipurposes"; - $urlSource = $this->dummyClient->sourceFromUrl("https://$dummyAddress"); + $urlSource = new UrlInputSource("https://$dummyAddress"); $this->expectException(MindeeSourceException::class); $this->expectExceptionMessage("Failed to download file: Could not resolve host: $dummyAddress"); $urlSource->asLocalInputSource("test.pdf"); } - public function testInvalidFileName(){ - $urlSource = $this->dummyClient->sourceFromUrl("https://addressthatdoesntworkforcipurposes"); + public function testInvalidFileName(): void + { + $urlSource = new UrlInputSource("https://addressthatdoesntworkforcipurposes"); $this->expectException(MindeeSourceException::class); $this->expectExceptionMessage("Filename must end with an extension."); $urlSource->asLocalInputSource("toto"); diff --git a/tests/TestingUtilities.php b/tests/TestingUtilities.php index e6370923..bff6bcd8 100644 --- a/tests/TestingUtilities.php +++ b/tests/TestingUtilities.php @@ -1,5 +1,7 @@ filePath = \TestingUtilities::getFileTypesDir() . "/pdf/blank_1.pdf"; - $this->apiKey = getenv('MINDEE_API_KEY'); - } - - public function testInvalidFilePath() - { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); - // Note : a direct comparison here would be too complicated due to the fact that the output of the command has - // formatting applied by Symfony CLI. - $this->assertEquals(1, $cmdOutput["code"]); - $this->assertTrue(str_contains($cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); - } - - public function testInvalidKey() - { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", $this->filePath, "-k", "invalid-key"]); - $this->assertEquals(1, $cmdOutput["code"]); - $this->assertTrue(str_contains(implode(" ", $cmdOutput["output"]), "Invalid token provided")); - } - - public function testInvalidProduct() - { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["invalid-product", $this->filePath, "-k", "invalid-key", "-D"]); - $this->assertEquals(1, $cmdOutput["code"]); - $this->assertTrue(str_contains($cmdOutput["output"][0], "Invalid product: invalid-product")); - } -} diff --git a/tests/V1/Cli/MindeeCliCommandTest.php b/tests/V1/Cli/MindeeCliCommandTest.php new file mode 100644 index 00000000..f88b449e --- /dev/null +++ b/tests/V1/Cli/MindeeCliCommandTest.php @@ -0,0 +1,43 @@ +filePath = TestingUtilities::getFileTypesDir() . "/pdf/blank_1.pdf"; + $this->apiKey = getenv('MINDEE_API_KEY'); + } + + public function testInvalidFilePath(): void + { + $cmdOutput = MindeeCliTestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); + } + + public function testInvalidKey(): void + { + $cmdOutput = MindeeCliTestingUtilities::executeTest(["financial-document", $this->filePath, "-k", "invalid-key"]); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains(implode(" ", $cmdOutput["output"]), "Invalid token provided")); + } + + public function testInvalidProduct(): void + { + $cmdOutput = MindeeCliTestingUtilities::executeTest(["invalid-product", $this->filePath, "-k", "invalid-key", "-D"]); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid product: invalid-product")); + } +} diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/Cli/MindeeCliCommandTestFunctional.php similarity index 58% rename from tests/V1/CLI/MindeeCLICommandTestFunctional.php rename to tests/V1/Cli/MindeeCliCommandTestFunctional.php index 285a8dd6..59b6de26 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/Cli/MindeeCliCommandTestFunctional.php @@ -1,16 +1,19 @@ apiKey]; if ($initialArgs) { $args = array_merge($args, $initialArgs); @@ -29,16 +32,17 @@ private function runValidCall($productName, $async = false, $initialArgs = []): if ($async) { $args[] = "-A"; } - return MindeeCLITestingUtilities::executeTest($args); + return MindeeCliTestingUtilities::executeTest($args); } - public function productDataProvider() + public static function provideProductCases(): iterable { $data = []; $data[] = ["generated", true, ["-a", "mindee", "-e", "invoice_splitter", "-d", "1"]]; - foreach (MindeeCLIDocuments::getSpecs() as $productName => $productSpecs) { - if ($productName != "custom" && $productName != "generated") { + /** @phpstan-ignore-next-line */ + foreach (MindeeCliDocuments::getSpecs() as $productName => $productSpecs) { + if ($productName !== "custom" && $productName !== "generated") { if ($productSpecs->isSync) { $data[] = [$productName, false]; } @@ -51,14 +55,14 @@ public function productDataProvider() } /** - * @dataProvider productDataProvider + * @dataProvider provideProductCases */ - public function testProduct($productName, $async, $additionnalArgs = []) + public function testProduct($productName, $async, $additionnalArgs = []): void { $cmdOutput = $this->runValidCall($productName, $async, $additionnalArgs); - $this->assertEquals(0, $cmdOutput["code"], $productName . ($async ? " async" : " sync") . " test (code)."); - $this->assertTrue( - str_contains($cmdOutput["output"][1], "Document"), + self::assertSame(0, $cmdOutput["code"], $productName . ($async ? " async" : " sync") . " test (code)."); + self::assertTrue( + str_contains((string) $cmdOutput["output"][1], "Document"), $productName . ($async ? " async" : " sync") . " test (string return)." ); } diff --git a/tests/V1/CLI/MindeeCLITestingUtilities.php b/tests/V1/Cli/MindeeCliTestingUtilities.php similarity index 89% rename from tests/V1/CLI/MindeeCLITestingUtilities.php rename to tests/V1/Cli/MindeeCliTestingUtilities.php index b7ed9b13..34e8a257 100644 --- a/tests/V1/CLI/MindeeCLITestingUtilities.php +++ b/tests/V1/Cli/MindeeCliTestingUtilities.php @@ -1,10 +1,10 @@ errorDir = \TestingUtilities::getV1DataDir() . "/errors/"; + $this->errorDir = TestingUtilities::getV1DataDir() . "/errors/"; $this->dummyClient = new Client("dummy-key"); - $this->dummyFile = $this->dummyClient->sourceFromPath( - \TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf" + $this->dummyFile = new PathInput( + TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf" ); } - public function testHTTPClientErrorShouldRaise() + public function testHttpClientErrorShouldRaise(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueClientException() + public function testHttpEnqueueClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPParseClientException() + public function testHttpParseClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueAndParseClientException() + public function testHttpEnqueueAndParseClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueueAndParse(InvoiceV4::class, $this->dummyFile); } - public function testHTTP400Exception() + public function testHttp400Exception(): void { $json = file_get_contents($this->errorDir . "error_400_no_details.json"); $errorObj = ["data" => json_decode($json, true), "code" => 400]; - $error400 = MindeeHttpException::handleError("dummy-url", $errorObj); - $this->assertEquals(400, $error400->statusCode); - $this->assertEquals("SomeCode", $error400->apiCode); - $this->assertEquals("Some scary message here", $error400->apiMessage); - $this->assertNull($error400->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $error400 = MindeeV1HttpException::handleError("dummy-url", $errorObj); + self::assertSame(400, $error400->statusCode); + self::assertSame("SomeCode", $error400->apiCode); + self::assertSame("Some scary message here", $error400->apiMessage); + self::assertNull($error400->apiDetails); + $this->expectException(MindeeV1HttpException::class); throw $error400; } - public function testHTTP401Exception() + public function testHttp401Exception(): void { $json = file_get_contents($this->errorDir . "error_401_invalid_token.json"); $errorObj = ["data" => json_decode($json, true), "code" => 401]; - $error401 = MindeeHttpException::handleError("dummy-url", $errorObj); - $this->assertEquals(401, $error401->statusCode); - $this->assertEquals("Unauthorized", $error401->apiCode); - $this->assertEquals("Authorization required", $error401->apiMessage); - $this->assertEquals("Invalid token provided", $error401->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $error401 = MindeeV1HttpException::handleError("dummy-url", $errorObj); + self::assertSame(401, $error401->statusCode); + self::assertSame("Unauthorized", $error401->apiCode); + self::assertSame("Authorization required", $error401->apiMessage); + self::assertSame("Invalid token provided", $error401->apiDetails); + $this->expectException(MindeeV1HttpException::class); throw $error401; } - public function testHTTP429Exception() + public function testHttp429Exception(): void { $json = file_get_contents($this->errorDir . "error_429_too_many_requests.json"); $errorObj = ["data" => json_decode($json, true), "code" => 429]; - $error429 = MindeeHttpException::handleError("dummy-url", $errorObj); - $this->assertEquals(429, $error429->statusCode); - $this->assertEquals("TooManyRequests", $error429->apiCode); - $this->assertEquals("Too many requests", $error429->apiMessage); - $this->assertEquals("Too Many Requests.", $error429->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $error429 = MindeeV1HttpException::handleError("dummy-url", $errorObj); + self::assertSame(429, $error429->statusCode); + self::assertSame("TooManyRequests", $error429->apiCode); + self::assertSame("Too many requests", $error429->apiMessage); + self::assertSame("Too Many Requests.", $error429->apiDetails); + $this->expectException(MindeeV1HttpException::class); throw $error429; } - public function testHTTP500Exception() + public function testHttp500Exception(): void { $json = file_get_contents($this->errorDir . "error_500_inference_fail.json"); $errorObj = ["data" => json_decode($json, true), "code" => 500]; - $error500 = MindeeHttpException::handleError("dummy-url", $errorObj); - $this->assertEquals(500, $error500->statusCode); - $this->assertEquals("failure", $error500->apiCode); - $this->assertEquals("Inference failed", $error500->apiMessage); - $this->assertEquals("Can not run prediction: ", $error500->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $error500 = MindeeV1HttpException::handleError("dummy-url", $errorObj); + self::assertSame(500, $error500->statusCode); + self::assertSame("failure", $error500->apiCode); + self::assertSame("Inference failed", $error500->apiMessage); + self::assertSame("Can not run prediction: ", $error500->apiDetails); + $this->expectException(MindeeV1HttpException::class); throw $error500; } - public function testHTTP500HTMLError() + public function testHttp500HTMLError(): void { $errorRefContents = file_get_contents($this->errorDir . "error_50x.html"); - $error500 = MindeeHttpException::handleError("dummy-url", ["data" => $errorRefContents, "code" => 500]); - $this->assertEquals(500, $error500->statusCode); - $this->assertEquals("UnknownError", $error500->apiCode); - $this->assertEquals("Server sent back an unexpected reply.", $error500->apiMessage); - $this->assertEquals($errorRefContents, $error500->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $error500 = MindeeV1HttpException::handleError("dummy-url", ["data" => $errorRefContents, "code" => 500]); + self::assertSame(500, $error500->statusCode); + self::assertSame("UnknownError", $error500->apiCode); + self::assertSame("Server sent back an unexpected reply.", $error500->apiMessage); + self::assertSame($errorRefContents, $error500->apiDetails); + $this->expectException(MindeeV1HttpException::class); throw $error500; } } diff --git a/tests/V1/Extraction/PdfExtractorTest.php b/tests/V1/Extraction/PdfExtractorTest.php deleted file mode 100644 index caca0452..00000000 --- a/tests/V1/Extraction/PdfExtractorTest.php +++ /dev/null @@ -1,80 +0,0 @@ -dummyClient = new Client("dummy-key"); - } - public function testGivenAnImageShouldExtractAPDF() - { - $jpg = \TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; - $localInput = new PathInput($jpg); - $this->assertFalse($localInput->isPdf()); - $extractor = new PdfExtractor($localInput); - $this->assertEquals(1, $extractor->getPageCount()); - } - - /** - * @test - */ - public function testGivenAPDFShouldExtractInvoicesNoStrict() - { - $pdf = new PathInput(\TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); - $response = $this->getPrediction(); - $this->assertNotNull($response); - $inference = $response->document->inference; - $extractor = new PdfExtractor($pdf); - $this->assertEquals(5, $extractor->getPageCount()); - - $extractedPDFSNoStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups); - $this->assertCount(3, $extractedPDFSNoStrict); - $this->assertEquals("invoice_5p_001-001.pdf", $extractedPDFSNoStrict[0]->getFileName()); - $this->assertEquals(1, $extractedPDFSNoStrict[0]->getPageCount()); - $this->assertEquals("invoice_5p_002-004.pdf", $extractedPDFSNoStrict[1]->getFileName()); - $this->assertEquals(3, $extractedPDFSNoStrict[1]->getPageCount()); - $this->assertEquals("invoice_5p_005-005.pdf", $extractedPDFSNoStrict[2]->getFileName()); - $this->assertEquals(1, $extractedPDFSNoStrict[2]->getPageCount()); - } - - /** - * @test - */ - public function testGivenAPDFShouldExtractInvoicesStrict() - { - $pdf = new PathInput(\TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); - $response = $this->getPrediction(); - $this->assertNotNull($response); - $inference = $response->document->inference; - - $extractor = new PdfExtractor($pdf); - $this->assertEquals(5, $extractor->getPageCount()); - - $extractedPDFStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups, true); - $this->assertCount(2, $extractedPDFStrict); - $this->assertEquals("invoice_5p_001-001.pdf", $extractedPDFStrict[0]->getFileName()); - $this->assertEquals(1, $extractedPDFStrict[0]->getPageCount()); - $this->assertEquals("invoice_5p_002-005.pdf", $extractedPDFStrict[1]->getFileName()); - $this->assertEquals(4, $extractedPDFStrict[1]->getPageCount()); - } - - private function getPrediction() - { - $fileName = \TestingUtilities::getV1DataDir() . "/products/invoice_splitter/response_v1/complete.json"; - $localResponse = new LocalResponse($fileName); - return $this->dummyClient->loadPrediction(InvoiceSplitterV1::class, $localResponse); - } -} diff --git a/tests/V1/Http/MindeeApiTest.php b/tests/V1/Http/MindeeApiTest.php index bc355a4f..e958ad3c 100644 --- a/tests/V1/Http/MindeeApiTest.php +++ b/tests/V1/Http/MindeeApiTest.php @@ -1,12 +1,16 @@ keyEnvName); } - public function testGivenOTSParametersAProperMindeeApiObjectShouldBeCreated() + public function testGivenOTSParametersAProperMindeeApiObjectShouldBeCreated(): void { $settings = new MindeeApi("my-api-key", InvoiceSplitterV1::$endpointName); - $this->assertEquals("my-api-key", $settings->apiKey); - $this->assertEquals(InvoiceSplitterV1::$endpointName, $settings->endpointName); - $this->assertEquals(\Mindee\Client::DEFAULT_OWNER, $settings->accountName); - $this->assertEquals("1", $settings->version); + self::assertSame("my-api-key", $settings->apiKey); + self::assertSame(InvoiceSplitterV1::$endpointName, $settings->endpointName); + self::assertSame(Client::DEFAULT_OWNER, $settings->accountName); + self::assertSame("1", $settings->version); } - public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated() + public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated(): void { $settings = new MindeeApi("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); - $this->assertEquals("my-api-key", $settings->apiKey); - $this->assertEquals("custom-endpoint-name", $settings->endpointName); - $this->assertEquals("custom-owner-name", $settings->accountName); - $this->assertEquals("1.3", $settings->version); + self::assertSame("my-api-key", $settings->apiKey); + self::assertSame("custom-endpoint-name", $settings->endpointName); + self::assertSame("custom-owner-name", $settings->accountName); + self::assertSame("1.3", $settings->version); } - public function testGivenInvalidApiKeyAnExceptionShouldBeThrown() + public function testGivenInvalidApiKeyAnExceptionShouldBeThrown(): void { $this->expectException(MindeeException::class); putenv(API_KEY_ENV_NAME . '='); diff --git a/tests/V1/Extraction/ImageExtractorTest.php b/tests/V1/Image/ImageExtractorTest.php similarity index 50% rename from tests/V1/Extraction/ImageExtractorTest.php rename to tests/V1/Image/ImageExtractorTest.php index 15c25af3..bdba2ce1 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Image/ImageExtractorTest.php @@ -1,18 +1,22 @@ dummyClient = new Client("dummy-key"); } - public function testGivenAnImageShouldExtractPositionFields() + public function testGivenAnImageShouldExtractPositionFields(): void { $image = new PathInput( - \TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/default_sample.jpg" + TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/default_sample.jpg" ); $response = $this->getMultiReceiptsDetectorPrediction("complete"); $inference = $response->document->inference; $extractor = new ImageExtractor($image); - $this->assertEquals(1, $extractor->getPageCount()); + self::assertSame(1, $extractor->getPageCount()); foreach ($inference->pages as $page) { $subImages = $extractor->extractImagesFromPage($page->prediction->receipts, $page->id); foreach ($subImages as $i => $extractedImage) { - $this->assertNotNull($extractedImage->image); - $extractedImage->writeToFile(\TestingUtilities::getRootDataDir() . "/output"); + self::assertNotNull($extractedImage->image); + $extractedImage->writeToFile(TestingUtilities::getRootDataDir() . "/output"); $source = $extractedImage->asInputSource(); - $this->assertEquals( + self::assertSame( sprintf("default_sample.jpg_page0-%d.jpg", $i), $source->fileName ); @@ -48,61 +52,61 @@ public function testGivenAnImageShouldExtractPositionFields() private function getMultiReceiptsDetectorPrediction($name) { - $fileName = \TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/response_v1/{$name}.json"; + $fileName = TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/response_v1/{$name}.json"; $localResponse = new LocalResponse($fileName); return $this->dummyClient->loadPrediction(MultiReceiptsDetectorV1::class, $localResponse); } - public function testGivenAnImageShouldExtractValueFields() + public function testGivenAnImageShouldExtractValueFields(): void { - $image = new PathInput(\TestingUtilities::getV1DataDir() . "/products/barcode_reader/default_sample.jpg"); + $image = new PathInput(TestingUtilities::getV1DataDir() . "/products/barcode_reader/default_sample.jpg"); $response = $this->getBarcodeReaderPrediction("complete"); $inference = $response->document->inference; $extractor = new ImageExtractor($image); - $this->assertEquals(1, $extractor->getPageCount()); + self::assertSame(1, $extractor->getPageCount()); foreach ($inference->pages as $page) { $codes1D = $extractor->extractImagesFromPage($page->prediction->codes1D, $page->id, "barcodes_1D.jpg"); foreach ($codes1D as $i => $extractedImage) { - $this->assertNotNull($extractedImage->image); + self::assertNotNull($extractedImage->image); $source = $extractedImage->asInputSource(); - $this->assertEquals( + self::assertSame( sprintf("barcodes_1D.jpg_page0-%d.jpg", $i), $source->fileName ); - $extractedImage->writeToFile(\TestingUtilities::getRootDataDir() . "/output"); + $extractedImage->writeToFile(TestingUtilities::getRootDataDir() . "/output"); } $codes2D = $extractor->extractImagesFromPage($page->prediction->codes2D, $page->id, "barcodes_2D.jpg"); foreach ($codes2D as $extractedImage) { - $this->assertNotNull($extractedImage->image); - $extractedImage->writeToFile(\TestingUtilities::getRootDataDir() . "/output"); + self::assertNotNull($extractedImage->image); + $extractedImage->writeToFile(TestingUtilities::getRootDataDir() . "/output"); } } } - public function testGivenAPdfShouldExtractPositionFields() + public function testGivenAPdfShouldExtractPositionFields(): void { $imageInput = new PathInput( - \TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/multipage_sample.pdf" + TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/multipage_sample.pdf" ); $response = $this->getMultiReceiptsDetectorPrediction("multipage_sample"); $inference = $response->document->inference; - $this->assertNotEmpty($imageInput->readContents()[1]); + self::assertNotEmpty($imageInput->readContents()[1]); $extractor = new ImageExtractor($imageInput); - $this->assertEquals(2, $extractor->getPageCount()); + self::assertSame(2, $extractor->getPageCount()); foreach ($inference->pages as $page) { $subImages = $extractor->extractImagesFromPage($page->prediction->receipts, $page->id); foreach ($subImages as $i => $extractedImage) { - $this->assertNotNull($extractedImage->image); - $extractedImage->writeToFile(\TestingUtilities::getRootDataDir() . "/output"); + self::assertNotNull($extractedImage->image); + $extractedImage->writeToFile(TestingUtilities::getRootDataDir() . "/output"); $source = $extractedImage->asInputSource(); - $this->assertEquals( + self::assertSame( sprintf("multipage_sample.pdf_page%d-%d.jpg", $page->id, $i), $source->fileName ); @@ -112,7 +116,7 @@ public function testGivenAPdfShouldExtractPositionFields() private function getBarcodeReaderPrediction($name) { - $fileName = \TestingUtilities::getV1DataDir() . "/products/barcode_reader/response_v1/{$name}.json"; + $fileName = TestingUtilities::getV1DataDir() . "/products/barcode_reader/response_v1/{$name}.json"; $localResponse = new LocalResponse($fileName); return $this->dummyClient->loadPrediction(BarcodeReaderV1::class, $localResponse); } @@ -120,20 +124,20 @@ private function getBarcodeReaderPrediction($name) protected function tearDown(): void { $filesToDelete = [ - \TestingUtilities::getRootDataDir() . "/output/barcodes_1D_page-001_001.jpg", - \TestingUtilities::getRootDataDir() . "/output/barcodes_2D_page-001_001.jpg", - \TestingUtilities::getRootDataDir() . "/output/barcodes_2D_page-001_002.jpg", - \TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_001.jpg", - \TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_002.jpg", - \TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_003.jpg", - \TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-002_001.jpg", - \TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-002_002.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_001.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_002.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_003.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_004.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_005.jpg", - \TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_006.jpg", + TestingUtilities::getRootDataDir() . "/output/barcodes_1D_page-001_001.jpg", + TestingUtilities::getRootDataDir() . "/output/barcodes_2D_page-001_001.jpg", + TestingUtilities::getRootDataDir() . "/output/barcodes_2D_page-001_002.jpg", + TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_001.jpg", + TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_002.jpg", + TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-001_003.jpg", + TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-002_001.jpg", + TestingUtilities::getRootDataDir() . "/output/multipage_sample_page-002_002.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_001.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_002.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_003.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_004.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_005.jpg", + TestingUtilities::getRootDataDir() . "/output/default_sample_page-001_006.jpg", ]; foreach ($filesToDelete as $file) { diff --git a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php similarity index 69% rename from tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php rename to tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php index 064752dd..dcc932ff 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php @@ -1,19 +1,21 @@ enqueueAndParse(InvoiceSplitterV1::class, $invoiceSplitterInput); $inference = $response->document->inference; $pdfExtractor = new PdfExtractor($invoiceSplitterInput); - $this->assertEquals(2, $pdfExtractor->getPageCount()); + self::assertSame(2, $pdfExtractor->getPageCount()); $extractedPdfsStrict = $pdfExtractor->extractInvoices($inference->prediction->invoicePageGroups); - $this->assertCount(2, $extractedPdfsStrict); - $this->assertEquals('default_sample_001-001.pdf', $extractedPdfsStrict[0]->getFilename()); - $this->assertEquals('default_sample_002-002.pdf', $extractedPdfsStrict[1]->getFilename()); + self::assertCount(2, $extractedPdfsStrict); + self::assertSame('default_sample_001-001.pdf', $extractedPdfsStrict[0]->getFilename()); + self::assertSame('default_sample_002-002.pdf', $extractedPdfsStrict[1]->getFilename()); $invoice0 = $client->parse(InvoiceV4::class, $extractedPdfsStrict[0]->asInputSource()); @@ -54,11 +56,11 @@ public function testPdfShouldExtractInvoicesStrict() invoicePrediction: $invoice0->document ); - $this->assertGreaterThan( + self::assertGreaterThan( 0.90, TestingUtilities::levenshteinRatio( $testStringRstInvoice0, - (string)$invoice0->document + (string) $invoice0->document ) ); } diff --git a/tests/V1/Input/LocalResponseV1Test.php b/tests/V1/Input/LocalResponseV1Test.php index a0abae30..296f93fe 100644 --- a/tests/V1/Input/LocalResponseV1Test.php +++ b/tests/V1/Input/LocalResponseV1Test.php @@ -1,9 +1,12 @@ filePath = \TestingUtilities::getV1DataDir() . '/async/get_completed_empty.json'; + $this->filePath = TestingUtilities::getV1DataDir() . '/async/get_completed_empty.json'; $this->signature = "5ed1673e34421217a5dbfcad905ee62261a3dd66c442f3edd19302072bbf70d0"; $this->dummyKey = "ogNjY44MhvKPGTtVsI8zG82JqWQa68woYQH"; } - public function testValidFileLocalResponse() + public function testValidFileLocalResponse(): void { - $file = fopen($this->filePath, 'rb'); + $file = fopen($this->filePath, 'r'); $localResponse = new LocalResponse($file); fclose($file); - $this->assertNotNull($localResponse->toArray(), 'Local response file should not be null'); + self::assertNotNull($localResponse->toArray(), 'Local response file should not be null'); $invalidSignature = 'invalid_signature'; - $this->assertFalse( + self::assertFalse( $localResponse->isValidHmacSignature($this->dummyKey, $invalidSignature), 'Invalid signature should not be valid' ); $calculatedSignature = $localResponse->getHmacSignature($this->dummyKey); - $this->assertEquals( + self::assertSame( $this->signature, $calculatedSignature, 'Calculated signature should match the expected valid signature' ); - $this->assertTrue( + self::assertTrue( $localResponse->isValidHmacSignature($this->dummyKey, $this->signature), 'Valid signature should be valid' ); } - public function testValidStringLocalResponse() + public function testValidStringLocalResponse(): void { $file = file_get_contents($this->filePath); $localResponse = new LocalResponse($file); - $this->assertNotNull($localResponse->toArray(), 'Local response file should not be null'); + self::assertNotNull($localResponse->toArray(), 'Local response file should not be null'); $invalidSignature = 'invalid_signature'; - $this->assertFalse( + self::assertFalse( $localResponse->isValidHmacSignature($this->dummyKey, $invalidSignature), 'Invalid signature should not be valid' ); $calculatedSignature = $localResponse->getHmacSignature($this->dummyKey); - $this->assertEquals( + self::assertSame( $this->signature, $calculatedSignature, 'Calculated signature should match the expected valid signature' ); - $this->assertTrue( + self::assertTrue( $localResponse->isValidHmacSignature($this->dummyKey, $this->signature), 'Valid signature should be valid' ); } - public function testValidStreamLocalResponse() + public function testValidStreamLocalResponse(): void { - // Create a stream from the file content $stream = fopen('php://memory', 'r+'); fwrite($stream, file_get_contents($this->filePath)); rewind($stream); - // Create LocalResponse instance with the stream $localResponse = new LocalResponse($stream); - $this->assertNotNull($localResponse->toArray(), 'Local response file should not be null'); + self::assertNotNull($localResponse->toArray(), 'Local response file should not be null'); $invalidSignature = 'invalid_signature'; - $this->assertFalse( + self::assertFalse( $localResponse->isValidHmacSignature($this->dummyKey, $invalidSignature), 'Invalid signature should not be valid' ); $calculatedSignature = $localResponse->getHmacSignature($this->dummyKey); - $this->assertEquals( + self::assertSame( $this->signature, $calculatedSignature, 'Calculated signature should match the expected valid signature' ); - $this->assertTrue( + self::assertTrue( $localResponse->isValidHmacSignature($this->dummyKey, $this->signature), 'Valid signature should be valid' ); - fclose($stream); // Close the stream after use + fclose($stream); } - public function testValidFilePathLocalResponse() + public function testValidFilePathLocalResponse(): void { $localResponse = new LocalResponse($this->filePath); - $this->assertNotNull($localResponse->toArray(), 'Local response file should not be null'); + self::assertNotNull($localResponse->toArray(), 'Local response file should not be null'); $invalidSignature = 'invalid_signature'; - $this->assertFalse( + self::assertFalse( $localResponse->isValidHmacSignature($this->dummyKey, $invalidSignature), 'Invalid signature should not be valid' ); $calculatedSignature = $localResponse->getHmacSignature($this->dummyKey); - $this->assertEquals( + self::assertSame( $this->signature, $calculatedSignature, 'Calculated signat match the expected valid signature' ); - $this->assertTrue( + self::assertTrue( $localResponse->isValidHmacSignature($this->dummyKey, $this->signature), 'Valid signature should be valid' ); diff --git a/tests/V1/Input/URLInputSourceTestFunctional.php b/tests/V1/Input/URLInputSourceTestFunctional.php deleted file mode 100644 index 432de859..00000000 --- a/tests/V1/Input/URLInputSourceTestFunctional.php +++ /dev/null @@ -1,59 +0,0 @@ -client = new Client(); - $this->outputFilePath = \TestingUtilities::getRootDataDir() . "/output/"; - $this->referenceFilePath = getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL'); - } - - public static function tearDownAfterClass(): void - { - unlink(\TestingUtilities::getRootDataDir() . "/output/blank_1.pdf"); - unlink(\TestingUtilities::getRootDataDir() . "/output/customFileName.pdf"); - } - - public function testLoadLocalFile() - { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); - $localSource = $urlSource->asLocalInputSource(); - $result = $this->client->parse(InvoiceV4::class, $localSource); - $this->assertEquals(1, $result->document->nPages); - $this->assertEquals("blank_1.pdf", $result->document->filename); - } - - public function testCustomFileName() - { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); - $localSource = $urlSource->asLocalInputSource("customName.pdf"); - $result = $this->client->parse(InvoiceV4::class, $localSource); - $this->assertEquals(1, $result->document->nPages); - $this->assertEquals("customName.pdf", $result->document->filename); - } - - public function testSaveFile() - { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); - $urlSource->saveToFile($this->outputFilePath); - $this->assertFileExists($this->outputFilePath . "blank_1.pdf"); - } - - public function testSaveFileWithFilename() - { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); - $urlSource->saveToFile($this->outputFilePath, "customFileName.pdf"); - $this->assertFileExists($this->outputFilePath . "customFileName.pdf"); - } -} diff --git a/tests/V1/Input/UrlInputSourceTestFunctional.php b/tests/V1/Input/UrlInputSourceTestFunctional.php new file mode 100644 index 00000000..fae63720 --- /dev/null +++ b/tests/V1/Input/UrlInputSourceTestFunctional.php @@ -0,0 +1,63 @@ +client = new Client(); + $this->outputFilePath = TestingUtilities::getRootDataDir() . "/output/"; + $this->referenceFilePath = getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL'); + } + + public static function tearDownAfterClass(): void + { + unlink(TestingUtilities::getRootDataDir() . "/output/blank_1.pdf"); + unlink(TestingUtilities::getRootDataDir() . "/output/customFileName.pdf"); + } + + public function testLoadLocalFile(): void + { + $urlSource = new UrlInputSource($this->referenceFilePath); + $localSource = $urlSource->asLocalInputSource(); + $result = $this->client->parse(InvoiceV4::class, $localSource); + self::assertSame(1, $result->document->nPages); + self::assertSame("blank_1.pdf", $result->document->filename); + } + + public function testCustomFileName(): void + { + $urlSource = new UrlInputSource($this->referenceFilePath); + $localSource = $urlSource->asLocalInputSource("customName.pdf"); + $result = $this->client->parse(InvoiceV4::class, $localSource); + self::assertSame(1, $result->document->nPages); + self::assertSame("customName.pdf", $result->document->filename); + } + + public function testSaveFile(): void + { + $urlSource = new UrlInputSource($this->referenceFilePath); + $urlSource->saveToFile($this->outputFilePath); + self::assertFileExists($this->outputFilePath . "blank_1.pdf"); + } + + public function testSaveFileWithFilename(): void + { + $urlSource = new UrlInputSource($this->referenceFilePath); + $urlSource->saveToFile($this->outputFilePath, "customFileName.pdf"); + self::assertFileExists($this->outputFilePath . "customFileName.pdf"); + } +} diff --git a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php index f48e153f..25c3cba1 100644 --- a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php +++ b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php @@ -1,11 +1,14 @@ filePathPostSuccess = $asyncDir . "/post_success.json"; $this->filePathPostFail = $asyncDir . "/post_fail_forbidden.json"; $this->filePathGetProcessing = $asyncDir . "/get_processing.json"; @@ -25,70 +28,70 @@ protected function setUp(): void $this->filePathGetFailJob = $asyncDir . "/get_failed_job_error.json"; } - public function testAsyncResponsePOSTSuccess() + public function testAsyncResponsePOSTSuccess(): void { $json = file_get_contents($this->filePathPostSuccess); $response = json_decode($json, true); - $this->assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); + self::assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); $parsedResponse = new AsyncPredictResponse(InvoiceSplitterV1::class, $response); - $this->assertNotNull($parsedResponse->job); - $this->assertEquals( + self::assertNotNull($parsedResponse->job); + self::assertSame( "2023-02-16T12:33:49.602947+00:00", $parsedResponse->job->issuedAt->format('Y-m-d\TH:i:s.uP') ); - $this->assertNull($parsedResponse->job->availableAt); - $this->assertEquals("waiting", $parsedResponse->job->status); - $this->assertEquals("76c90710-3a1b-4b91-8a39-31a6543e347c", $parsedResponse->job->id); - $this->assertEmpty($parsedResponse->apiRequest->error); + self::assertNull($parsedResponse->job->availableAt); + self::assertSame("waiting", $parsedResponse->job->status); + self::assertSame("76c90710-3a1b-4b91-8a39-31a6543e347c", $parsedResponse->job->id); + self::assertEmpty($parsedResponse->apiRequest->error); } - public function testAsyncResponsePOSTFail() + public function testAsyncResponsePOSTFail(): void { $json = file_get_contents($this->filePathPostFail); $response = json_decode($json, true); - $this->assertFalse(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); + self::assertFalse(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); } - public function testAsyncResponseGETFailedJob() + public function testAsyncResponseGETFailedJob(): void { $json = file_get_contents($this->filePathGetFailJob); $response = json_decode($json, true); - $this->assertFalse(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); + self::assertFalse(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); } - public function testAsyncResponseGETProcessing() + public function testAsyncResponseGETProcessing(): void { $json = file_get_contents($this->filePathGetProcessing); $response = json_decode($json, true); - $this->assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); + self::assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); $parsedResponse = new AsyncPredictResponse(InvoiceSplitterV1::class, $response); - $this->assertNotNull($parsedResponse->job); - $this->assertEquals( + self::assertNotNull($parsedResponse->job); + self::assertSame( "2023-03-16T12:33:49.602947", $parsedResponse->job->issuedAt->format('Y-m-d\TH:i:s.u') ); - $this->assertNull($parsedResponse->job->availableAt); - $this->assertEquals("processing", $parsedResponse->job->status); - $this->assertEquals("76c90710-3a1b-4b91-8a39-31a6543e347c", $parsedResponse->job->id); - $this->assertEmpty($parsedResponse->apiRequest->error); + self::assertNull($parsedResponse->job->availableAt); + self::assertSame("processing", $parsedResponse->job->status); + self::assertSame("76c90710-3a1b-4b91-8a39-31a6543e347c", $parsedResponse->job->id); + self::assertEmpty($parsedResponse->apiRequest->error); } - public function testAsyncResponseGETCompleted() + public function testAsyncResponseGETCompleted(): void { $json = file_get_contents($this->filePathGetCompleted); $response = json_decode($json, true); - $this->assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); + self::assertTrue(ResponseValidation::isValidAsyncResponse(["data" => $response, "code" => 200])); $parsedResponse = new AsyncPredictResponse(InvoiceSplitterV1::class, $response); - $this->assertNotNull($parsedResponse->job); - $this->assertEquals( + self::assertNotNull($parsedResponse->job); + self::assertSame( "2023-03-21T13:52:56.326107", $parsedResponse->job->issuedAt->format('Y-m-d\TH:i:s.u') ); - $this->assertEquals( + self::assertSame( "2023-03-21T13:53:00.990339", $parsedResponse->job->availableAt->format('Y-m-d\TH:i:s.u') ); - $this->assertEquals("completed", $parsedResponse->job->status); - $this->assertEquals("b6caf9e8-9bcc-4412-bcb7-f5b416678f0d", $parsedResponse->job->id); - $this->assertEmpty($parsedResponse->apiRequest->error); + self::assertSame("completed", $parsedResponse->job->status); + self::assertSame("b6caf9e8-9bcc-4412-bcb7-f5b416678f0d", $parsedResponse->job->id); + self::assertEmpty($parsedResponse->apiRequest->error); } } diff --git a/tests/V1/Parsing/Common/Extras/CropperExtraTest.php b/tests/V1/Parsing/Common/Extras/CropperExtraTest.php index 62ce9757..eb8be935 100644 --- a/tests/V1/Parsing/Common/Extras/CropperExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/CropperExtraTest.php @@ -1,11 +1,14 @@ cropperDir = \TestingUtilities::getV1DataDir() . "/extras/cropper/"; + $this->cropperDir = TestingUtilities::getV1DataDir() . "/extras/cropper/"; $completeDocFile = file_get_contents($this->cropperDir . "complete.json"); $completeDocJSON = json_decode($completeDocFile, true); $this->completeDoc = new Document(ReceiptV5::class, $completeDocJSON["document"]); } - public function testEnqueuingCropperEnqueuesCropper() + public function testEnqueuingCropperEnqueuesCropper(): void { $predictOptions = new PredictOptions(); $predictOptions->setCropper(true); - $this->assertTrue($predictOptions->cropper); + self::assertTrue($predictOptions->cropper); } - public function testCropperExtra() + public function testCropperExtra(): void { - $this->assertEquals(1, count($this->completeDoc->inference->pages[0]->extras->cropper->croppings)); - $this->assertEquals(0.057, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[0]->getX()); - $this->assertEquals(0.008, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[0]->getY()); - $this->assertEquals(0.846, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[1]->getX()); - $this->assertEquals(0.008, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[1]->getY()); - $this->assertEquals(0.846, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[2]->getX()); - $this->assertEquals(1.0, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[2]->getY()); - $this->assertEquals(0.057, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[3]->getX()); - $this->assertEquals(1.0, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[3]->getY()); - $this->assertEquals(24, count($this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->polygon->getCoordinates())); - $this->assertEquals(4, count($this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->quadrangle->getCoordinates())); - $this->assertEquals(4, count($this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->rectangle->getCoordinates())); + self::assertCount(1, $this->completeDoc->inference->pages[0]->extras->cropper->croppings); + self::assertSame(0.057, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[0]->getX()); + self::assertSame(0.008, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[0]->getY()); + self::assertSame(0.846, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[1]->getX()); + self::assertSame(0.008, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[1]->getY()); + self::assertSame(0.846, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[2]->getX()); + self::assertSame(1.0, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[2]->getY()); + self::assertSame(0.057, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[3]->getX()); + self::assertSame(1.0, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->boundingBox->getCoordinates()[3]->getY()); + self::assertCount(24, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->polygon->getCoordinates()); + self::assertCount(4, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->quadrangle->getCoordinates()); + self::assertCount(4, $this->completeDoc->inference->pages[0]->extras->cropper->croppings[0]->rectangle->getCoordinates()); } } diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 65e84521..9e6e7301 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -1,13 +1,20 @@ client->sourceFromPath( - \TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg" + $sample = new PathInput( + TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg" ); $predictOptions = new PredictOptions(); $predictOptions->setCropper(true); @@ -30,14 +37,14 @@ public function testShouldSendCropperExtra(): void $response = $this->client->parse(InvoiceV4::class, $sample, $predictMethodOptions); - $this->assertNotNull($response->document->inference->pages[0]->extras->cropper); - $this->assertGreaterThan(0, count($response->document->inference->pages[0]->extras->cropper->croppings)); + self::assertNotNull($response->document->inference->pages[0]->extras->cropper); + self::assertGreaterThan(0, count($response->document->inference->pages[0]->extras->cropper->croppings)); } public function testShouldSendFullTextOcrExtra(): void { - $sample = $this->client->sourceFromPath( - \TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" + $sample = new PathInput( + TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" ); $predictOptions = new PredictOptions(); $predictOptions->setFullText(true); @@ -45,7 +52,7 @@ public function testShouldSendFullTextOcrExtra(): void $predictMethodOptions->setPredictOptions($predictOptions); $response = $this->client->enqueueAndParse(InternationalIdV2::class, $sample, $predictMethodOptions); - $this->assertNotNull($response->document->extras->fullTextOcr); - $this->assertGreaterThan(10, strlen($response->document->extras->fullTextOcr->content)); + self::assertNotNull($response->document->extras->fullTextOcr); + self::assertGreaterThan(10, strlen((string) $response->document->extras->fullTextOcr->content)); } } diff --git a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php index 48896e73..2594f049 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php @@ -1,55 +1,39 @@ extrasDir = \TestingUtilities::getV1DataDir() . "/extras"; + $this->extrasDir = TestingUtilities::getV1DataDir() . "/extras"; } private function loadDocument() { - $dummyClient = new \Mindee\Client("dummy-key"); - $localResponse = new \Mindee\Input\LocalResponse($this->extrasDir . '/full_text_ocr/complete.json'); + $dummyClient = new Client("dummy-key"); + $localResponse = new LocalResponse($this->extrasDir . '/full_text_ocr/complete.json'); $response = $dummyClient->loadPrediction(InternationalIdV2::class, $localResponse); return $response->document; } - public function testGetsFullTextOCRResult() + public function testGetsFullTextOcrResult(): void { $expectedText = file_get_contents($this->extrasDir . '/full_text_ocr/full_text_ocr.txt'); $document = $this->loadDocument(); $fullTextOcr = $document->extras->fullTextOcr; - $this->assertEquals(trim($expectedText), trim(strval($fullTextOcr))); - } - - // NOTE: disabled due to the current system used to manage pages of some APIs. - /* - private function loadPages() - { - $dummyClient = new \Mindee\Client("dummy-key"); - $localResponse = new \Mindee\Input\LocalResponse($this->extrasDir . '/full_text_ocr/complete.json'); - $response = $dummyClient->loadPrediction(InternationalIdV2::class, $localResponse); - return $response->document->inference->pages; - } - - public function testGetsFullTextOCRResultForPage() - { - $expectedText = file_get_contents($this->extrasDir . '/full_text_ocr/full_text_ocr.txt'); - - $pages = $this->loadPages(); - $page0Ocr = $pages[0]->extras->fullTextOcr->content; - - $this->assertEquals(implode("\n", explode("\n", $expectedText)), $page0Ocr); + self::assertSame(trim($expectedText), trim((string) $fullTextOcr)); } - */ } diff --git a/tests/V1/Parsing/Common/Ocr/OcrTest.php b/tests/V1/Parsing/Common/Ocr/OcrTest.php index 0fd958d3..74b492d3 100644 --- a/tests/V1/Parsing/Common/Ocr/OcrTest.php +++ b/tests/V1/Parsing/Common/Ocr/OcrTest.php @@ -1,53 +1,57 @@ ocrObject = new Ocr($jsonData["document"]["ocr"]); } - public function testResponse() + public function testResponse(): void { $expectedText = file_get_contents( - \TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" + TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" ); - $this->assertEquals($expectedText, strval($this->ocrObject)); - $this->assertEquals($expectedText, strval($this->ocrObject->mvisionV1->pages[0])); + self::assertSame($expectedText, (string) ($this->ocrObject)); + self::assertSame($expectedText, (string) ($this->ocrObject->mvisionV1->pages[0])); } - public function testFindOneLineByRegex() + public function testFindOneLineByRegex(): void { $regexFilter = '/platinum[\w\s]*\$65\.00/i'; $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals( + self::assertNotNull($matchingLines); + self::assertSame( "Platinum web hosting package $65.00 $65.00", - strval($matchingLines[0][0]) + (string) ($matchingLines[0][0]) ); } - public function testFindMultipleLinesByRegex() + public function testFindMultipleLinesByRegex(): void { $regexFilter = '/^.*\$.*$/m'; $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals(8, count($matchingLines[0])); - $this->assertEquals( + self::assertNotNull($matchingLines); + self::assertCount(8, $matchingLines[0]); + self::assertSame( "Amount Due (USD): $2,608.20", - strval($matchingLines[0][0]) + (string) ($matchingLines[0][0]) ); - $this->assertEquals( + self::assertSame( "Amount due (CAD): $2,608.20", - strval($matchingLines[0][7]) + (string) ($matchingLines[0][7]) ); } } diff --git a/tests/V1/Parsing/Common/PredictResponseTest.php b/tests/V1/Parsing/Common/PredictResponseTest.php index ebcd8359..1427ab9c 100644 --- a/tests/V1/Parsing/Common/PredictResponseTest.php +++ b/tests/V1/Parsing/Common/PredictResponseTest.php @@ -1,25 +1,28 @@ assertInstanceOf(InvoiceV4::class, $parsedResponse->document->inference); + self::assertInstanceOf(InvoiceV4::class, $parsedResponse->document->inference); foreach ($parsedResponse->document->inference->pages as $page) { - $this->assertInstanceOf(InvoiceV4Document::class, $page->prediction); + self::assertInstanceOf(InvoiceV4Document::class, $page->prediction); } - $this->assertEquals(1, $parsedResponse->document->nPages); + self::assertSame(1, $parsedResponse->document->nPages); } } diff --git a/tests/V1/Pdf/PdfExtractorTest.php b/tests/V1/Pdf/PdfExtractorTest.php new file mode 100644 index 00000000..653b21d8 --- /dev/null +++ b/tests/V1/Pdf/PdfExtractorTest.php @@ -0,0 +1,81 @@ +dummyClient = new Client("dummy-key"); + } + public function testGivenAnImageShouldExtractAPdf(): void + { + $jpg = TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; + $localInput = new PathInput($jpg); + self::assertFalse($localInput->isPdf()); + $extractor = new PdfExtractor($localInput); + self::assertSame(1, $extractor->getPageCount()); + } + + /** + * + */ + public function testGivenAPdfShouldExtractInvoicesNoStrict(): void + { + $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); + $response = $this->getPrediction(); + self::assertNotNull($response); + $inference = $response->document->inference; + $extractor = new PdfExtractor($pdf); + self::assertSame(5, $extractor->getPageCount()); + + $extractedPdfSNoStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups); + self::assertCount(3, $extractedPdfSNoStrict); + self::assertSame("invoice_5p_001-001.pdf", $extractedPdfSNoStrict[0]->getFileName()); + self::assertSame(1, $extractedPdfSNoStrict[0]->getPageCount()); + self::assertSame("invoice_5p_002-004.pdf", $extractedPdfSNoStrict[1]->getFileName()); + self::assertSame(3, $extractedPdfSNoStrict[1]->getPageCount()); + self::assertSame("invoice_5p_005-005.pdf", $extractedPdfSNoStrict[2]->getFileName()); + self::assertSame(1, $extractedPdfSNoStrict[2]->getPageCount()); + } + + /** + * + */ + public function testGivenAPdfShouldExtractInvoicesStrict(): void + { + $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); + $response = $this->getPrediction(); + self::assertNotNull($response); + $inference = $response->document->inference; + + $extractor = new PdfExtractor($pdf); + self::assertSame(5, $extractor->getPageCount()); + + $extractedPdfStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups, true); + self::assertCount(2, $extractedPdfStrict); + self::assertSame("invoice_5p_001-001.pdf", $extractedPdfStrict[0]->getFileName()); + self::assertSame(1, $extractedPdfStrict[0]->getPageCount()); + self::assertSame("invoice_5p_002-005.pdf", $extractedPdfStrict[1]->getFileName()); + self::assertSame(4, $extractedPdfStrict[1]->getPageCount()); + } + + private function getPrediction() + { + $fileName = TestingUtilities::getV1DataDir() . "/products/invoice_splitter/response_v1/complete.json"; + $localResponse = new LocalResponse($fileName); + return $this->dummyClient->loadPrediction(InvoiceSplitterV1::class, $localResponse); + } +} diff --git a/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php b/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php index a3302b99..bda66885 100644 --- a/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php +++ b/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(BarcodeReader\BarcodeReaderV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BarcodeReader\BarcodeReaderV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(BarcodeReaderV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BarcodeReaderV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertEquals(0, count($prediction->codes1D)); - $this->assertEquals(0, count($prediction->codes2D)); + self::assertCount(0, $prediction->codes1D); + self::assertCount(0, $prediction->codes2D); } } diff --git a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php deleted file mode 100644 index 9970cdc8..00000000 --- a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php +++ /dev/null @@ -1,58 +0,0 @@ -completeDoc = new Document(BillOfLading\BillOfLadingV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BillOfLading\BillOfLadingV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->billOfLadingNumber->value); - $this->assertNull($prediction->shipper->address); - $this->assertNull($prediction->shipper->email); - $this->assertNull($prediction->shipper->name); - $this->assertNull($prediction->shipper->phone); - $this->assertNull($prediction->consignee->address); - $this->assertNull($prediction->consignee->email); - $this->assertNull($prediction->consignee->name); - $this->assertNull($prediction->consignee->phone); - $this->assertNull($prediction->notifyParty->address); - $this->assertNull($prediction->notifyParty->email); - $this->assertNull($prediction->notifyParty->name); - $this->assertNull($prediction->notifyParty->phone); - $this->assertNull($prediction->carrier->name); - $this->assertNull($prediction->carrier->professionalNumber); - $this->assertNull($prediction->carrier->scac); - $this->assertEquals(0, count($prediction->carrierItems)); - $this->assertNull($prediction->portOfLoading->value); - $this->assertNull($prediction->portOfDischarge->value); - $this->assertNull($prediction->placeOfDelivery->value); - $this->assertNull($prediction->dateOfIssue->value); - $this->assertNull($prediction->departureDate->value); - } -} diff --git a/tests/V1/Product/BusinessCard/BusinessCardV1Test.php b/tests/V1/Product/BusinessCard/BusinessCardV1Test.php index cbfcf915..acf6727a 100644 --- a/tests/V1/Product/BusinessCard/BusinessCardV1Test.php +++ b/tests/V1/Product/BusinessCard/BusinessCardV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(BusinessCard\BusinessCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BusinessCard\BusinessCardV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(BusinessCardV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BusinessCardV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->firstname->value); - $this->assertNull($prediction->lastname->value); - $this->assertNull($prediction->jobTitle->value); - $this->assertNull($prediction->company->value); - $this->assertNull($prediction->email->value); - $this->assertNull($prediction->phoneNumber->value); - $this->assertNull($prediction->mobileNumber->value); - $this->assertNull($prediction->faxNumber->value); - $this->assertNull($prediction->address->value); - $this->assertNull($prediction->website->value); - $this->assertEquals(0, count($prediction->socialMedia)); + self::assertNull($prediction->firstname->value); + self::assertNull($prediction->lastname->value); + self::assertNull($prediction->jobTitle->value); + self::assertNull($prediction->company->value); + self::assertNull($prediction->email->value); + self::assertNull($prediction->phoneNumber->value); + self::assertNull($prediction->mobileNumber->value); + self::assertNull($prediction->faxNumber->value); + self::assertNull($prediction->address->value); + self::assertNull($prediction->website->value); + self::assertCount(0, $prediction->socialMedia); } } diff --git a/tests/V1/Product/Cropper/CropperV1Test.php b/tests/V1/Product/Cropper/CropperV1Test.php index 2807bd2d..f1af6ef3 100644 --- a/tests/V1/Product/Cropper/CropperV1Test.php +++ b/tests/V1/Product/Cropper/CropperV1Test.php @@ -1,11 +1,15 @@ completeDoc = new Document(Cropper\CropperV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Cropper\CropperV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(Cropper\CropperV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(CropperV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(CropperV1::class, $emptyDocJSON["document"]); + $this->completePage0 = new Page(CropperV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->pages[0]->prediction; - $this->assertEquals(0, count($prediction->cropping)); + self::assertCount(0, $prediction->cropping); } - public function testCompletePage0() + public function testCompletePage0(): void { - $this->assertEquals(0, $this->completePage0->id); - $this->assertEquals($this->completePage0Reference, strval($this->completePage0)); + self::assertSame(0, $this->completePage0->id); + self::assertSame($this->completePage0Reference, (string) ($this->completePage0)); } } diff --git a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php deleted file mode 100644 index 2ff3f366..00000000 --- a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php +++ /dev/null @@ -1,43 +0,0 @@ -completeDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->deliveryDate->value); - $this->assertNull($prediction->deliveryNumber->value); - $this->assertNull($prediction->supplierName->value); - $this->assertNull($prediction->supplierAddress->value); - $this->assertNull($prediction->customerName->value); - $this->assertNull($prediction->customerAddress->value); - $this->assertNull($prediction->totalAmount->value); - } -} diff --git a/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php b/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php index 729fb748..7d674eef 100644 --- a/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php +++ b/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(DriverLicense\DriverLicenseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(DriverLicense\DriverLicenseV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(DriverLicenseV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(DriverLicenseV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->countryCode->value); - $this->assertNull($prediction->state->value); - $this->assertNull($prediction->id->value); - $this->assertNull($prediction->category->value); - $this->assertNull($prediction->lastName->value); - $this->assertNull($prediction->firstName->value); - $this->assertNull($prediction->dateOfBirth->value); - $this->assertNull($prediction->placeOfBirth->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->issuedDate->value); - $this->assertNull($prediction->issuingAuthority->value); - $this->assertNull($prediction->mrz->value); - $this->assertNull($prediction->ddNumber->value); + self::assertNull($prediction->countryCode->value); + self::assertNull($prediction->state->value); + self::assertNull($prediction->id->value); + self::assertNull($prediction->category->value); + self::assertNull($prediction->lastName->value); + self::assertNull($prediction->firstName->value); + self::assertNull($prediction->dateOfBirth->value); + self::assertNull($prediction->placeOfBirth->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->issuedDate->value); + self::assertNull($prediction->issuingAuthority->value); + self::assertNull($prediction->mrz->value); + self::assertNull($prediction->ddNumber->value); } } diff --git a/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php b/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php index 6182e57b..9a37dce4 100644 --- a/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php +++ b/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php @@ -1,11 +1,15 @@ completeDocInvoice = new Document(FinancialDocument\FinancialDocumentV1::class, $completeDocJSONInvoice["document"]); - $this->completeDocReceipt = new Document(FinancialDocument\FinancialDocumentV1::class, $completeDocJSONReceipt["document"]); - $this->emptyDoc = new Document(FinancialDocument\FinancialDocumentV1::class, $emptyDocJSON["document"]); - $this->completePage0Invoice = new Page(FinancialDocument\FinancialDocumentV1Document::class, $completeDocJSONInvoice["document"]["inference"]["pages"][0]); - $this->completePage0Receipt = new Page(FinancialDocument\FinancialDocumentV1Document::class, $completeDocJSONReceipt["document"]["inference"]["pages"][0]); + $this->completeDocInvoice = new Document(FinancialDocumentV1::class, $completeDocJSONInvoice["document"]); + $this->completeDocReceipt = new Document(FinancialDocumentV1::class, $completeDocJSONReceipt["document"]); + $this->emptyDoc = new Document(FinancialDocumentV1::class, $emptyDocJSON["document"]); + $this->completePage0Invoice = new Page(FinancialDocumentV1Document::class, $completeDocJSONInvoice["document"]["inference"]["pages"][0]); + $this->completePage0Receipt = new Page(FinancialDocumentV1Document::class, $completeDocJSONReceipt["document"]["inference"]["pages"][0]); $this->completeDocReferenceInvoice = file_get_contents($productDir . "summary_full_invoice.rst"); $this->completeDocReferenceReceipt = file_get_contents($productDir . "summary_full_receipt.rst"); $this->completePage0ReferenceInvoice = file_get_contents($productDir . "summary_page0_invoice.rst"); $this->completePage0ReferenceReceipt = file_get_contents($productDir . "summary_page0_receipt.rst"); } - public function testCompleteDocInvoice() + public function testCompleteDocInvoice(): void { - $this->assertEquals($this->completeDocReferenceInvoice, strval($this->completeDocInvoice)); + self::assertSame($this->completeDocReferenceInvoice, (string) ($this->completeDocInvoice)); } - public function testCompleteDocReceipt() + public function testCompleteDocReceipt(): void { - $this->assertEquals($this->completeDocReferenceReceipt, strval($this->completeDocReceipt)); + self::assertSame($this->completeDocReferenceReceipt, (string) ($this->completeDocReceipt)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->locale->value); - $this->assertNull($prediction->invoiceNumber->value); - $this->assertEquals(0, count($prediction->referenceNumbers)); - $this->assertNull($prediction->date->value); - $this->assertNull($prediction->dueDate->value); - $this->assertNull($prediction->totalNet->value); - $this->assertNull($prediction->totalAmount->value); - $this->assertEquals(0, count($prediction->taxes)); - $this->assertEquals(0, count($prediction->supplierPaymentDetails)); - $this->assertNull($prediction->supplierName->value); - $this->assertEquals(0, count($prediction->supplierCompanyRegistrations)); - $this->assertNull($prediction->supplierAddress->value); - $this->assertNull($prediction->customerName->value); - $this->assertEquals(0, count($prediction->customerCompanyRegistrations)); - $this->assertNull($prediction->customerAddress->value); - $this->assertEquals(0, count($prediction->lineItems)); - $this->assertNull($prediction->totalTax->value); - $this->assertNull($prediction->billingAddress->value); - $this->assertNull($prediction->documentNumber->value); - $this->assertEquals("EXPENSE RECEIPT", $prediction->documentType->value); - $this->assertEquals("EXPENSE RECEIPT", $prediction->documentTypeExtended->value); - $this->assertNull($prediction->customerId->value); - $this->assertNull($prediction->tip->value); - $this->assertNull($prediction->time->value); + self::assertNull($prediction->locale->value); + self::assertNull($prediction->invoiceNumber->value); + self::assertCount(0, $prediction->referenceNumbers); + self::assertNull($prediction->date->value); + self::assertNull($prediction->dueDate->value); + self::assertNull($prediction->totalNet->value); + self::assertNull($prediction->totalAmount->value); + self::assertCount(0, $prediction->taxes); + self::assertCount(0, $prediction->supplierPaymentDetails); + self::assertNull($prediction->supplierName->value); + self::assertCount(0, $prediction->supplierCompanyRegistrations); + self::assertNull($prediction->supplierAddress->value); + self::assertNull($prediction->customerName->value); + self::assertCount(0, $prediction->customerCompanyRegistrations); + self::assertNull($prediction->customerAddress->value); + self::assertCount(0, $prediction->lineItems); + self::assertNull($prediction->totalTax->value); + self::assertNull($prediction->billingAddress->value); + self::assertNull($prediction->documentNumber->value); + self::assertSame("EXPENSE RECEIPT", $prediction->documentType->value); + self::assertSame("EXPENSE RECEIPT", $prediction->documentTypeExtended->value); + self::assertNull($prediction->customerId->value); + self::assertNull($prediction->tip->value); + self::assertNull($prediction->time->value); } - public function testCompletePage0Invoice() + public function testCompletePage0Invoice(): void { - $this->assertEquals(0, $this->completePage0Invoice->id); - $this->assertEquals($this->completePage0ReferenceInvoice, strval($this->completePage0Invoice)); + self::assertSame(0, $this->completePage0Invoice->id); + self::assertSame($this->completePage0ReferenceInvoice, (string) ($this->completePage0Invoice)); } - public function testCompletePage0Receipt() + public function testCompletePage0Receipt(): void { - $this->assertEquals(0, $this->completePage0Receipt->id); - $this->assertEquals($this->completePage0ReferenceReceipt, strval($this->completePage0Receipt)); + self::assertSame(0, $this->completePage0Receipt->id); + self::assertSame($this->completePage0ReferenceReceipt, (string) ($this->completePage0Receipt)); } } diff --git a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php index 0a06bfd2..4233e042 100644 --- a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php +++ b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(BankAccountDetails\BankAccountDetailsV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankAccountDetails\BankAccountDetailsV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(BankAccountDetailsV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BankAccountDetailsV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->iban->value); - $this->assertNull($prediction->accountHolderName->value); - $this->assertNull($prediction->swift->value); + self::assertNull($prediction->iban->value); + self::assertNull($prediction->accountHolderName->value); + self::assertNull($prediction->swift->value); } } diff --git a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php index 3e6d129e..63d43ebc 100644 --- a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php +++ b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(BankAccountDetails\BankAccountDetailsV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankAccountDetails\BankAccountDetailsV2::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(BankAccountDetailsV2::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BankAccountDetailsV2::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->accountHoldersNames->value); - $this->assertNull($prediction->bban->bbanBankCode); - $this->assertNull($prediction->bban->bbanBranchCode); - $this->assertNull($prediction->bban->bbanKey); - $this->assertNull($prediction->bban->bbanNumber); - $this->assertNull($prediction->iban->value); - $this->assertNull($prediction->swiftCode->value); + self::assertNull($prediction->accountHoldersNames->value); + self::assertNull($prediction->bban->bbanBankCode); + self::assertNull($prediction->bban->bbanBranchCode); + self::assertNull($prediction->bban->bbanKey); + self::assertNull($prediction->bban->bbanNumber); + self::assertNull($prediction->iban->value); + self::assertNull($prediction->swiftCode->value); } } diff --git a/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php b/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php index ce17ea28..db013e0e 100644 --- a/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php +++ b/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(CarteGrise\CarteGriseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(CarteGrise\CarteGriseV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(CarteGriseV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(CarteGriseV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->a->value); - $this->assertNull($prediction->b->value); - $this->assertNull($prediction->c1->value); - $this->assertNull($prediction->c3->value); - $this->assertNull($prediction->c41->value); - $this->assertNull($prediction->c4A->value); - $this->assertNull($prediction->d1->value); - $this->assertNull($prediction->d3->value); - $this->assertNull($prediction->e->value); - $this->assertNull($prediction->f1->value); - $this->assertNull($prediction->f2->value); - $this->assertNull($prediction->f3->value); - $this->assertNull($prediction->g->value); - $this->assertNull($prediction->g1->value); - $this->assertNull($prediction->i->value); - $this->assertNull($prediction->j->value); - $this->assertNull($prediction->j1->value); - $this->assertNull($prediction->j2->value); - $this->assertNull($prediction->j3->value); - $this->assertNull($prediction->p1->value); - $this->assertNull($prediction->p2->value); - $this->assertNull($prediction->p3->value); - $this->assertNull($prediction->p6->value); - $this->assertNull($prediction->q->value); - $this->assertNull($prediction->s1->value); - $this->assertNull($prediction->s2->value); - $this->assertNull($prediction->u1->value); - $this->assertNull($prediction->u2->value); - $this->assertNull($prediction->v7->value); - $this->assertNull($prediction->x1->value); - $this->assertNull($prediction->y1->value); - $this->assertNull($prediction->y2->value); - $this->assertNull($prediction->y3->value); - $this->assertNull($prediction->y4->value); - $this->assertNull($prediction->y5->value); - $this->assertNull($prediction->y6->value); - $this->assertNull($prediction->formulaNumber->value); - $this->assertNull($prediction->ownerFirstName->value); - $this->assertNull($prediction->ownerSurname->value); - $this->assertNull($prediction->mrz1->value); - $this->assertNull($prediction->mrz2->value); + self::assertNull($prediction->a->value); + self::assertNull($prediction->b->value); + self::assertNull($prediction->c1->value); + self::assertNull($prediction->c3->value); + self::assertNull($prediction->c41->value); + self::assertNull($prediction->c4A->value); + self::assertNull($prediction->d1->value); + self::assertNull($prediction->d3->value); + self::assertNull($prediction->e->value); + self::assertNull($prediction->f1->value); + self::assertNull($prediction->f2->value); + self::assertNull($prediction->f3->value); + self::assertNull($prediction->g->value); + self::assertNull($prediction->g1->value); + self::assertNull($prediction->i->value); + self::assertNull($prediction->j->value); + self::assertNull($prediction->j1->value); + self::assertNull($prediction->j2->value); + self::assertNull($prediction->j3->value); + self::assertNull($prediction->p1->value); + self::assertNull($prediction->p2->value); + self::assertNull($prediction->p3->value); + self::assertNull($prediction->p6->value); + self::assertNull($prediction->q->value); + self::assertNull($prediction->s1->value); + self::assertNull($prediction->s2->value); + self::assertNull($prediction->u1->value); + self::assertNull($prediction->u2->value); + self::assertNull($prediction->v7->value); + self::assertNull($prediction->x1->value); + self::assertNull($prediction->y1->value); + self::assertNull($prediction->y2->value); + self::assertNull($prediction->y3->value); + self::assertNull($prediction->y4->value); + self::assertNull($prediction->y5->value); + self::assertNull($prediction->y6->value); + self::assertNull($prediction->formulaNumber->value); + self::assertNull($prediction->ownerFirstName->value); + self::assertNull($prediction->ownerSurname->value); + self::assertNull($prediction->mrz1->value); + self::assertNull($prediction->mrz2->value); } } diff --git a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php b/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php deleted file mode 100644 index 20c64e57..00000000 --- a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php +++ /dev/null @@ -1,54 +0,0 @@ -completeDoc = new Document(EnergyBill\EnergyBillV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(EnergyBill\EnergyBillV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->invoiceNumber->value); - $this->assertNull($prediction->contractId->value); - $this->assertNull($prediction->deliveryPoint->value); - $this->assertNull($prediction->invoiceDate->value); - $this->assertNull($prediction->dueDate->value); - $this->assertNull($prediction->totalBeforeTaxes->value); - $this->assertNull($prediction->totalTaxes->value); - $this->assertNull($prediction->totalAmount->value); - $this->assertNull($prediction->energySupplier->address); - $this->assertNull($prediction->energySupplier->name); - $this->assertNull($prediction->energyConsumer->address); - $this->assertNull($prediction->energyConsumer->name); - $this->assertEquals(0, count($prediction->subscription)); - $this->assertEquals(0, count($prediction->energyUsage)); - $this->assertEquals(0, count($prediction->taxesAndContributions)); - $this->assertNull($prediction->meterDetails->meterNumber); - $this->assertNull($prediction->meterDetails->meterType); - $this->assertNull($prediction->meterDetails->unit); - } -} diff --git a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php b/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php deleted file mode 100644 index b9e53ab8..00000000 --- a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php +++ /dev/null @@ -1,40 +0,0 @@ -completeDoc = new Document(HealthCard\HealthCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthCard\HealthCardV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->socialSecurity->value); - $this->assertNull($prediction->issuanceDate->value); - } -} diff --git a/tests/V1/Product/Fr/IdCard/IdCardV1Test.php b/tests/V1/Product/Fr/IdCard/IdCardV1Test.php index 41e5060f..0db944aa 100644 --- a/tests/V1/Product/Fr/IdCard/IdCardV1Test.php +++ b/tests/V1/Product/Fr/IdCard/IdCardV1Test.php @@ -1,11 +1,15 @@ completeDoc = new Document(IdCard\IdCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IdCard\IdCardV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(IdCard\IdCardV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(IdCardV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(IdCardV1::class, $emptyDocJSON["document"]); + $this->completePage0 = new Page(IdCardV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->idNumber->value); - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->birthDate->value); - $this->assertNull($prediction->birthPlace->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->authority->value); - $this->assertNull($prediction->gender->value); - $this->assertNull($prediction->mrz1->value); - $this->assertNull($prediction->mrz2->value); + self::assertNull($prediction->idNumber->value); + self::assertCount(0, $prediction->givenNames); + self::assertNull($prediction->surname->value); + self::assertNull($prediction->birthDate->value); + self::assertNull($prediction->birthPlace->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->authority->value); + self::assertNull($prediction->gender->value); + self::assertNull($prediction->mrz1->value); + self::assertNull($prediction->mrz2->value); } - public function testCompletePage0() + public function testCompletePage0(): void { - $this->assertEquals(0, $this->completePage0->id); - $this->assertEquals($this->completePage0Reference, strval($this->completePage0)); + self::assertSame(0, $this->completePage0->id); + self::assertSame($this->completePage0Reference, (string) ($this->completePage0)); } } diff --git a/tests/V1/Product/Fr/IdCard/IdCardV2Test.php b/tests/V1/Product/Fr/IdCard/IdCardV2Test.php index 74bdf21b..8e470ed5 100644 --- a/tests/V1/Product/Fr/IdCard/IdCardV2Test.php +++ b/tests/V1/Product/Fr/IdCard/IdCardV2Test.php @@ -1,11 +1,15 @@ completeDoc = new Document(IdCard\IdCardV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IdCard\IdCardV2::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(IdCard\IdCardV2Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(IdCardV2::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(IdCardV2::class, $emptyDocJSON["document"]); + $this->completePage0 = new Page(IdCardV2Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->nationality->value); - $this->assertNull($prediction->cardAccessNumber->value); - $this->assertNull($prediction->documentNumber->value); - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->alternateName->value); - $this->assertNull($prediction->birthDate->value); - $this->assertNull($prediction->birthPlace->value); - $this->assertNull($prediction->gender->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->mrz1->value); - $this->assertNull($prediction->mrz2->value); - $this->assertNull($prediction->mrz3->value); - $this->assertNull($prediction->issueDate->value); - $this->assertNull($prediction->authority->value); + self::assertNull($prediction->nationality->value); + self::assertNull($prediction->cardAccessNumber->value); + self::assertNull($prediction->documentNumber->value); + self::assertCount(0, $prediction->givenNames); + self::assertNull($prediction->surname->value); + self::assertNull($prediction->alternateName->value); + self::assertNull($prediction->birthDate->value); + self::assertNull($prediction->birthPlace->value); + self::assertNull($prediction->gender->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->mrz1->value); + self::assertNull($prediction->mrz2->value); + self::assertNull($prediction->mrz3->value); + self::assertNull($prediction->issueDate->value); + self::assertNull($prediction->authority->value); } - public function testCompletePage0() + public function testCompletePage0(): void { - $this->assertEquals(0, $this->completePage0->id); - $this->assertEquals($this->completePage0Reference, strval($this->completePage0)); + self::assertSame(0, $this->completePage0->id); + self::assertSame($this->completePage0Reference, (string) ($this->completePage0)); } } diff --git a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php b/tests/V1/Product/Fr/Payslip/PayslipV3Test.php deleted file mode 100644 index 1dd77e2d..00000000 --- a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php +++ /dev/null @@ -1,77 +0,0 @@ -completeDoc = new Document(Payslip\PayslipV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Payslip\PayslipV3::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->payPeriod->endDate); - $this->assertNull($prediction->payPeriod->month); - $this->assertNull($prediction->payPeriod->paymentDate); - $this->assertNull($prediction->payPeriod->startDate); - $this->assertNull($prediction->payPeriod->year); - $this->assertNull($prediction->employee->address); - $this->assertNull($prediction->employee->dateOfBirth); - $this->assertNull($prediction->employee->firstName); - $this->assertNull($prediction->employee->lastName); - $this->assertNull($prediction->employee->phoneNumber); - $this->assertNull($prediction->employee->registrationNumber); - $this->assertNull($prediction->employee->socialSecurityNumber); - $this->assertNull($prediction->employer->address); - $this->assertNull($prediction->employer->companyId); - $this->assertNull($prediction->employer->companySite); - $this->assertNull($prediction->employer->nafCode); - $this->assertNull($prediction->employer->name); - $this->assertNull($prediction->employer->phoneNumber); - $this->assertNull($prediction->employer->urssafNumber); - $this->assertNull($prediction->bankAccountDetails->bankName); - $this->assertNull($prediction->bankAccountDetails->iban); - $this->assertNull($prediction->bankAccountDetails->swift); - $this->assertNull($prediction->employment->category); - $this->assertNull($prediction->employment->coefficient); - $this->assertNull($prediction->employment->collectiveAgreement); - $this->assertNull($prediction->employment->jobTitle); - $this->assertNull($prediction->employment->positionLevel); - $this->assertNull($prediction->employment->seniorityDate); - $this->assertNull($prediction->employment->startDate); - $this->assertEquals(0, count($prediction->salaryDetails)); - $this->assertNull($prediction->payDetail->grossSalary); - $this->assertNull($prediction->payDetail->grossSalaryYtd); - $this->assertNull($prediction->payDetail->incomeTaxRate); - $this->assertNull($prediction->payDetail->incomeTaxWithheld); - $this->assertNull($prediction->payDetail->netPaid); - $this->assertNull($prediction->payDetail->netPaidBeforeTax); - $this->assertNull($prediction->payDetail->netTaxable); - $this->assertNull($prediction->payDetail->netTaxableYtd); - $this->assertNull($prediction->payDetail->totalCostEmployer); - $this->assertNull($prediction->payDetail->totalTaxesAndDeductions); - $this->assertEquals(0, count($prediction->paidTimeOff)); - } -} diff --git a/tests/V1/Product/Generated/GeneratedV1Test.php b/tests/V1/Product/Generated/GeneratedV1Test.php index 3b812293..b12b80f7 100644 --- a/tests/V1/Product/Generated/GeneratedV1Test.php +++ b/tests/V1/Product/Generated/GeneratedV1Test.php @@ -1,17 +1,19 @@ internationalIdV1CompleteDoc = new Document( GeneratedV1::class, json_decode( - file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_international_id_v1.json"), + file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_international_id_v1.json"), true )["document"] ); @@ -34,7 +36,7 @@ protected function setUp(): void $this->internationalIdV1EmptyDoc = new Document( GeneratedV1::class, json_decode( - file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/empty_international_id_v1.json"), + file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/empty_international_id_v1.json"), true )["document"] ); @@ -42,7 +44,7 @@ protected function setUp(): void $this->invoiceV4EmptyDoc = new Document( GeneratedV1::class, json_decode( - file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/empty_invoice_v4.json"), + file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/empty_invoice_v4.json"), true )["document"] ); @@ -50,13 +52,13 @@ protected function setUp(): void $this->invoiceV4CompleteDoc = new Document( GeneratedV1::class, json_decode( - file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_invoice_v4.json"), + file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_invoice_v4.json"), true )["document"] ); $jsonData = json_decode( - file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_invoice_v4.json"), + file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/complete_invoice_v4.json"), true ); $this->invoiceV4Page0 = new Page( @@ -67,320 +69,316 @@ protected function setUp(): void public function testInternationalIdV1EmptyDoc(): void { - $docStr = file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_empty_international_id_v1.rst"); + $docStr = file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_empty_international_id_v1.rst"); $fields = $this->internationalIdV1EmptyDoc->inference->prediction->fields; - $this->assertInstanceOf(StringField::class, $fields["document_type"]); - $this->assertNull($fields["document_type"]->value); + self::assertInstanceOf(StringField::class, $fields["document_type"]); + self::assertNull($fields["document_type"]->value); - $this->assertInstanceOf(StringField::class, $fields["document_number"]); - $this->assertNull($fields["document_number"]->value); + self::assertInstanceOf(StringField::class, $fields["document_number"]); + self::assertNull($fields["document_number"]->value); - $this->assertInstanceOf(StringField::class, $fields["country_of_issue"]); - $this->assertNull($fields["country_of_issue"]->value); + self::assertInstanceOf(StringField::class, $fields["country_of_issue"]); + self::assertNull($fields["country_of_issue"]->value); - $this->assertInstanceOf(GeneratedListField::class, $fields["surnames"]); - $this->assertCount(0, $fields["surnames"]->values); + self::assertInstanceOf(GeneratedListField::class, $fields["surnames"]); + self::assertCount(0, $fields["surnames"]->values); - $this->assertInstanceOf(GeneratedListField::class, $fields["given_names"]); - $this->assertCount(0, $fields["given_names"]->values); + self::assertInstanceOf(GeneratedListField::class, $fields["given_names"]); + self::assertCount(0, $fields["given_names"]->values); - $this->assertInstanceOf(StringField::class, $fields["sex"]); - $this->assertNull($fields["sex"]->value); + self::assertInstanceOf(StringField::class, $fields["sex"]); + self::assertNull($fields["sex"]->value); - $this->assertInstanceOf(StringField::class, $fields["birth_date"]); - $this->assertNull($fields["birth_date"]->value); + self::assertInstanceOf(StringField::class, $fields["birth_date"]); + self::assertNull($fields["birth_date"]->value); - $this->assertInstanceOf(StringField::class, $fields["birth_place"]); - $this->assertNull($fields["birth_place"]->value); + self::assertInstanceOf(StringField::class, $fields["birth_place"]); + self::assertNull($fields["birth_place"]->value); - $this->assertInstanceOf(StringField::class, $fields["nationality"]); - $this->assertNull($fields["nationality"]->value); + self::assertInstanceOf(StringField::class, $fields["nationality"]); + self::assertNull($fields["nationality"]->value); - $this->assertInstanceOf(StringField::class, $fields["issue_date"]); - $this->assertNull($fields["issue_date"]->value); + self::assertInstanceOf(StringField::class, $fields["issue_date"]); + self::assertNull($fields["issue_date"]->value); - $this->assertInstanceOf(StringField::class, $fields["expiry_date"]); - $this->assertNull($fields["expiry_date"]->value); + self::assertInstanceOf(StringField::class, $fields["expiry_date"]); + self::assertNull($fields["expiry_date"]->value); - $this->assertInstanceOf(StringField::class, $fields["address"]); - $this->assertNull($fields["address"]->value); + self::assertInstanceOf(StringField::class, $fields["address"]); + self::assertNull($fields["address"]->value); - $this->assertInstanceOf(StringField::class, $fields["mrz1"]); - $this->assertNull($fields["mrz1"]->value); + self::assertInstanceOf(StringField::class, $fields["mrz1"]); + self::assertNull($fields["mrz1"]->value); - $this->assertInstanceOf(StringField::class, $fields["mrz2"]); - $this->assertNull($fields["mrz2"]->value); + self::assertInstanceOf(StringField::class, $fields["mrz2"]); + self::assertNull($fields["mrz2"]->value); - $this->assertInstanceOf(StringField::class, $fields["mrz3"]); - $this->assertNull($fields["mrz3"]->value); + self::assertInstanceOf(StringField::class, $fields["mrz3"]); + self::assertNull($fields["mrz3"]->value); - $this->assertSame((string)$this->internationalIdV1EmptyDoc, $docStr); + self::assertSame((string) $this->internationalIdV1EmptyDoc, $docStr); } public function testInternationalIdV1CompleteDoc(): void { - $docStr = file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_full_international_id_v1.rst"); + $docStr = file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_full_international_id_v1.rst"); $fields = $this->internationalIdV1CompleteDoc->inference->prediction->fields; - $this->assertInstanceOf(StringField::class, $fields["document_type"]); - $this->assertSame($fields["document_type"]->value, "NATIONAL_ID_CARD"); + self::assertInstanceOf(StringField::class, $fields["document_type"]); + self::assertSame($fields["document_type"]->value, "NATIONAL_ID_CARD"); - $this->assertInstanceOf(StringField::class, $fields["document_number"]); - $this->assertSame($fields["document_number"]->value, "99999999R"); + self::assertInstanceOf(StringField::class, $fields["document_number"]); + self::assertSame($fields["document_number"]->value, "99999999R"); - $this->assertInstanceOf(StringField::class, $fields["country_of_issue"]); - $this->assertSame($fields["country_of_issue"]->value, "ESP"); + self::assertInstanceOf(StringField::class, $fields["country_of_issue"]); + self::assertSame($fields["country_of_issue"]->value, "ESP"); - $this->assertInstanceOf(GeneratedListField::class, $fields["surnames"]); - $this->assertSame($fields["surnames"]->values[0]->value, "ESPAÑOLA"); - $this->assertSame($fields["surnames"]->values[1]->value, "ESPAÑOLA"); + self::assertInstanceOf(GeneratedListField::class, $fields["surnames"]); + self::assertSame($fields["surnames"]->values[0]->value, "ESPAÑOLA"); + self::assertSame($fields["surnames"]->values[1]->value, "ESPAÑOLA"); - $this->assertInstanceOf(GeneratedListField::class, $fields["given_names"]); - $this->assertSame($fields["given_names"]->values[0]->value, "CARMEN"); + self::assertInstanceOf(GeneratedListField::class, $fields["given_names"]); + self::assertSame($fields["given_names"]->values[0]->value, "CARMEN"); - $this->assertInstanceOf(StringField::class, $fields["sex"]); - $this->assertSame($fields["sex"]->value, "F"); + self::assertInstanceOf(StringField::class, $fields["sex"]); + self::assertSame($fields["sex"]->value, "F"); - $this->assertInstanceOf(StringField::class, $fields["birth_date"]); - $this->assertSame($fields["birth_date"]->value, "1980-01-01"); + self::assertInstanceOf(StringField::class, $fields["birth_date"]); + self::assertSame($fields["birth_date"]->value, "1980-01-01"); - $this->assertInstanceOf(StringField::class, $fields["birth_place"]); - $this->assertSame($fields["birth_place"]->value, "MADRID"); + self::assertInstanceOf(StringField::class, $fields["birth_place"]); + self::assertSame($fields["birth_place"]->value, "MADRID"); - $this->assertInstanceOf(StringField::class, $fields["nationality"]); - $this->assertSame($fields["nationality"]->value, "ESP"); + self::assertInstanceOf(StringField::class, $fields["nationality"]); + self::assertSame($fields["nationality"]->value, "ESP"); - $this->assertInstanceOf(StringField::class, $fields["issue_date"]); - $this->assertSame($fields["issue_date"]->value, "2015-01-01"); + self::assertInstanceOf(StringField::class, $fields["issue_date"]); + self::assertSame($fields["issue_date"]->value, "2015-01-01"); - $this->assertInstanceOf(StringField::class, $fields["expiry_date"]); - $this->assertSame($fields["expiry_date"]->value, "2025-01-01"); + self::assertInstanceOf(StringField::class, $fields["expiry_date"]); + self::assertSame($fields["expiry_date"]->value, "2025-01-01"); - $this->assertInstanceOf(StringField::class, $fields["address"]); - $this->assertSame($fields["address"]->value, "AVDA DE MADRID S-N MADRID MADRID"); + self::assertInstanceOf(StringField::class, $fields["address"]); + self::assertSame($fields["address"]->value, "AVDA DE MADRID S-N MADRID MADRID"); - $this->assertInstanceOf(StringField::class, $fields["mrz1"]); - $this->assertSame($fields["mrz1"]->value, "IDESPBAA000589599999999R<<<<<<"); + self::assertInstanceOf(StringField::class, $fields["mrz1"]); + self::assertSame($fields["mrz1"]->value, "IDESPBAA000589599999999R<<<<<<"); - $this->assertInstanceOf(StringField::class, $fields["mrz2"]); - $this->assertSame($fields["mrz2"]->value, "8001014F2501017ESP<<<<<<<<<<<7"); + self::assertInstanceOf(StringField::class, $fields["mrz2"]); + self::assertSame($fields["mrz2"]->value, "8001014F2501017ESP<<<<<<<<<<<7"); - $this->assertInstanceOf(StringField::class, $fields["mrz3"]); - $this->assertSame($fields["mrz3"]->value, "ESPANOLAvalue, "ESPANOLAassertSame((string)$this->internationalIdV1CompleteDoc, $docStr); + self::assertSame((string) $this->internationalIdV1CompleteDoc, $docStr); } public function testInvoiceV4CompleteDoc(): void { - $docStr = file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_full_invoice_v4.rst"); + $docStr = file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_full_invoice_v4.rst"); $fields = $this->invoiceV4CompleteDoc->inference->prediction->fields; - $this->assertInstanceOf(StringField::class, $fields["customer_address"]); - $this->assertSame($fields["customer_address"]->value, "1954 Bloon Street West Toronto, ON, M6P 3K9 Canada"); + self::assertInstanceOf(StringField::class, $fields["customer_address"]); + self::assertSame($fields["customer_address"]->value, "1954 Bloon Street West Toronto, ON, M6P 3K9 Canada"); - $this->assertInstanceOf(GeneratedListField::class, $fields["customer_company_registrations"]); - $this->assertCount(0, $fields["customer_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $fields["customer_company_registrations"]); + self::assertCount(0, $fields["customer_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $fields["customer_name"]); - $this->assertSame($fields["customer_name"]->value, "JIRO DOI"); + self::assertInstanceOf(StringField::class, $fields["customer_name"]); + self::assertSame($fields["customer_name"]->value, "JIRO DOI"); - $this->assertInstanceOf(StringField::class, $fields["date"]); - $this->assertSame($fields["date"]->value, "2020-02-17"); + self::assertInstanceOf(StringField::class, $fields["date"]); + self::assertSame($fields["date"]->value, "2020-02-17"); - $this->assertInstanceOf(StringField::class, $fields["document_type"]); - $this->assertSame($fields["document_type"]->value, "INVOICE"); + self::assertInstanceOf(StringField::class, $fields["document_type"]); + self::assertSame($fields["document_type"]->value, "INVOICE"); - $this->assertInstanceOf(StringField::class, $fields["due_date"]); - $this->assertSame($fields["due_date"]->value, "2020-02-17"); + self::assertInstanceOf(StringField::class, $fields["due_date"]); + self::assertSame($fields["due_date"]->value, "2020-02-17"); - $this->assertInstanceOf(StringField::class, $fields["invoice_number"]); - $this->assertSame($fields["invoice_number"]->value, "0042004801351"); + self::assertInstanceOf(StringField::class, $fields["invoice_number"]); + self::assertSame($fields["invoice_number"]->value, "0042004801351"); - $this->assertInstanceOf(GeneratedListField::class, $fields["line_items"]); - $this->assertInstanceOf(GeneratedObjectField::class, $fields["line_items"]->values[0]); - $this->assertSame($fields["line_items"]->values[0]->description, "S)BOIE 5X500 FEUILLES A4"); - $this->assertNull($fields["line_items"]->values[0]->product_code); - $this->assertNull($fields["line_items"]->values[0]->quantity); - $this->assertSame($fields["line_items"]->values[6]->quantity, "1.0"); - $this->assertNull($fields["line_items"]->values[0]->tax_amount); - $this->assertNull($fields["line_items"]->values[0]->tax_rate); - $this->assertSame($fields["line_items"]->values[0]->total_amount, "2.63"); - $this->assertNull($fields["line_items"]->values[0]->unit_price); - $this->assertSame($fields["line_items"]->values[6]->unit_price, "65.0"); + self::assertInstanceOf(GeneratedListField::class, $fields["line_items"]); + self::assertInstanceOf(GeneratedObjectField::class, $fields["line_items"]->values[0]); + self::assertSame($fields["line_items"]->values[0]->description, "S)BOIE 5X500 FEUILLES A4"); + self::assertNull($fields["line_items"]->values[0]->product_code); + self::assertNull($fields["line_items"]->values[0]->quantity); + self::assertSame($fields["line_items"]->values[6]->quantity, "1.0"); + self::assertNull($fields["line_items"]->values[0]->tax_amount); + self::assertNull($fields["line_items"]->values[0]->tax_rate); + self::assertSame($fields["line_items"]->values[0]->total_amount, "2.63"); + self::assertNull($fields["line_items"]->values[0]->unit_price); + self::assertSame($fields["line_items"]->values[6]->unit_price, "65.0"); - $this->assertInstanceOf(GeneratedObjectField::class, $fields["locale"]); - $this->assertSame($fields["locale"]->currency, "EUR"); - $this->assertSame($fields["locale"]->language, "fr"); + self::assertInstanceOf(GeneratedObjectField::class, $fields["locale"]); + self::assertSame($fields["locale"]->currency, "EUR"); + self::assertSame($fields["locale"]->language, "fr"); - $this->assertInstanceOf(GeneratedListField::class, $fields["reference_numbers"]); - $this->assertSame($fields["reference_numbers"]->values[0]->value, "AD29094"); + self::assertInstanceOf(GeneratedListField::class, $fields["reference_numbers"]); + self::assertSame($fields["reference_numbers"]->values[0]->value, "AD29094"); - $this->assertInstanceOf(StringField::class, $fields["supplier_address"]); - $this->assertSame($fields["supplier_address"]->value, "156 University Ave, Toronto ON, Canada M5H 2H7"); + self::assertInstanceOf(StringField::class, $fields["supplier_address"]); + self::assertSame($fields["supplier_address"]->value, "156 University Ave, Toronto ON, Canada M5H 2H7"); - $this->assertInstanceOf(GeneratedListField::class, $fields["supplier_company_registrations"]); - $this->assertCount(0, $fields["supplier_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $fields["supplier_company_registrations"]); + self::assertCount(0, $fields["supplier_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $fields["supplier_name"]); - $this->assertSame($fields["supplier_name"]->value, "TURNPIKE DESIGNS CO."); + self::assertInstanceOf(StringField::class, $fields["supplier_name"]); + self::assertSame($fields["supplier_name"]->value, "TURNPIKE DESIGNS CO."); - $this->assertInstanceOf(GeneratedListField::class, $fields["supplier_payment_details"]); - $this->assertSame($fields["supplier_payment_details"]->values[0]->iban, "FR7640254025476501124705368"); + self::assertInstanceOf(GeneratedListField::class, $fields["supplier_payment_details"]); + self::assertSame($fields["supplier_payment_details"]->values[0]->iban, "FR7640254025476501124705368"); - $this->assertInstanceOf(GeneratedListField::class, $fields["taxes"]); - $this->assertInstanceOf(PositionField::class, $fields["taxes"]->values[0]->polygon); - $this->assertSame( - array_map(function ($point) { - return [$point->getX(), $point->getY()]; - }, $fields["taxes"]->values[0]->polygon->value->getCoordinates()), + self::assertInstanceOf(GeneratedListField::class, $fields["taxes"]); + self::assertInstanceOf(PositionField::class, $fields["taxes"]->values[0]->polygon); + self::assertSame( + array_map(static fn($point) => [$point->getX(), $point->getY()], $fields["taxes"]->values[0]->polygon->value->getCoordinates()), [[0.292, 0.749], [0.543, 0.749], [0.543, 0.763], [0.292, 0.763]] ); - $this->assertSame($fields["taxes"]->values[0]->rate, "20.0"); - $this->assertSame($fields["taxes"]->values[0]->value, "97.98"); + self::assertSame($fields["taxes"]->values[0]->rate, "20.0"); + self::assertSame($fields["taxes"]->values[0]->value, "97.98"); - $this->assertInstanceOf(StringField::class, $fields["total_amount"]); - $this->assertSame($fields["total_amount"]->value, "587.95"); + self::assertInstanceOf(StringField::class, $fields["total_amount"]); + self::assertSame($fields["total_amount"]->value, "587.95"); - $this->assertInstanceOf(StringField::class, $fields["total_net"]); - $this->assertSame($fields["total_net"]->value, "489.97"); + self::assertInstanceOf(StringField::class, $fields["total_net"]); + self::assertSame($fields["total_net"]->value, "489.97"); - $this->assertSame((string)$this->invoiceV4CompleteDoc, $docStr); + self::assertSame((string) $this->invoiceV4CompleteDoc, $docStr); } - public function testInvoiceV4Page0() + public function testInvoiceV4Page0(): void { - $docStr = file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_page0_invoice_v4.rst"); + $docStr = file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_page0_invoice_v4.rst"); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["customer_address"]); - $this->assertNull($this->invoiceV4Page0->prediction->fields["customer_address"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["customer_address"]); + self::assertNull($this->invoiceV4Page0->prediction->fields["customer_address"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["customer_company_registrations"]); - $this->assertCount(0, $this->invoiceV4Page0->prediction->fields["customer_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["customer_company_registrations"]); + self::assertCount(0, $this->invoiceV4Page0->prediction->fields["customer_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["customer_name"]); - $this->assertNull($this->invoiceV4Page0->prediction->fields["customer_name"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["customer_name"]); + self::assertNull($this->invoiceV4Page0->prediction->fields["customer_name"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["date"]); - $this->assertEquals("2020-02-17", $this->invoiceV4Page0->prediction->fields["date"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["date"]); + self::assertSame("2020-02-17", $this->invoiceV4Page0->prediction->fields["date"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["document_type"]); - $this->assertEquals("INVOICE", $this->invoiceV4Page0->prediction->fields["document_type"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["document_type"]); + self::assertSame("INVOICE", $this->invoiceV4Page0->prediction->fields["document_type"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["due_date"]); - $this->assertEquals("2020-02-17", $this->invoiceV4Page0->prediction->fields["due_date"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["due_date"]); + self::assertSame("2020-02-17", $this->invoiceV4Page0->prediction->fields["due_date"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["invoice_number"]); - $this->assertEquals("0042004801351", $this->invoiceV4Page0->prediction->fields["invoice_number"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["invoice_number"]); + self::assertSame("0042004801351", $this->invoiceV4Page0->prediction->fields["invoice_number"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["line_items"]); - $this->assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]); - $this->assertEquals("S)BOIE 5X500 FEUILLES A4", $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->description); - $this->assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->product_code); - $this->assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->quantity); - $this->assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->tax_amount); - $this->assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->tax_rate); - $this->assertEquals("2.63", $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->total_amount); - $this->assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->unit_price); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["line_items"]); + self::assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]); + self::assertSame("S)BOIE 5X500 FEUILLES A4", $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->description); + self::assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->product_code); + self::assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->quantity); + self::assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->tax_amount); + self::assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->tax_rate); + self::assertSame("2.63", $this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->total_amount); + self::assertNull($this->invoiceV4Page0->prediction->fields["line_items"]->values[0]->unit_price); - $this->assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4Page0->prediction->fields["locale"]); - $this->assertEquals("EUR", $this->invoiceV4Page0->prediction->fields["locale"]->currency); - $this->assertEquals("fr", $this->invoiceV4Page0->prediction->fields["locale"]->language); + self::assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4Page0->prediction->fields["locale"]); + self::assertSame("EUR", $this->invoiceV4Page0->prediction->fields["locale"]->currency); + self::assertSame("fr", $this->invoiceV4Page0->prediction->fields["locale"]->language); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["reference_numbers"]); - $this->assertCount(0, $this->invoiceV4Page0->prediction->fields["reference_numbers"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["reference_numbers"]); + self::assertCount(0, $this->invoiceV4Page0->prediction->fields["reference_numbers"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["supplier_address"]); - $this->assertNull($this->invoiceV4Page0->prediction->fields["supplier_address"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["supplier_address"]); + self::assertNull($this->invoiceV4Page0->prediction->fields["supplier_address"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["supplier_company_registrations"]); - $this->assertCount(0, $this->invoiceV4Page0->prediction->fields["supplier_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["supplier_company_registrations"]); + self::assertCount(0, $this->invoiceV4Page0->prediction->fields["supplier_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["supplier_name"]); - $this->assertNull($this->invoiceV4Page0->prediction->fields["supplier_name"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["supplier_name"]); + self::assertNull($this->invoiceV4Page0->prediction->fields["supplier_name"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["supplier_payment_details"]); - $this->assertEquals("FR7640254025476501124705368", $this->invoiceV4Page0->prediction->fields["supplier_payment_details"]->values[0]->iban); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["supplier_payment_details"]); + self::assertSame("FR7640254025476501124705368", $this->invoiceV4Page0->prediction->fields["supplier_payment_details"]->values[0]->iban); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["taxes"]); - $this->assertInstanceOf(PositionField::class, $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->polygon); - $this->assertEquals([[0.292, 0.749], [0.543, 0.749], [0.543, 0.763], [0.292, 0.763]], array_map(function ($point) { - return [$point->getX(), $point->getY()]; - }, $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->polygon->value->getCoordinates())); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4Page0->prediction->fields["taxes"]); + self::assertInstanceOf(PositionField::class, $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->polygon); + self::assertSame([[0.292, 0.749], [0.543, 0.749], [0.543, 0.763], [0.292, 0.763]], array_map(static fn($point) => [$point->getX(), $point->getY()], $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->polygon->value->getCoordinates())); - $this->assertEquals("20.0", $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->rate); - $this->assertEquals("97.98", $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->value); + self::assertSame("20.0", $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->rate); + self::assertSame("97.98", $this->invoiceV4Page0->prediction->fields["taxes"]->values[0]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["total_amount"]); - $this->assertEquals("587.95", $this->invoiceV4Page0->prediction->fields["total_amount"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["total_net"]); - $this->assertEquals("489.97", $this->invoiceV4Page0->prediction->fields["total_net"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["total_amount"]); + self::assertSame("587.95", $this->invoiceV4Page0->prediction->fields["total_amount"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4Page0->prediction->fields["total_net"]); + self::assertSame("489.97", $this->invoiceV4Page0->prediction->fields["total_net"]->value); - $this->assertSame((string)$this->invoiceV4Page0, $docStr); + self::assertSame((string) $this->invoiceV4Page0, $docStr); } - public function testInvoiceV4EmptyDoc() + public function testInvoiceV4EmptyDoc(): void { - $docStr = file_get_contents(\TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_empty_invoice_v4.rst"); + $docStr = file_get_contents(TestingUtilities::getV1DataDir() . "/products/generated/response_v1/summary_empty_invoice_v4.rst"); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_address"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["customer_address"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_address"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["customer_address"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_company_registrations"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_company_registrations"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_name"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["customer_name"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["customer_name"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["customer_name"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["date"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["date"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["date"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["date"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["document_type"]); - $this->assertEquals("INVOICE", $this->invoiceV4EmptyDoc->inference->prediction->fields["document_type"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["document_type"]); + self::assertSame("INVOICE", $this->invoiceV4EmptyDoc->inference->prediction->fields["document_type"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["due_date"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["due_date"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["due_date"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["due_date"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["invoice_number"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["invoice_number"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["invoice_number"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["invoice_number"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["line_items"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["line_items"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["line_items"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["line_items"]->values); - $this->assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]->currency); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]->language); + self::assertInstanceOf(GeneratedObjectField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]->currency); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["locale"]->language); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["reference_numbers"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["reference_numbers"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["reference_numbers"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["reference_numbers"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_address"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_address"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_address"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_address"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_company_registrations"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_company_registrations"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_company_registrations"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_company_registrations"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_name"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_name"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_name"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_name"]->value); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_payment_details"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_payment_details"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_payment_details"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["supplier_payment_details"]->values); - $this->assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["taxes"]); - $this->assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["taxes"]->values); + self::assertInstanceOf(GeneratedListField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["taxes"]); + self::assertCount(0, $this->invoiceV4EmptyDoc->inference->prediction->fields["taxes"]->values); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["total_amount"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["total_amount"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["total_amount"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["total_amount"]->value); - $this->assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["total_net"]); - $this->assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["total_net"]->value); + self::assertInstanceOf(StringField::class, $this->invoiceV4EmptyDoc->inference->prediction->fields["total_net"]); + self::assertNull($this->invoiceV4EmptyDoc->inference->prediction->fields["total_net"]->value); - $this->assertEquals($docStr, strval($this->invoiceV4EmptyDoc)); + self::assertSame($docStr, (string) ($this->invoiceV4EmptyDoc)); } } diff --git a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php b/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php deleted file mode 100644 index 09e8735e..00000000 --- a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php +++ /dev/null @@ -1,57 +0,0 @@ -completeDoc = new Document(IndianPassport\IndianPassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IndianPassport\IndianPassportV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->country->value); - $this->assertNull($prediction->idNumber->value); - $this->assertNull($prediction->givenNames->value); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->birthDate->value); - $this->assertNull($prediction->birthPlace->value); - $this->assertNull($prediction->issuancePlace->value); - $this->assertNull($prediction->issuanceDate->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->mrz1->value); - $this->assertNull($prediction->mrz2->value); - $this->assertNull($prediction->legalGuardian->value); - $this->assertNull($prediction->nameOfSpouse->value); - $this->assertNull($prediction->nameOfMother->value); - $this->assertNull($prediction->oldPassportDateOfIssue->value); - $this->assertNull($prediction->oldPassportNumber->value); - $this->assertNull($prediction->oldPassportPlaceOfIssue->value); - $this->assertNull($prediction->address1->value); - $this->assertNull($prediction->address2->value); - $this->assertNull($prediction->address3->value); - $this->assertNull($prediction->fileNumber->value); - } -} diff --git a/tests/V1/Product/InternationalId/InternationalIdV2Test.php b/tests/V1/Product/InternationalId/InternationalIdV2Test.php index 82aeb855..4c2b4ed8 100644 --- a/tests/V1/Product/InternationalId/InternationalIdV2Test.php +++ b/tests/V1/Product/InternationalId/InternationalIdV2Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(InternationalId\InternationalIdV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(InternationalId\InternationalIdV2::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(InternationalIdV2::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(InternationalIdV2::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->documentNumber->value); - $this->assertEquals(0, count($prediction->surnames)); - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertNull($prediction->sex->value); - $this->assertNull($prediction->birthDate->value); - $this->assertNull($prediction->birthPlace->value); - $this->assertNull($prediction->nationality->value); - $this->assertNull($prediction->personalNumber->value); - $this->assertNull($prediction->countryOfIssue->value); - $this->assertNull($prediction->stateOfIssue->value); - $this->assertNull($prediction->issueDate->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->address->value); - $this->assertNull($prediction->mrzLine1->value); - $this->assertNull($prediction->mrzLine2->value); - $this->assertNull($prediction->mrzLine3->value); + self::assertNull($prediction->documentNumber->value); + self::assertCount(0, $prediction->surnames); + self::assertCount(0, $prediction->givenNames); + self::assertNull($prediction->sex->value); + self::assertNull($prediction->birthDate->value); + self::assertNull($prediction->birthPlace->value); + self::assertNull($prediction->nationality->value); + self::assertNull($prediction->personalNumber->value); + self::assertNull($prediction->countryOfIssue->value); + self::assertNull($prediction->stateOfIssue->value); + self::assertNull($prediction->issueDate->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->address->value); + self::assertNull($prediction->mrzLine1->value); + self::assertNull($prediction->mrzLine2->value); + self::assertNull($prediction->mrzLine3->value); } } diff --git a/tests/V1/Product/Invoice/InvoiceV4Test.php b/tests/V1/Product/Invoice/InvoiceV4Test.php index 5595e6c4..5c47e975 100644 --- a/tests/V1/Product/Invoice/InvoiceV4Test.php +++ b/tests/V1/Product/Invoice/InvoiceV4Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(Invoice\InvoiceV4::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Invoice\InvoiceV4::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(InvoiceV4::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(InvoiceV4::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->locale->value); - $this->assertNull($prediction->invoiceNumber->value); - $this->assertNull($prediction->poNumber->value); - $this->assertEquals(0, count($prediction->referenceNumbers)); - $this->assertNull($prediction->date->value); - $this->assertNull($prediction->dueDate->value); - $this->assertNull($prediction->paymentDate->value); - $this->assertNull($prediction->totalNet->value); - $this->assertNull($prediction->totalAmount->value); - $this->assertNull($prediction->totalTax->value); - $this->assertEquals(0, count($prediction->taxes)); - $this->assertEquals(0, count($prediction->supplierPaymentDetails)); - $this->assertNull($prediction->supplierName->value); - $this->assertEquals(0, count($prediction->supplierCompanyRegistrations)); - $this->assertNull($prediction->supplierAddress->value); - $this->assertNull($prediction->supplierPhoneNumber->value); - $this->assertNull($prediction->supplierWebsite->value); - $this->assertNull($prediction->supplierEmail->value); - $this->assertNull($prediction->customerName->value); - $this->assertEquals(0, count($prediction->customerCompanyRegistrations)); - $this->assertNull($prediction->customerAddress->value); - $this->assertNull($prediction->customerId->value); - $this->assertNull($prediction->shippingAddress->value); - $this->assertNull($prediction->billingAddress->value); - $this->assertEquals(0, count($prediction->lineItems)); + self::assertNull($prediction->locale->value); + self::assertNull($prediction->invoiceNumber->value); + self::assertNull($prediction->poNumber->value); + self::assertCount(0, $prediction->referenceNumbers); + self::assertNull($prediction->date->value); + self::assertNull($prediction->dueDate->value); + self::assertNull($prediction->paymentDate->value); + self::assertNull($prediction->totalNet->value); + self::assertNull($prediction->totalAmount->value); + self::assertNull($prediction->totalTax->value); + self::assertCount(0, $prediction->taxes); + self::assertCount(0, $prediction->supplierPaymentDetails); + self::assertNull($prediction->supplierName->value); + self::assertCount(0, $prediction->supplierCompanyRegistrations); + self::assertNull($prediction->supplierAddress->value); + self::assertNull($prediction->supplierPhoneNumber->value); + self::assertNull($prediction->supplierWebsite->value); + self::assertNull($prediction->supplierEmail->value); + self::assertNull($prediction->customerName->value); + self::assertCount(0, $prediction->customerCompanyRegistrations); + self::assertNull($prediction->customerAddress->value); + self::assertNull($prediction->customerId->value); + self::assertNull($prediction->shippingAddress->value); + self::assertNull($prediction->billingAddress->value); + self::assertCount(0, $prediction->lineItems); } } diff --git a/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php b/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php index 81d953cd..3bc4ed80 100644 --- a/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php +++ b/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(InvoiceSplitter\InvoiceSplitterV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(InvoiceSplitter\InvoiceSplitterV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(InvoiceSplitterV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(InvoiceSplitterV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertEquals(0, count($prediction->invoicePageGroups)); + self::assertCount(0, $prediction->invoicePageGroups); } } diff --git a/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php b/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php index d16f66f6..3af1af4c 100644 --- a/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php +++ b/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(MultiReceiptsDetectorV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(MultiReceiptsDetectorV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertEquals(0, count($prediction->receipts)); + self::assertCount(0, $prediction->receipts); } } diff --git a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php deleted file mode 100644 index ead37651..00000000 --- a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php +++ /dev/null @@ -1,74 +0,0 @@ -completeDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->servingPerBox->value); - $this->assertNull($prediction->servingSize->amount); - $this->assertNull($prediction->servingSize->unit); - $this->assertNull($prediction->calories->dailyValue); - $this->assertNull($prediction->calories->per100G); - $this->assertNull($prediction->calories->perServing); - $this->assertNull($prediction->totalFat->dailyValue); - $this->assertNull($prediction->totalFat->per100G); - $this->assertNull($prediction->totalFat->perServing); - $this->assertNull($prediction->saturatedFat->dailyValue); - $this->assertNull($prediction->saturatedFat->per100G); - $this->assertNull($prediction->saturatedFat->perServing); - $this->assertNull($prediction->transFat->dailyValue); - $this->assertNull($prediction->transFat->per100G); - $this->assertNull($prediction->transFat->perServing); - $this->assertNull($prediction->cholesterol->dailyValue); - $this->assertNull($prediction->cholesterol->per100G); - $this->assertNull($prediction->cholesterol->perServing); - $this->assertNull($prediction->totalCarbohydrate->dailyValue); - $this->assertNull($prediction->totalCarbohydrate->per100G); - $this->assertNull($prediction->totalCarbohydrate->perServing); - $this->assertNull($prediction->dietaryFiber->dailyValue); - $this->assertNull($prediction->dietaryFiber->per100G); - $this->assertNull($prediction->dietaryFiber->perServing); - $this->assertNull($prediction->totalSugars->dailyValue); - $this->assertNull($prediction->totalSugars->per100G); - $this->assertNull($prediction->totalSugars->perServing); - $this->assertNull($prediction->addedSugars->dailyValue); - $this->assertNull($prediction->addedSugars->per100G); - $this->assertNull($prediction->addedSugars->perServing); - $this->assertNull($prediction->protein->dailyValue); - $this->assertNull($prediction->protein->per100G); - $this->assertNull($prediction->protein->perServing); - $this->assertNull($prediction->sodium->dailyValue); - $this->assertNull($prediction->sodium->per100G); - $this->assertNull($prediction->sodium->perServing); - $this->assertNull($prediction->sodium->unit); - $this->assertEquals(0, count($prediction->nutrients)); - } -} diff --git a/tests/V1/Product/Passport/PassportV1Test.php b/tests/V1/Product/Passport/PassportV1Test.php index 7408188c..a3fc5296 100644 --- a/tests/V1/Product/Passport/PassportV1Test.php +++ b/tests/V1/Product/Passport/PassportV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(Passport\PassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Passport\PassportV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(PassportV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(PassportV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->country->value); - $this->assertNull($prediction->idNumber->value); - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->birthDate->value); - $this->assertNull($prediction->birthPlace->value); - $this->assertNull($prediction->gender->value); - $this->assertNull($prediction->issuanceDate->value); - $this->assertNull($prediction->expiryDate->value); - $this->assertNull($prediction->mrz1->value); - $this->assertNull($prediction->mrz2->value); + self::assertNull($prediction->country->value); + self::assertNull($prediction->idNumber->value); + self::assertCount(0, $prediction->givenNames); + self::assertNull($prediction->surname->value); + self::assertNull($prediction->birthDate->value); + self::assertNull($prediction->birthPlace->value); + self::assertNull($prediction->gender->value); + self::assertNull($prediction->issuanceDate->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->mrz1->value); + self::assertNull($prediction->mrz2->value); } } diff --git a/tests/V1/Product/Receipt/ReceiptV5Test.php b/tests/V1/Product/Receipt/ReceiptV5Test.php index 7e282df1..00e0b82e 100644 --- a/tests/V1/Product/Receipt/ReceiptV5Test.php +++ b/tests/V1/Product/Receipt/ReceiptV5Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(Receipt\ReceiptV5::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Receipt\ReceiptV5::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(ReceiptV5::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(ReceiptV5::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->locale->value); - $this->assertNull($prediction->date->value); - $this->assertNull($prediction->time->value); - $this->assertNull($prediction->totalAmount->value); - $this->assertNull($prediction->totalNet->value); - $this->assertNull($prediction->totalTax->value); - $this->assertNull($prediction->tip->value); - $this->assertEquals(0, count($prediction->taxes)); - $this->assertNull($prediction->supplierName->value); - $this->assertEquals(0, count($prediction->supplierCompanyRegistrations)); - $this->assertNull($prediction->supplierAddress->value); - $this->assertNull($prediction->supplierPhoneNumber->value); - $this->assertNull($prediction->receiptNumber->value); - $this->assertEquals(0, count($prediction->lineItems)); + self::assertNull($prediction->locale->value); + self::assertNull($prediction->date->value); + self::assertNull($prediction->time->value); + self::assertNull($prediction->totalAmount->value); + self::assertNull($prediction->totalNet->value); + self::assertNull($prediction->totalTax->value); + self::assertNull($prediction->tip->value); + self::assertCount(0, $prediction->taxes); + self::assertNull($prediction->supplierName->value); + self::assertCount(0, $prediction->supplierCompanyRegistrations); + self::assertNull($prediction->supplierAddress->value); + self::assertNull($prediction->supplierPhoneNumber->value); + self::assertNull($prediction->receiptNumber->value); + self::assertCount(0, $prediction->lineItems); } } diff --git a/tests/V1/Product/Resume/ResumeV1Test.php b/tests/V1/Product/Resume/ResumeV1Test.php index 876d4551..0dc24b2f 100644 --- a/tests/V1/Product/Resume/ResumeV1Test.php +++ b/tests/V1/Product/Resume/ResumeV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(Resume\ResumeV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Resume\ResumeV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(ResumeV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(ResumeV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->documentLanguage->value); - $this->assertEquals(0, count($prediction->givenNames)); - $this->assertEquals(0, count($prediction->surnames)); - $this->assertNull($prediction->nationality->value); - $this->assertNull($prediction->emailAddress->value); - $this->assertNull($prediction->phoneNumber->value); - $this->assertNull($prediction->address->value); - $this->assertEquals(0, count($prediction->socialNetworksUrls)); - $this->assertNull($prediction->profession->value); - $this->assertNull($prediction->jobApplied->value); - $this->assertEquals(0, count($prediction->languages)); - $this->assertEquals(0, count($prediction->hardSkills)); - $this->assertEquals(0, count($prediction->softSkills)); - $this->assertEquals(0, count($prediction->education)); - $this->assertEquals(0, count($prediction->professionalExperiences)); - $this->assertEquals(0, count($prediction->certificates)); + self::assertNull($prediction->documentLanguage->value); + self::assertCount(0, $prediction->givenNames); + self::assertCount(0, $prediction->surnames); + self::assertNull($prediction->nationality->value); + self::assertNull($prediction->emailAddress->value); + self::assertNull($prediction->phoneNumber->value); + self::assertNull($prediction->address->value); + self::assertCount(0, $prediction->socialNetworksUrls); + self::assertNull($prediction->profession->value); + self::assertNull($prediction->jobApplied->value); + self::assertCount(0, $prediction->languages); + self::assertCount(0, $prediction->hardSkills); + self::assertCount(0, $prediction->softSkills); + self::assertCount(0, $prediction->education); + self::assertCount(0, $prediction->professionalExperiences); + self::assertCount(0, $prediction->certificates); } } diff --git a/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php b/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php index 50b7162f..38e6d571 100644 --- a/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php +++ b/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php @@ -1,11 +1,15 @@ completeDoc = new Document(BankCheck\BankCheckV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankCheck\BankCheckV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(BankCheck\BankCheckV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(BankCheckV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BankCheckV1::class, $emptyDocJSON["document"]); + $this->completePage0 = new Page(BankCheckV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } - public function testCompleteDoc() + public function testCompleteDoc(): void { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); + self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); } - public function testEmptyDoc() + public function testEmptyDoc(): void { $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->date->value); - $this->assertNull($prediction->amount->value); - $this->assertEquals(0, count($prediction->payees)); - $this->assertNull($prediction->routingNumber->value); - $this->assertNull($prediction->accountNumber->value); - $this->assertNull($prediction->checkNumber->value); + self::assertNull($prediction->date->value); + self::assertNull($prediction->amount->value); + self::assertCount(0, $prediction->payees); + self::assertNull($prediction->routingNumber->value); + self::assertNull($prediction->accountNumber->value); + self::assertNull($prediction->checkNumber->value); } - public function testCompletePage0() + public function testCompletePage0(): void { - $this->assertEquals(0, $this->completePage0->id); - $this->assertEquals($this->completePage0Reference, strval($this->completePage0)); + self::assertSame(0, $this->completePage0->id); + self::assertSame($this->completePage0Reference, (string) ($this->completePage0)); } } diff --git a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php b/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php deleted file mode 100644 index 48d3fe02..00000000 --- a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php +++ /dev/null @@ -1,50 +0,0 @@ -completeDoc = new Document(HealthcareCard\HealthcareCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthcareCard\HealthcareCardV1::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->companyName->value); - $this->assertNull($prediction->planName->value); - $this->assertNull($prediction->memberName->value); - $this->assertNull($prediction->memberId->value); - $this->assertNull($prediction->issuer80840->value); - $this->assertEquals(0, count($prediction->dependents)); - $this->assertNull($prediction->groupNumber->value); - $this->assertNull($prediction->payerId->value); - $this->assertNull($prediction->rxBin->value); - $this->assertNull($prediction->rxId->value); - $this->assertNull($prediction->rxGrp->value); - $this->assertNull($prediction->rxPcn->value); - $this->assertEquals(0, count($prediction->copays)); - $this->assertNull($prediction->enrollmentDate->value); - } -} diff --git a/tests/V1/Product/Us/UsMail/UsMailV3Test.php b/tests/V1/Product/Us/UsMail/UsMailV3Test.php deleted file mode 100644 index 38172d24..00000000 --- a/tests/V1/Product/Us/UsMail/UsMailV3Test.php +++ /dev/null @@ -1,45 +0,0 @@ -completeDoc = new Document(UsMail\UsMailV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(UsMail\UsMailV3::class, $emptyDocJSON["document"]); - $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); - } - - public function testCompleteDoc() - { - $this->assertEquals($this->completeDocReference, strval($this->completeDoc)); - } - - public function testEmptyDoc() - { - $prediction = $this->emptyDoc->inference->prediction; - $this->assertNull($prediction->senderName->value); - $this->assertNull($prediction->senderAddress->city); - $this->assertNull($prediction->senderAddress->complete); - $this->assertNull($prediction->senderAddress->postalCode); - $this->assertNull($prediction->senderAddress->state); - $this->assertNull($prediction->senderAddress->street); - $this->assertEquals(0, count($prediction->recipientNames)); - $this->assertEquals(0, count($prediction->recipientAddresses)); - $this->assertNull($prediction->isReturnToSender->value); - } -} diff --git a/tests/V1/Standard/AmountFieldTest.php b/tests/V1/Standard/AmountFieldTest.php index 314c19ae..06754acd 100644 --- a/tests/V1/Standard/AmountFieldTest.php +++ b/tests/V1/Standard/AmountFieldTest.php @@ -1,13 +1,15 @@ "2", @@ -17,19 +19,19 @@ public function testConstructor() [0.414, 0.707], [0.414, 0.831], [0.016, 0.831], - ] + ], ]; $amount = new AmountField($fieldArray); - $this->assertEquals(2, $amount->value); + self::assertSame(2.0, $amount->value); } - public function testConstructorNoAmount() + public function testConstructorNoAmount(): void { $fieldArray = [ "value" => "N/A", - "confidence" => 0.1 + "confidence" => 0.1, ]; $amount = new AmountField($fieldArray); - $this->assertNull($amount->value); + self::assertNull($amount->value); } } diff --git a/tests/V1/Standard/ClassificationFieldTest.php b/tests/V1/Standard/ClassificationFieldTest.php index 9f4d1846..149fa9b0 100644 --- a/tests/V1/Standard/ClassificationFieldTest.php +++ b/tests/V1/Standard/ClassificationFieldTest.php @@ -1,30 +1,32 @@ "automobile", - "confidence" => 0.1 + "confidence" => 0.1, ]; $classification = new ClassificationField($fieldArray); - $this->assertEquals("automobile", $classification->value); - $this->assertEquals(0.1, $classification->confidence); + self::assertSame("automobile", $classification->value); + self::assertSame(0.1, $classification->confidence); } - public function testConstructorNoClassificatio() + public function testConstructorNoClassificatio(): void { $fieldArray = [ "value" => "N/A", - "confidence" => 0.1 + "confidence" => 0.1, ]; $classification = new ClassificationField($fieldArray); - $this->assertNull($classification->value); + self::assertNull($classification->value); } } diff --git a/tests/V1/Standard/CompanyRegistrationFieldTest.php b/tests/V1/Standard/CompanyRegistrationFieldTest.php index 2d0445b9..82ae2468 100644 --- a/tests/V1/Standard/CompanyRegistrationFieldTest.php +++ b/tests/V1/Standard/CompanyRegistrationFieldTest.php @@ -1,13 +1,15 @@ "VAT NUMBER", - "value" => "FR00000000000" + "value" => "FR00000000000", ]; $companyRegistration = new CompanyRegistrationField($fieldArray); - $this->assertEquals("FR00000000000", $companyRegistration->value); - $this->assertEquals("VAT NUMBER", $companyRegistration->type); + self::assertSame("FR00000000000", $companyRegistration->value); + self::assertSame("VAT NUMBER", $companyRegistration->type); } } diff --git a/tests/V1/Standard/DateFieldTest.php b/tests/V1/Standard/DateFieldTest.php index bd76e60b..09ea3840 100644 --- a/tests/V1/Standard/DateFieldTest.php +++ b/tests/V1/Standard/DateFieldTest.php @@ -1,13 +1,16 @@ "2018-04-01", @@ -18,21 +21,21 @@ public function testConstructor() [0.414, 0.831], [0.016, 0.831], ], - "is_computed" => true + "is_computed" => true, ]; $date = new DateField($fieldArray); - $this->assertEquals("2018-04-01", $date->value); - $this->assertInstanceOf(\DateTimeImmutable::class, $date->dateObject); - $this->assertTrue($date->isComputed); + self::assertSame("2018-04-01", $date->value); + self::assertInstanceOf(DateTimeImmutable::class, $date->dateObject); + self::assertTrue($date->isComputed); } - public function testConstructorNoDate() + public function testConstructorNoDate(): void { $fieldArray = [ "iso" => "N/A", - "confidence" => 0.1 + "confidence" => 0.1, ]; $date = new DateField($fieldArray); - $this->assertNull($date->value); + self::assertNull($date->value); } } diff --git a/tests/V1/Standard/LocaleFieldTest.php b/tests/V1/Standard/LocaleFieldTest.php index e162309a..6ac75a60 100644 --- a/tests/V1/Standard/LocaleFieldTest.php +++ b/tests/V1/Standard/LocaleFieldTest.php @@ -1,13 +1,15 @@ 0.82, @@ -18,13 +20,13 @@ public function testConstructor() ]; $companyRegistration = new LocaleField($fieldArray); - $this->assertEquals("en-GB", $companyRegistration->value); - $this->assertEquals("en", $companyRegistration->language); - $this->assertEquals("GB", $companyRegistration->country); - $this->assertEquals("GBP", $companyRegistration->currency); + self::assertSame("en-GB", $companyRegistration->value); + self::assertSame("en", $companyRegistration->language); + self::assertSame("GB", $companyRegistration->country); + self::assertSame("GBP", $companyRegistration->currency); } - public function testConstructorNoValues() + public function testConstructorNoValues(): void { $fieldArray = [ "confidence" => 0, @@ -34,9 +36,9 @@ public function testConstructorNoValues() "value" => null, ]; $classification = new LocaleField($fieldArray); - $this->assertNull($classification->value); - $this->assertNull($classification->language); - $this->assertNull($classification->country); - $this->assertNull($classification->currency); + self::assertNull($classification->value); + self::assertNull($classification->language); + self::assertNull($classification->country); + self::assertNull($classification->currency); } } diff --git a/tests/V1/Standard/PaymentDetailsFieldTest.php b/tests/V1/Standard/PaymentDetailsFieldTest.php index edc14dc8..4f3b29b9 100644 --- a/tests/V1/Standard/PaymentDetailsFieldTest.php +++ b/tests/V1/Standard/PaymentDetailsFieldTest.php @@ -1,13 +1,15 @@ "12345678910", @@ -18,31 +20,31 @@ public function testConstructor() "polygon" => [ [ 0.666, - 0.123 + 0.123, ], [ 0.861, - 0.123 + 0.123, ], [ 0.861, - 0.14 + 0.14, ], [ 0.666, - 0.14 - ] + 0.14, + ], ], ]; $companyRegistration = new PaymentDetailsField($fieldArray); - $this->assertEquals("FR7640254025476501124705368", $companyRegistration->iban); - $this->assertEquals("211212121212", $companyRegistration->routingNumber); - $this->assertEquals("CEPAFRPP", $companyRegistration->swift); - $this->assertEquals("12345678910", $companyRegistration->accountNumber); + self::assertSame("FR7640254025476501124705368", $companyRegistration->iban); + self::assertSame("211212121212", $companyRegistration->routingNumber); + self::assertSame("CEPAFRPP", $companyRegistration->swift); + self::assertSame("12345678910", $companyRegistration->accountNumber); } - public function testConstructorNoValues() + public function testConstructorNoValues(): void { $fieldArray = [ "confidence" => 0, @@ -52,9 +54,9 @@ public function testConstructorNoValues() "account_number" => null, ]; $companyRegistration = new PaymentDetailsField($fieldArray); - $this->assertNull($companyRegistration->iban); - $this->assertNull($companyRegistration->routingNumber); - $this->assertNull($companyRegistration->swift); - $this->assertNull($companyRegistration->accountNumber); + self::assertNull($companyRegistration->iban); + self::assertNull($companyRegistration->routingNumber); + self::assertNull($companyRegistration->swift); + self::assertNull($companyRegistration->accountNumber); } } diff --git a/tests/V1/Standard/PositionFieldTest.php b/tests/V1/Standard/PositionFieldTest.php index 009e60e6..85636246 100644 --- a/tests/V1/Standard/PositionFieldTest.php +++ b/tests/V1/Standard/PositionFieldTest.php @@ -1,48 +1,50 @@ [ [0.016, 0.707], [0.414, 0.707], [0.414, 0.831], - [0.016, 0.831] + [0.016, 0.831], ], "confidence" => 0.1, "quadrangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], "polygon" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], - "rectangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]] + "rectangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], ]; $field = new PositionField($fieldArray); - $this->assertEquals(4, count($field->value->getCoordinates())); - $this->assertEquals(0.1, $field->confidence); - $this->assertEquals(0.016, $field->polygon->getCoordinates()[0]->getX()); + self::assertCount(4, $field->value->getCoordinates()); + self::assertSame(0.1, $field->confidence); + self::assertSame(0.016, $field->polygon->getCoordinates()[0]->getX()); } - public function testConstructorFail() + public function testConstructorFail(): void { $fieldArray = [ "bounding_box" => [ [0.016, 0.707], [0.414, 0.707], [0.414, 0.831], - [0.016, 0.831] + [0.016, 0.831], ], "confidence" => 0.1, "quadrangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], - "rectangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]] + "rectangle" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], ]; $field = new PositionField($fieldArray); - $this->assertNull($field->value); + self::assertNull($field->value); } } diff --git a/tests/V1/Standard/StringFieldTest.php b/tests/V1/Standard/StringFieldTest.php index c3fe246c..7c1411c2 100644 --- a/tests/V1/Standard/StringFieldTest.php +++ b/tests/V1/Standard/StringFieldTest.php @@ -1,31 +1,35 @@ [ [0.016, 0.707], [0.414, 0.707], [0.414, 0.831], - [0.016, 0.831] + [0.016, 0.831], ], "confidence" => 0.1, "value" => "some-value", ]; $field = new StringField($fieldArray); - $this->assertEquals("some-value", $field->value); - $this->assertGreaterThan(0, count($field->boundingBox->getCoordinates())); + self::assertSame("some-value", $field->value); + self::assertGreaterThan(0, count($field->boundingBox->getCoordinates())); } - public function testConstructorFail() + public function testConstructorFail(): void { $fieldArray = [ "polygon" => null, @@ -34,10 +38,10 @@ public function testConstructorFail() ]; $field = new StringField($fieldArray); - $this->assertNull($field->value); + self::assertNull($field->value); } - public function testConstructorNoRawValue() + public function testConstructorNoRawValue(): void { $fieldArray = [ "value" => "hello world", @@ -52,11 +56,11 @@ public function testConstructorNoRawValue() $field = new StringField($fieldArray); - $this->assertEquals("hello world", $field->value); - $this->assertNull($field->rawValue); + self::assertSame("hello world", $field->value); + self::assertNull($field->rawValue); } - public function testConstructorRawValue() + public function testConstructorRawValue(): void { $fieldArray = [ "value" => "hello world", @@ -72,7 +76,7 @@ public function testConstructorRawValue() $field = new StringField($fieldArray); - $this->assertEquals("hello world", $field->value); - $this->assertEquals("HelLO wOrld", $field->rawValue); + self::assertSame("hello world", $field->value); + self::assertSame("HelLO wOrld", $field->rawValue); } } diff --git a/tests/V1/Standard/TaxesTest.php b/tests/V1/Standard/TaxesTest.php index 7afed0aa..f95d9da5 100644 --- a/tests/V1/Standard/TaxesTest.php +++ b/tests/V1/Standard/TaxesTest.php @@ -1,13 +1,17 @@ 2, @@ -17,28 +21,28 @@ public function testConstructor() "polygon" => [[0.016, 0.707], [0.414, 0.707], [0.414, 0.831], [0.016, 0.831]], ]; $tax = new TaxField($fieldArray); - $this->assertEquals(2, $tax->value); - $this->assertEquals(0.1, $tax->confidence); - $this->assertEquals(0.2, $tax->rate); - $this->assertGreaterThan(0, count($tax->boundingBox->getCoordinates())); - $this->assertEquals("Base: , Code: QST, Rate (%): 0.20, Amount: 2.00", strval($tax)); + self::assertSame(2.0, $tax->value); + self::assertSame(0.1, $tax->confidence); + self::assertSame(0.2, $tax->rate); + self::assertGreaterThan(0, count($tax->boundingBox->getCoordinates())); + self::assertSame("Base: , Code: QST, Rate (%): 0.20, Amount: 2.00", (string) $tax); } public function testConstructorNoRate(): void { $fieldDict = ["value" => 2.0, "confidence" => 0.1]; $tax = new TaxField($fieldDict); - $this->assertNull($tax->rate); - $this->assertNull($tax->boundingBox); - $this->assertEquals("Base: , Code: , Rate (%): , Amount: 2.00", (string)$tax); + self::assertNull($tax->rate); + self::assertNull($tax->boundingBox); + self::assertSame("Base: , Code: , Rate (%): , Amount: 2.00", (string) $tax); } public function testConstructorNoAmount(): void { $fieldDict = ["value" => "NA", "rate" => "AA", "code" => "N/A", "confidence" => 0.1]; $tax = new TaxField($fieldDict); - $this->assertNull($tax->value); - $this->assertEquals("Base: , Code: , Rate (%): , Amount:", (string)$tax); + self::assertNull($tax->value); + self::assertSame("Base: , Code: , Rate (%): , Amount:", (string) $tax); } public function testConstructorOnlyCode(): void @@ -50,7 +54,7 @@ public function testConstructorOnlyCode(): void "confidence" => 0.1, ]; $tax = new TaxField($fieldDict); - $this->assertNull($tax->value); - $this->assertEquals("Base: , Code: TAXES AND FEES, Rate (%): , Amount:", (string)$tax); + self::assertNull($tax->value); + self::assertSame("Base: , Code: TAXES AND FEES, Rate (%): , Amount:", (string) $tax); } } diff --git a/tests/V1/Workflow/WorkflowTest.php b/tests/V1/Workflow/WorkflowTest.php index ab9dd5bd..6113be2d 100644 --- a/tests/V1/Workflow/WorkflowTest.php +++ b/tests/V1/Workflow/WorkflowTest.php @@ -1,9 +1,11 @@ workflowDir . "success.json"); $constructedWorkflow = new WorkflowResponse(GeneratedV1::class, json_decode($json, true)); - $this->assertNotNull($constructedWorkflow); - $this->assertNotNull($constructedWorkflow->apiRequest); - $this->assertNull($constructedWorkflow->execution->batchName); - $this->assertNull($constructedWorkflow->execution->createdAt); - $this->assertNull($constructedWorkflow->execution->file->alias); - $this->assertEquals("default_sample.jpg", $constructedWorkflow->execution->file->name); - $this->assertEquals( + self::assertNotNull($constructedWorkflow); + self::assertNotNull($constructedWorkflow->apiRequest); + self::assertNull($constructedWorkflow->execution->batchName); + self::assertNull($constructedWorkflow->execution->createdAt); + self::assertNull($constructedWorkflow->execution->file->alias); + self::assertSame("default_sample.jpg", $constructedWorkflow->execution->file->name); + self::assertSame( "8c75c035-e083-4e77-ba3b-7c3598bd1d8a", $constructedWorkflow->execution->id ); - $this->assertNull($constructedWorkflow->execution->inference); - $this->assertEquals("medium", $constructedWorkflow->execution->priority); - $this->assertNull($constructedWorkflow->execution->reviewedAt); - $this->assertNull($constructedWorkflow->execution->reviewedPrediction); - $this->assertEquals("processing", $constructedWorkflow->execution->status); - $this->assertEquals("manual", $constructedWorkflow->execution->type); - $this->assertEquals( + self::assertNull($constructedWorkflow->execution->inference); + self::assertSame("medium", $constructedWorkflow->execution->priority); + self::assertNull($constructedWorkflow->execution->reviewedAt); + self::assertNull($constructedWorkflow->execution->reviewedPrediction); + self::assertSame("processing", $constructedWorkflow->execution->status); + self::assertSame("manual", $constructedWorkflow->execution->type); + self::assertSame( "2024-11-13T13:02:31.699190", $constructedWorkflow->execution->uploadedAt->format('Y-m-d\TH:i:s.u') ); - $this->assertEquals( + self::assertSame( "07ebf237-ff27-4eee-b6a2-425df4a5cca6", $constructedWorkflow->execution->workflowId ); } - public function testDeserializeWorkflowWithPriorityAndAlias() + public function testDeserializeWorkflowWithPriorityAndAlias(): void { $json = file_get_contents($this->workflowDir . "success_low_priority.json"); $constructedWorkflow = new WorkflowResponse(GeneratedV1::class, json_decode($json, true)); - $this->assertNotNull($constructedWorkflow); - $this->assertNotNull($constructedWorkflow->apiRequest); - $this->assertNull($constructedWorkflow->execution->batchName); - $this->assertNull($constructedWorkflow->execution->createdAt); - $this->assertEquals( + self::assertNotNull($constructedWorkflow); + self::assertNotNull($constructedWorkflow->apiRequest); + self::assertNull($constructedWorkflow->execution->batchName); + self::assertNull($constructedWorkflow->execution->createdAt); + self::assertSame( "low-priority-sample-test", $constructedWorkflow->execution->file->alias ); - $this->assertEquals("default_sample.jpg", $constructedWorkflow->execution->file->name); - $this->assertEquals( + self::assertSame("default_sample.jpg", $constructedWorkflow->execution->file->name); + self::assertSame( "b743e123-e18c-4b62-8a07-811a4f72afd3", $constructedWorkflow->execution->id ); - $this->assertNull($constructedWorkflow->execution->inference); - $this->assertEquals("low", $constructedWorkflow->execution->priority); - $this->assertNull($constructedWorkflow->execution->reviewedAt); - $this->assertNull($constructedWorkflow->execution->reviewedPrediction); - $this->assertEquals("processing", $constructedWorkflow->execution->status); - $this->assertEquals("manual", $constructedWorkflow->execution->type); - $this->assertEquals( + self::assertNull($constructedWorkflow->execution->inference); + self::assertSame("low", $constructedWorkflow->execution->priority); + self::assertNull($constructedWorkflow->execution->reviewedAt); + self::assertNull($constructedWorkflow->execution->reviewedPrediction); + self::assertSame("processing", $constructedWorkflow->execution->status); + self::assertSame("manual", $constructedWorkflow->execution->type); + self::assertSame( "2024-11-13T13:17:01.315179", $constructedWorkflow->execution->uploadedAt->format('Y-m-d\TH:i:s.u') ); - $this->assertEquals( + self::assertSame( "07ebf237-ff27-4eee-b6a2-425df4a5cca6", $constructedWorkflow->execution->workflowId ); diff --git a/tests/V1/Workflow/WorkflowTestFunctional.php b/tests/V1/Workflow/WorkflowTestFunctional.php index 1144e612..089b360f 100644 --- a/tests/V1/Workflow/WorkflowTestFunctional.php +++ b/tests/V1/Workflow/WorkflowTestFunctional.php @@ -1,12 +1,16 @@ mindeeClient = new Client(); $this->workflowId = getenv('WORKFLOW_ID') ?: ''; $this->predictionType = FinancialDocumentV1::class; - $this->inputSource = $this->mindeeClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . "/products/financial_document/default_sample.jpg" + $this->inputSource = new PathInput( + TestingUtilities::getV1DataDir() . "/products/financial_document/default_sample.jpg" ); } - public function testWorkflow() { + public function testWorkflow(): void + { $currentDateTime = date('Y-m-d-H:i:s'); $options = new WorkflowOptions( "php-" . $currentDateTime, @@ -37,14 +42,17 @@ public function testWorkflow() { true ); $response = $this->mindeeClient->executeWorkflow( - $this->inputSource, $this->workflowId, $options + $this->inputSource, + $this->workflowId, + $options ); - $this->assertEquals(202, $response->apiRequest->statusCode); - $this->assertEquals("php-$currentDateTime", $response->execution->file->alias); - $this->assertEquals("low", $response->execution->priority); + self::assertSame(202, $response->apiRequest->statusCode); + self::assertSame("php-$currentDateTime", $response->execution->file->alias); + self::assertSame("low", $response->execution->priority); } - public function testWorkflowPollingWithRAG() { + public function testWorkflowPollingWithRAG(): void + { $options = new PredictMethodOptions(); $options->setRAG(true)->setWorkflowId($this->workflowId); $response = $this->mindeeClient->enqueueAndParse( @@ -52,12 +60,13 @@ public function testWorkflowPollingWithRAG() { $this->inputSource, $options ); - $this->assertNotEmpty(strval($response->document)); - $this->assertNotEmpty($response->document->inference->extras); - $this->assertNotEmpty($response->document->inference->extras->rag->matchingDocumentId); + self::assertNotEmpty((string) ($response->document)); + self::assertNotEmpty($response->document->inference->extras); + self::assertNotEmpty($response->document->inference->extras->rag->matchingDocumentId); } - public function testWorkflowPollingWithoutRAG() { + public function testWorkflowPollingWithoutRAG(): void + { $options = new PredictMethodOptions(); $options->setWorkflowId($this->workflowId); $response = $this->mindeeClient->enqueueAndParse( @@ -65,8 +74,8 @@ public function testWorkflowPollingWithoutRAG() { $this->inputSource, $options ); - $this->assertNotEmpty(strval($response->document)); - $this->assertObjectHasProperty('rag', $response->document->inference->extras); - $this->assertFalse(isset($response->document->inference->extras->rag)); + self::assertNotEmpty((string) ($response->document)); + self::assertObjectHasProperty('rag', $response->document->inference->extras); + self::assertFalse(isset($response->document->inference->extras->rag)); } } diff --git a/tests/V2/ClientOptions/BaseParametersTest.php b/tests/V2/ClientOptions/BaseParametersTest.php index f727299e..6603b97b 100644 --- a/tests/V2/ClientOptions/BaseParametersTest.php +++ b/tests/V2/ClientOptions/BaseParametersTest.php @@ -1,5 +1,7 @@ asHash(); - $this->assertArrayHasKey('model_id', $hash); - $this->assertArrayHasKey('webhook_ids', $hash); - $this->assertSame('model-id', $hash['model_id']); - $this->assertSame('first-id,second-id', $hash['webhook_ids']); + self::assertArrayHasKey('model_id', $hash); + self::assertArrayHasKey('webhook_ids', $hash); + self::assertSame('model-id', $hash['model_id']); + self::assertSame('first-id,second-id', $hash['webhook_ids']); } } diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 3de066ed..8d4edbad 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -1,27 +1,30 @@ getProperty('mindeeApi'); - $property->setAccessible(true); $property->setValue($client, $mockedApi); return $client; } @@ -29,24 +32,24 @@ private static function makeClientWithMockedApi(MindeeApiV2 $mockedApi): ClientV public function testEnqueuePostAsync(): void { $predictable = $this->createMock(MindeeApiV2::class); - $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); - $predictable->expects($this->once()) + $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); + $predictable->expects(self::once()) ->method('reqPostEnqueue') ->with( - $this->isInstanceOf(LocalInputSource::class), - $this->isInstanceOf(InferenceParameters::class) + self::isInstanceOf(LocalInputSource::class), + self::isInstanceOf(ExtractionParameters::class) ) ->willReturn(new JobResponse(json_decode($syntheticResponse, true))); $mindeeClient = self::makeClientWithMockedApi($predictable); - $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $params = new InferenceParameters('dummy-model-id', textContext: 'dummy text context'); + $input = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); + $params = new ExtractionParameters('dummy-model-id', textContext: 'dummy text context'); - $response = $mindeeClient->enqueueInference($input, $params); + $response = $mindeeClient->enqueue($input, $params); - $this->assertNotNull($response, 'enqueue() must return a response'); - $this->assertInstanceOf(JobResponse::class, $response); + self::assertNotNull($response, 'enqueue() must return a response'); + self::assertEmpty($response->job->error); } public function testDocumentGetJobAsync(): void @@ -54,20 +57,20 @@ public function testDocumentGetJobAsync(): void /** @var MindeeApiV2&MockObject $predictable */ $predictable = $this->createMock(MindeeApiV2::class); - $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); + $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $processing = new JobResponse(json_decode($syntheticResponse, true)); - $predictable->expects($this->once()) + $predictable->expects(self::once()) ->method('reqGetJob') - ->with($this->equalTo('dummy-id')) + ->with(self::equalTo('dummy-id')) ->willReturn($processing); $mindeeClient = self::makeClientWithMockedApi($predictable); $response = $mindeeClient->getJob('dummy-id'); - $this->assertNotNull($response, 'must return a response'); - $this->assertNotNull($response->job, 'job must return a response'); + self::assertNotNull($response, 'must return a response'); + self::assertNotNull($response->job, 'job must return a response'); } public function testDocumentGetInferenceAsync(): void @@ -75,33 +78,36 @@ public function testDocumentGetInferenceAsync(): void /** @var MindeeApiV2&MockObject $predictable */ $predictable = $this->createMock(MindeeApiV2::class); - $jsonFile = \TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; - $this->assertFileExists($jsonFile, 'Test resource file must exist'); + $jsonFile = TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; + self::assertFileExists($jsonFile, 'Test resource file must exist'); $json = json_decode(file_get_contents($jsonFile), true); - $processing = new InferenceResponse($json); + $processing = new ExtractionResponse($json); - $predictable->expects($this->once()) - ->method('reqGetInference') - ->with($this->equalTo('12345678-1234-1234-1234-123456789abc')) + $predictable->expects(self::once()) + ->method('reqGetResult') + ->with( + self::equalTo(ExtractionResponse::class), + self::equalTo('12345678-1234-1234-1234-123456789abc') + ) ->willReturn($processing); $mindeeClient = self::makeClientWithMockedApi($predictable); - $response = $mindeeClient->getInference('12345678-1234-1234-1234-123456789abc'); + $response = $mindeeClient->getResult(ExtractionResponse::class, '12345678-1234-1234-1234-123456789abc'); - $this->assertNotNull($response, 'must have a response'); - $this->assertNotNull($response->inference, 'inference must have a response'); + self::assertNotNull($response, 'must have a response'); + self::assertNotNull($response->inference, 'inference must have a response'); $fields = $response->inference->result->fields ?? []; - $this->assertCount( + self::assertCount( 21, $fields, 'Result must have 21 fields' ); $supplierName = $fields['supplier_name']->value ?? null; - $this->assertEquals( + self::assertSame( 'John Smith', $supplierName, 'Result "' . $supplierName . '" must deserialize fields properly.' @@ -110,29 +116,30 @@ public function testDocumentGetInferenceAsync(): void public function testInferenceLoadsLocally(): void { - $jsonFile = \TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; - $this->assertFileExists($jsonFile, 'Test resource file must exist'); + $jsonFile = TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; + self::assertFileExists($jsonFile, 'Test resource file must exist'); $localResponse = new LocalResponse($jsonFile); - $loaded = $localResponse->deserializeResponse(InferenceResponse::class); + $loaded = $localResponse->deserializeResponse(ExtractionResponse::class); - $this->assertNotNull($loaded, 'Loaded InferenceResponse must not be null'); - $this->assertInstanceOf(InferenceResponse::class, $loaded); + self::assertNotNull($loaded, 'Loaded ExtractionResponse must not be null'); + self::assertInstanceOf(ExtractionResponse::class, $loaded); $modelId = $loaded->inference->model->id ?? null; - $this->assertEquals( + self::assertSame( '12345678-1234-1234-1234-123456789abc', $modelId, 'Model Id mismatch' ); - $supplierName = $loaded->inference->result->fields['supplier_name']->value ?? null; - $this->assertEquals( + $supplierName = $loaded->inference->result->fields['supplier_name']->getStringValue(); + self::assertSame( 'John Smith', $supplierName, 'Supplier name mismatch' ); } + public function testInvalidBaseUrlRaisesMindeeException(): void { $this->expectException(MindeeException::class); @@ -141,16 +148,33 @@ public function testInvalidBaseUrlRaisesMindeeException(): void putenv('MINDEE_V2_BASE_URL=https://invalid-v2.mindee.net'); try { - $client = new ClientV2('dummy-key'); - $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $params = new InferenceParameters('dummy-model-id'); - $client->enqueueAndGetInference($input, $params); + $client = new Client('dummy-key'); + $input = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); + $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); } } } + + public function testInvalidApiKeyRaisesMindeeException(): void + { + $original = getenv('MINDEE_V2_API_KEY') ?: null; + putenv('MINDEE_V2_API_KEY='); + $this->expectException(MindeeException::class); + $this->expectExceptionMessage('Missing API key for call, check your Client configuration.You can set this using the MINDEE_V2_API_KEY environment variable.'); + try { + $client = new Client(); + } finally { + if (null === $original) { + putenv('MINDEE_V2_API_KEY'); + } else { + putenv('MINDEE_V2_API_KEY=' . $original); + } + } + } } diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index e2e70991..ea23eb7d 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -1,18 +1,21 @@ modelId = getenv('MINDEE_V2_FINDOC_MODEL_ID'); - $this->mindeeClient = new ClientV2($apiKey); + $this->mindeeClient = new Client($apiKey); } public function testParseFileEmptyMultiPageMustSucceed(): void { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters($this->modelId, rag: false, rawText: true); + $inferenceParams = new ExtractionParameters($this->modelId, rag: false, rawText: true); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); - $this->assertNotNull($response); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); + self::assertNotNull($response); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); $file = $inference->file; - $this->assertNotNull($file); - $this->assertEquals('multipage_cut-2.pdf', $file->name); - $this->assertEquals(2, $file->pageCount); + self::assertNotNull($file); + self::assertSame('multipage_cut-2.pdf', $file->name); + self::assertSame(2, $file->pageCount); - $this->assertNotNull($inference->model); - $this->assertEquals($this->modelId, $inference->model->id); + self::assertNotNull($inference->model); + self::assertSame($this->modelId, $inference->model->id); $activeOptions = $inference->activeOptions; - $this->assertTrue($activeOptions->rawText, "Raw text must be enabled"); - $this->assertFalse($activeOptions->polygon, "Polygon must be disabled by default"); - $this->assertFalse($activeOptions->confidence, "Confidence must be disabled by default"); - $this->assertFalse($activeOptions->rag, "RAG must be disabled by default"); + self::assertTrue($activeOptions->rawText, "Raw text must be enabled"); + self::assertFalse($activeOptions->polygon, "Polygon must be disabled by default"); + self::assertFalse($activeOptions->confidence, "Confidence must be disabled by default"); + self::assertFalse($activeOptions->rag, "RAG must be disabled by default"); $result = $inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); $rawText = $result->rawText; - $this->assertNotNull($rawText); - $this->assertCount(2, $rawText->pages); + self::assertNotNull($rawText); + self::assertCount(2, $rawText->pages); } /** @@ -64,29 +67,29 @@ public function testParseFileFilledSinglePageMustSucceed(): void TestingUtilities::getV1DataDir() . '/products/financial_document/default_sample.jpg' ); - $inferenceParams = new InferenceParameters($this->modelId, rag: false, textContext: 'this is an invoice'); + $inferenceParams = new ExtractionParameters($this->modelId, rag: false, textContext: 'this is an invoice'); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); - $this->assertNotNull($response); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); + self::assertNotNull($response); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); $file = $inference->file; - $this->assertNotNull($file); - $this->assertEquals('default_sample.jpg', $file->name); - $this->assertEquals(1, $file->pageCount); + self::assertNotNull($file); + self::assertSame('default_sample.jpg', $file->name); + self::assertSame(1, $file->pageCount); - $this->assertNotNull($inference->model); - $this->assertEquals($this->modelId, $inference->model->id); + self::assertNotNull($inference->model); + self::assertSame($this->modelId, $inference->model->id); $result = $inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); - $this->assertNotNull($result->fields); - $this->assertNotNull($result->fields['supplier_name'] ?? null); + self::assertNotNull($result->fields); + self::assertNotNull($result->fields['supplier_name'] ?? null); $supplierName = $result->fields['supplier_name']->value ?? null; - $this->assertEquals( + self::assertSame( 'John Smith', $supplierName ); @@ -97,14 +100,14 @@ public function testInvalidUUIDMustThrowError(): void $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $inferenceParams = new InferenceParameters('INVALID MODEL ID'); + $inferenceParams = new ExtractionParameters('INVALID MODEL ID'); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { - $this->assertStringStartsWith('422-', $e->errorCode); - $this->assertNotEmpty($e->title); - $this->assertIsArray($e->errors); + self::assertStringStartsWith('422-', $e->errorCode); + self::assertNotEmpty($e->title); + self::assertIsArray($e->errors); } } @@ -112,14 +115,14 @@ public function testUnknownModelMustThrowError(): void { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters('fc405e37-4ba4-4d03-aeba-533a8d1f0f21', textContext: 'this is invalid'); + $inferenceParams = new ExtractionParameters('fc405e37-4ba4-4d03-aeba-533a8d1f0f21', textContext: 'this is invalid'); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { - $this->assertStringStartsWith('404-', $e->errorCode); - $this->assertNotEmpty($e->title); - $this->assertIsArray($e->errors); + self::assertStringStartsWith('404-', $e->errorCode); + self::assertNotEmpty($e->title); + self::assertIsArray($e->errors); } } @@ -127,19 +130,19 @@ public function testUnknownModelMustThrowError(): void public function testInvalidJobMustThrowError(): void { try { - $this->mindeeClient->getInference('fc405e37-4ba4-4d03-aeba-533a8d1f0f21'); + $this->mindeeClient->getResult(ExtractionResponse::class, 'fc405e37-4ba4-4d03-aeba-533a8d1f0f21'); } catch (MindeeV2HttpException $e) { - $this->assertStringStartsWith('404-', $e->errorCode); - $this->assertNotEmpty($e->title); - $this->assertIsArray($e->errors); + self::assertStringStartsWith('404-', $e->errorCode); + self::assertNotEmpty($e->title); + self::assertIsArray($e->errors); } } - public function testInvalidWebhookIDsMustThrowError() + public function testInvalidWebhookIDsMustThrowError(): void { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters( + $inferenceParams = new ExtractionParameters( $this->modelId, null, null, @@ -151,30 +154,30 @@ public function testInvalidWebhookIDsMustThrowError() ); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { - $this->assertStringStartsWith('422-', $e->errorCode); - $this->assertNotEmpty($e->title); - $this->assertIsArray($e->errors); + self::assertStringStartsWith('422-', $e->errorCode); + self::assertNotEmpty($e->title); + self::assertIsArray($e->errors); } } public function testUrlInputSourceMustNotRaiseErrors(): void { - $urlSource = new URLInputSource(getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')); + $urlSource = new UrlInputSource(getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')); - $inferenceParams = new InferenceParameters($this->modelId); + $inferenceParams = new ExtractionParameters($this->modelId); - $response = $this->mindeeClient->enqueueAndGetInference($urlSource, $inferenceParams); - $this->assertNotNull($response); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $urlSource, $inferenceParams); + self::assertNotNull($response); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); $file = $inference->file; - $this->assertNotNull($file); + self::assertNotNull($file); $result = $inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); } public function testDataSchemaMustSucceed(): void @@ -187,30 +190,30 @@ public function testDataSchemaMustSucceed(): void TestingUtilities::getV2DataDir() . '/products/extraction/data_schema_replace_param.json' ); - $inferenceParams = new InferenceParameters($this->modelId, dataSchema: $dataSchemaReplace); + $inferenceParams = new ExtractionParameters($this->modelId, dataSchema: $dataSchemaReplace); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); - $this->assertNotNull($response); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); + self::assertNotNull($response); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); $file = $inference->file; - $this->assertNotNull($file); - $this->assertEquals('blank_1.pdf', $file->name); - $this->assertEquals(1, $file->pageCount); + self::assertNotNull($file); + self::assertSame('blank_1.pdf', $file->name); + self::assertSame(1, $file->pageCount); - $this->assertNotNull($inference->model); - $this->assertEquals($this->modelId, $inference->model->id); - $this->assertNotNull($inference->activeOptions); - $this->assertTrue($inference->activeOptions->dataSchema->replace); + self::assertNotNull($inference->model); + self::assertSame($this->modelId, $inference->model->id); + self::assertNotNull($inference->activeOptions); + self::assertTrue($inference->activeOptions->dataSchema->replace); $result = $inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); - $this->assertNotNull($result->fields); - $this->assertNotNull($result->fields['test_replace'] ?? null); + self::assertNotNull($result->fields); + self::assertNotNull($result->fields['test_replace'] ?? null); - $this->assertEquals( + self::assertSame( 'a test value', $result->fields['test_replace']->value ); @@ -222,11 +225,13 @@ public function testMultipleWebhooksMustSucceed(): void TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf' ); - $inferenceParams = new InferenceParameters($this->modelId, webhooksIds: [ - getenv('MINDEE_V2_FAILURE_WEBHOOK_ID'), - getenv('MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID')] + $inferenceParams = new ExtractionParameters( + $this->modelId, + webhookIds: [ + getenv('MINDEE_V2_FAILURE_WEBHOOK_ID'), + getenv('MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID')] ); $response = $this->mindeeClient->enqueue($source, $inferenceParams); - $this->assertEquals(2, count($response->job->webhooks)); + self::assertCount(2, $response->job->webhooks); } } diff --git a/tests/V2/FileOperations/CropFunctional.php b/tests/V2/FileOperations/CropFunctional.php index c7de38b2..a57b26bd 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -1,19 +1,24 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->cropModelId = getenv('MINDEE_V2_CROP_MODEL_ID') ?: ''; $this->findocModelId = getenv('MINDEE_V2_FINDOC_MODEL_ID') ?: ''; $this->outputDir = getcwd() . '/output'; if (!is_dir($this->outputDir)) { - mkdir($this->outputDir, 0777, true); + mkdir($this->outputDir, 0o777, true); } } @@ -44,61 +49,62 @@ protected function tearDown(): void } } - private function checkFindocReturn(InferenceResponse $findocResponse): void + private function checkFindocReturn(ExtractionResponse $findocResponse): void { - $this->assertGreaterThan(0, strlen($findocResponse->inference->model->id)); + self::assertGreaterThan(0, strlen($findocResponse->inference->model->id)); $totalAmount = $findocResponse->inference->result->fields['total_amount']; - $this->assertNotNull($totalAmount); - $this->assertGreaterThan(0, $totalAmount->value); + self::assertNotNull($totalAmount); + self::assertGreaterThan(0, $totalAmount->value); } public function testExtractCropsFromImageCorrectly(): void { - $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/crop/default_sample.jpg'); + $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/crop/default_sample.jpg'); $cropParams = new CropParameters($this->cropModelId); $response = $this->client->enqueueAndGetResult(CropResponse::class, $inputSource, $cropParams); - $this->assertNotNull($response); - $this->assertCount(2, $response->inference->result->crops); - - $cropOperation = new Crop($inputSource); - $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); + self::assertNotNull($response); + self::assertCount(2, $response->inference->result->crops); + self::assertInstanceOf(CropResponse::class, $response); + $extractedImages = $response->inference->result->extractFromInputSource($inputSource); + $extractedImage0 = $response->inference->result->crops[0]->extractFromInputSource($inputSource); + self::assertEquals($extractedImage0, $extractedImages[0]); - $this->assertCount(2, $extractedImages); - $this->assertEquals('default_sample.jpg_page0-0.jpg', $extractedImages[0]->filename); - $this->assertEquals('default_sample.jpg_page0-1.jpg', $extractedImages[1]->filename); + self::assertCount(2, $extractedImages); + self::assertSame('default_sample.jpg_page0-0.jpg', $extractedImages[0]->filename); + self::assertSame('default_sample.jpg_page0-1.jpg', $extractedImages[1]->filename); $extractionInput = $extractedImages[0]->asInputSource(); - $findocParams = new InferenceParameters($this->findocModelId); + $findocParams = new ExtractionParameters($this->findocModelId); - $invoice0 = $this->client->enqueueAndGetResult(InferenceResponse::class, $extractionInput, $findocParams); + $invoice0 = $this->client->enqueueAndGetResult(ExtractionResponse::class, $extractionInput, $findocParams); $this->checkFindocReturn($invoice0); $extractedImages->saveAllToDisk($this->outputDir, quality: 50); $file1Info = filesize($this->outputDir . '/crop_001.jpg'); - $this->assertGreaterThanOrEqual(97000, $file1Info); - $this->assertLessThanOrEqual(100000, $file1Info); + self::assertGreaterThanOrEqual(97000, $file1Info); + self::assertLessThanOrEqual(103000, $file1Info); $file2Info = filesize($this->outputDir . '/crop_002.jpg'); - $this->assertGreaterThanOrEqual(97000, $file2Info); - $this->assertLessThanOrEqual(100000, $file2Info); + self::assertGreaterThanOrEqual(97000, $file2Info); + self::assertLessThanOrEqual(103000, $file2Info); } public function testExtractCropsFromEachPdfPageCorrectly(): void { - $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); + $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); $cropParams = new CropParameters($this->cropModelId); $response = $this->client->enqueueAndGetResult(CropResponse::class, $inputSource, $cropParams); $cropOperation = new Crop($inputSource); - $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); + $extractedImages = $cropOperation->extractMultipleCrops($response->inference->result->crops); - $this->assertCount(5, $extractedImages); - $this->assertEquals('multipage_sample.pdf_page0-0.jpg', $extractedImages[0]->filename); - $this->assertEquals('multipage_sample.pdf_page1-0.jpg', $extractedImages[3]->filename); + self::assertCount(5, $extractedImages); + self::assertSame('multipage_sample.pdf_page0-0.jpg', $extractedImages[0]->filename); + self::assertSame('multipage_sample.pdf_page1-0.jpg', $extractedImages[3]->filename); } } diff --git a/tests/V2/FileOperations/CropTest.php b/tests/V2/FileOperations/CropTest.php index 51ddb48c..8b934721 100644 --- a/tests/V2/FileOperations/CropTest.php +++ b/tests/V2/FileOperations/CropTest.php @@ -1,5 +1,6 @@ cropDataDir = \TestingUtilities::getV2DataDir() . '/products/crop'; + $this->cropDataDir = TestingUtilities::getV2DataDir() . '/products/crop'; } public function testProcessesSinglePageCropSplitCorrectly(): void @@ -26,17 +28,17 @@ public function testProcessesSinglePageCropSplitCorrectly(): void $doc = $localResponse->deserializeResponse(CropResponse::class); $cropOperation = new Crop($inputSample); - $extractedCrops = $cropOperation->extractCrops($doc->inference->result->crops); + $extractedCrops = $cropOperation->extractMultipleCrops($doc->inference->result->crops); - $this->assertCount(1, $extractedCrops); + self::assertCount(1, $extractedCrops); - $this->assertEquals(0, $extractedCrops[0]->pageId); - $this->assertEquals(0, $extractedCrops[0]->elementId); + self::assertSame(0, $extractedCrops[0]->pageId); + self::assertSame(0, $extractedCrops[0]->elementId); $bitmap0 = $extractedCrops[0]->image; - $this->assertEquals(2822, $bitmap0->width ?? clone $bitmap0->getWidth()); - $this->assertEquals(1572, $bitmap0->height ?? clone $bitmap0->getHeight()); + self::assertSame(2822, $bitmap0->width ?? clone $bitmap0->getWidth()); + self::assertSame(1572, $bitmap0->height ?? clone $bitmap0->getHeight()); } public function testProcessesMultiPageReceiptSplitCorrectly(): void @@ -47,22 +49,22 @@ public function testProcessesMultiPageReceiptSplitCorrectly(): void $doc = $localResponse->deserializeResponse(CropResponse::class); $cropOperation = new Crop($inputSample); - $extractedCrops = $cropOperation->extractCrops($doc->inference->result->crops); + $extractedCrops = $cropOperation->extractMultipleCrops($doc->inference->result->crops); - $this->assertCount(2, $extractedCrops); + self::assertCount(2, $extractedCrops); - $this->assertEquals(0, $extractedCrops[0]->pageId); - $this->assertEquals(0, $extractedCrops[0]->elementId); + self::assertSame(0, $extractedCrops[0]->pageId); + self::assertSame(0, $extractedCrops[0]->elementId); $bitmap0 = $extractedCrops[0]->image; - $this->assertEquals(156, $bitmap0->width ?? $bitmap0->getWidth()); - $this->assertEquals(757, $bitmap0->height ?? $bitmap0->getHeight()); + self::assertSame(156, $bitmap0->width ?? $bitmap0->getWidth()); + self::assertSame(757, $bitmap0->height ?? $bitmap0->getHeight()); - $this->assertEquals(0, $extractedCrops[1]->pageId); - $this->assertEquals(1, $extractedCrops[1]->elementId); + self::assertSame(0, $extractedCrops[1]->pageId); + self::assertSame(1, $extractedCrops[1]->elementId); $bitmap1 = $extractedCrops[1]->image; - $this->assertEquals(188, $bitmap1->width ?? $bitmap1->getWidth()); - $this->assertEquals(691, $bitmap1->height ?? $bitmap1->getHeight()); + self::assertSame(188, $bitmap1->width ?? $bitmap1->getWidth()); + self::assertSame(691, $bitmap1->height ?? $bitmap1->getHeight()); } } diff --git a/tests/V2/FileOperations/SplitFunctional.php b/tests/V2/FileOperations/SplitFunctional.php index dd12191d..d3b7de4a 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -1,19 +1,27 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->splitModelId = getenv('MINDEE_V2_SPLIT_MODEL_ID') ?: ''; $this->findocModelId = getenv('MINDEE_V2_FINDOC_MODEL_ID') ?: ''; $this->outputDir = getcwd() . '/output'; if (!is_dir($this->outputDir)) { - mkdir($this->outputDir, 0777, true); + mkdir($this->outputDir, 0o777, true); } } @@ -44,38 +52,41 @@ protected function tearDown(): void } } - private function checkFindocReturn(InferenceResponse $findocResponse): void + private function checkFindocReturn(ExtractionResponse $findocResponse): void { - $this->assertGreaterThan(0, strlen($findocResponse->inference->model->id)); + self::assertGreaterThan(0, strlen($findocResponse->inference->model->id)); $totalAmount = $findocResponse->inference->result->fields['total_amount']; - $this->assertNotNull($totalAmount); - $this->assertGreaterThan(0, $totalAmount->value); + self::assertNotNull($totalAmount); + self::assertGreaterThan(0, $totalAmount->value); } + /** + * @throws ImagickException + */ public function testExtractSplitsFromPdfCorrectly(): void { - $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/split/default_sample.pdf'); + $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/split/default_sample.pdf'); $splitParams = new SplitParameters($this->splitModelId); $response = $this->client->enqueueAndGetResult(SplitResponse::class, $inputSource, $splitParams); - $this->assertNotNull($response); - $this->assertCount(2, $response->inference->result->splits); + self::assertNotNull($response); + self::assertCount(2, $response->inference->result->splits); - $splitOperation = new Split($inputSource); - $extractedSplits = $splitOperation->extractSplits( - array_map(fn($s) => $s->pageRange, $response->inference->result->splits) - ); + self::assertInstanceof(SplitResponse::class, $response); + $extractedSplits = $response->inference->result->extractFromInputSource($inputSource); + $extractedSplit0 = $response->inference->result->splits[0]->extractFromInputSource($inputSource); + self::assertEquals($extractedSplit0, $extractedSplits[0]); - $this->assertCount(2, $extractedSplits); - $this->assertEquals('default_sample_001-001.pdf', $extractedSplits[0]->filename); - $this->assertEquals('default_sample_002-002.pdf', $extractedSplits[1]->filename); + self::assertCount(2, $extractedSplits); + self::assertSame('default_sample_001-001.pdf', $extractedSplits[0]->filename); + self::assertSame('default_sample_002-002.pdf', $extractedSplits[1]->filename); $inferenceInput = $extractedSplits[0]->asInputSource(); - $findocParams = new InferenceParameters($this->findocModelId); + $findocParams = new ExtractionParameters($this->findocModelId); - $invoice0 = $this->client->enqueueAndGetResult(InferenceResponse::class, $inferenceInput, $findocParams); + $invoice0 = $this->client->enqueueAndGetResult(ExtractionResponse::class, $inferenceInput, $findocParams); $this->checkFindocReturn($invoice0); @@ -85,11 +96,11 @@ public function testExtractSplitsFromPdfCorrectly(): void $fileName = sprintf('split_%03d.pdf', $i + 1); $filePath = $this->outputDir . '/' . $fileName; - $this->assertFileExists($filePath); - $this->assertGreaterThan(0, filesize($filePath)); + self::assertFileExists($filePath); + self::assertGreaterThan(0, filesize($filePath)); $localInput = new PathInput($filePath); - $this->assertEquals($extractedSplits[$i]->getPageCount(), $localInput->getPageCount()); + self::assertSame($extractedSplits[$i]->getPageCount(), $localInput->getPageCount()); } } -} \ No newline at end of file +} diff --git a/tests/V2/FileOperations/SplitTest.php b/tests/V2/FileOperations/SplitTest.php index 97f8e833..feceaa17 100644 --- a/tests/V2/FileOperations/SplitTest.php +++ b/tests/V2/FileOperations/SplitTest.php @@ -1,5 +1,7 @@ splitDataDir = \TestingUtilities::getV2DataDir() . '/products/split'; - $this->finDocDataDir = \TestingUtilities::getV2DataDir() . '/products/extraction/financial_document'; + $this->splitDataDir = TestingUtilities::getV2DataDir() . '/products/split'; + $this->finDocDataDir = TestingUtilities::getV2DataDir() . '/products/extraction/financial_document'; } public function testProcessesSinglePageSplitCorrectly(): void @@ -28,11 +31,11 @@ public function testProcessesSinglePageSplitCorrectly(): void $splitOperation = new Split($inputSample); $splits = $doc->inference->result->splits; - $extractedSplits = $splitOperation->extractSplits(array_map(fn($s) => $s->pageRange, $splits)); + $extractedSplits = $splitOperation->extractMultipleSplits(array_map(static fn($s) => $s->pageRange, $splits)); - $this->assertCount(1, $extractedSplits); + self::assertCount(1, $extractedSplits); - $this->assertEquals(1, $extractedSplits[0]->getPageCount()); + self::assertSame(1, $extractedSplits[0]->getPageCount()); } public function testProcessesMultiPageReceiptSplitCorrectly(): void @@ -44,12 +47,12 @@ public function testProcessesMultiPageReceiptSplitCorrectly(): void $splitOperation = new Split($inputSample); $splits = $doc->inference->result->splits; - $extractedSplits = $splitOperation->extractSplits(array_map(fn($s) => $s->pageRange, $splits)); + $extractedSplits = $splitOperation->extractMultipleSplits(array_map(static fn($s) => $s->pageRange, $splits)); - $this->assertCount(3, $extractedSplits); + self::assertCount(3, $extractedSplits); - $this->assertEquals(1, $extractedSplits[0]->getPageCount()); - $this->assertEquals(3, $extractedSplits[1]->getPageCount()); - $this->assertEquals(1, $extractedSplits[2]->getPageCount()); + self::assertSame(1, $extractedSplits[0]->getPageCount()); + self::assertSame(3, $extractedSplits[1]->getPageCount()); + self::assertSame(1, $extractedSplits[2]->getPageCount()); } } diff --git a/tests/V2/Input/InferenceParameterTest.php b/tests/V2/Input/InferenceParameterTest.php index c449e46e..e009b907 100644 --- a/tests/V2/Input/InferenceParameterTest.php +++ b/tests/V2/Input/InferenceParameterTest.php @@ -1,11 +1,13 @@ expectedSchemaString = $fileContents; $this->expectedSchemaDict = json_decode($fileContents, true); $this->expectedSchemaObject = new DataSchema($fileContents); } - public function testDataSchemaShouldntReplaceWhenUnset() { - $params = new InferenceParameters('model_id', dataSchema: null); - $this->assertFalse(isset($params->dataSchema)); + public function testDataSchemaShouldntReplaceWhenUnset(): void + { + $params = new ExtractionParameters('model_id', dataSchema: null); + self::assertFalse(isset($params->dataSchema)); } - public function testDataSchemaShouldEquateNoMatterTheType(){ - $paramsDict = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaDict); - $paramsString = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaString); - $paramsObject = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaObject); - $this->assertEquals(strval($paramsDict->dataSchema), $this->expectedSchemaString); - $this->assertEquals(strval($paramsObject->dataSchema), $this->expectedSchemaString); - $this->assertEquals(strval($paramsString->dataSchema), $this->expectedSchemaString); + public function testDataSchemaShouldEquateNoMatterTheType(): void + { + $paramsDict = new ExtractionParameters('model_id', dataSchema: $this->expectedSchemaDict); + $paramsString = new ExtractionParameters('model_id', dataSchema: $this->expectedSchemaString); + $paramsObject = new ExtractionParameters('model_id', dataSchema: $this->expectedSchemaObject); + self::assertSame((string) ($paramsDict->dataSchema), $this->expectedSchemaString); + self::assertSame((string) ($paramsObject->dataSchema), $this->expectedSchemaString); + self::assertSame((string) ($paramsString->dataSchema), $this->expectedSchemaString); } } diff --git a/tests/V2/Input/LocalResponseV2Test.php b/tests/V2/Input/LocalResponseV2Test.php index 0b1b761e..1109af1f 100644 --- a/tests/V2/Input/LocalResponseV2Test.php +++ b/tests/V2/Input/LocalResponseV2Test.php @@ -1,10 +1,14 @@ filePath = \TestingUtilities::getV2DataDir() . '/products/extraction/standard_field_types.json'; + $this->filePath = TestingUtilities::getV2DataDir() . '/products/extraction/standard_field_types.json'; } protected function assertLocalResponse(LocalResponse $localResponse): void { $fakeHMACSigning = "ogNjY44MhvKPGTtVsI8zG82JqWQa68woYQH"; $signature = "e51bdf80f1a08ed44ee161100fc30a25cb35b4ede671b0a575dc9064a3f5dbf1"; - $reflectedLocalResponse = new \ReflectionClass($localResponse); + $reflectedLocalResponse = new ReflectionClass($localResponse); $reflectedFile = $reflectedLocalResponse->getProperty('file'); - $reflectedFile->setAccessible(true); - $this->assertNotNull($reflectedFile); - $this->assertFalse($localResponse->isValidHMACSignature($fakeHMACSigning, "fake HMAC signature")); - $this->assertEquals($signature, $localResponse->getHmacSignature($fakeHMACSigning)); - $this->assertTrue($localResponse->isValidHMACSignature($fakeHMACSigning, $signature)); - $response = $localResponse->deserializeResponse(InferenceResponse::class); - $this->assertInstanceOf(InferenceResponse::class, $response); - $this->assertNotNull($response->inference); - $this->assertNotNull($response->inference->result); - $this->assertNotNull($response->inference->result->fields); + self::assertNotNull($reflectedFile); + self::assertFalse($localResponse->isValidHMACSignature($fakeHMACSigning, "fake HMAC signature")); + self::assertSame($signature, $localResponse->getHmacSignature($fakeHMACSigning)); + self::assertTrue($localResponse->isValidHMACSignature($fakeHMACSigning, $signature)); + $response = $localResponse->deserializeResponse(ExtractionResponse::class); + self::assertInstanceOf(ExtractionResponse::class, $response); + self::assertNotNull($response->inference); + self::assertNotNull($response->inference->result); + self::assertNotNull($response->inference->result->fields); } - public function testValidFileLocalResponse(){ - $file = fopen($this->filePath, 'rb'); + public function testValidFileLocalResponse(): void + { + $file = fopen($this->filePath, 'r'); $localResponse = new LocalResponse($file); fclose($file); $this->assertLocalResponse($localResponse); } - public function testValidPathLocalResponse(){ + public function testValidPathLocalResponse(): void + { $localResponse = new LocalResponse($this->filePath); $this->assertLocalResponse($localResponse); } - public function testValidBytesLocalResponse(){ + public function testValidBytesLocalResponse(): void + { $raw = file_get_contents($this->filePath); $encoding = mb_detect_encoding($raw, ['UTF-8','UTF-16','UTF-32','ISO-8859-1','Windows-1252'], true) ?: 'UTF-8'; $utf8 = ($encoding === 'UTF-8') ? $raw : mb_convert_encoding($raw, 'UTF-8', $encoding); diff --git a/tests/V2/Parsing/ExtractionResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php new file mode 100644 index 00000000..ad6e85b8 --- /dev/null +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -0,0 +1,446 @@ +deserializeResponse(ExtractionResponse::class); + } + + private function readFileAsString(string $path): string + { + self::assertFileExists($path, "Resource file must exist: $path"); + + return file_get_contents($path); + } + + /** + * When the async prediction is blank - all properties must be valid. + */ + public function testAsyncPredictWhenEmptyMustHaveValidProperties(): void + { + $response = $this->loadFromResource('extraction/financial_document/blank.json'); + $fields = $response->inference->result->fields; + + self::assertCount(21, $fields, 'Expected 21 fields'); + + self::assertInstanceOf( + SimpleField::class, + $fields['total_amount'], + "Field 'total_amount' must be a SimpleField" + ); + $totalAmount = $fields->getSimpleField('total_amount'); + self::assertEmpty($totalAmount->value); + self::assertNull($totalAmount->getFloatValue()); + + self::assertInstanceOf( + ListField::class, + $fields['taxes'], + "Field 'taxes' must be a ListField" + ); + $taxes = $fields->getListField('taxes'); + self::assertEmpty($taxes->items); + + self::assertInstanceOf( + ObjectField::class, + $fields['supplier_address'], + "Field 'supplier_address' must be an ObjectField" + ); + $supplierAddress = $fields->getObjectField('supplier_address'); + self::assertCount(9, $supplierAddress->fields); + + foreach ($fields as $fieldName => $field) { + if (null === $field) { + continue; + } + if ($field instanceof ListField) { + self::assertEmpty($field->items, "Field $fieldName.items must be empty"); + } elseif ($field instanceof ObjectField) { + foreach ($field->fields as $subFieldName => $subField) { + self::assertEmpty($subField->value, "Field $fieldName.$subFieldName must be empty"); + } + } elseif ($field instanceof SimpleField) { + self::assertIsNotObject($field->value, "Field $fieldName must be a scalar value"); + } else { + self::fail("Unknown field type: $fieldName"); + } + } + } + + /** + * When the async prediction is complete - every exposed property must be valid and consistent. + */ + public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void + { + $response = $this->loadFromResource('extraction/financial_document/complete.json'); + $inference = $response->inference; + + self::assertNotNull($inference, 'Inference must not be null'); + self::assertSame('12345678-1234-1234-1234-123456789abc', $inference->id, 'ExtractionInference ID mismatch'); + + $model = $inference->model; + self::assertNotNull($model, 'Model must not be null'); + self::assertSame('12345678-1234-1234-1234-123456789abc', $model->id, 'Model ID mismatch'); + + $file = $inference->file; + self::assertNotNull($file, 'File must not be null'); + self::assertSame('complete.jpg', $file->name, 'File name mismatch'); + self::assertSame(1, $file->pageCount, 'File page count mismatch'); + self::assertSame('image/jpeg', $file->mimeType, 'File MIME type mismatch'); + self::assertNull($file->alias ?? null, 'File alias must be null for this payload'); + + $fields = $inference->result->fields; + self::assertCount(21, $fields, 'Expected 21 fields in the payload'); + + $date = $fields->get('date'); + self::assertInstanceOf(SimpleField::class, $date); + self::assertSame('2019-11-02', $date->getStringValue(), "'date' value mismatch"); + + $taxes = $fields->getListField('taxes'); + self::assertNotNull($taxes, "'taxes' field must exist"); + self::assertInstanceOf(ListField::class, $taxes, "'taxes' must be a ListField"); + self::assertCount(1, $taxes->items, "'taxes' list must contain exactly one item"); + + $taxItemObj = $taxes->items[0]; + self::assertInstanceOf(ObjectField::class, $taxItemObj, 'First item of "taxes" must be an ObjectField'); + self::assertCount(3, $taxItemObj->fields, 'Tax ObjectField must contain 3 sub-fields'); + + $baseTax = $taxItemObj->fields->get('base'); + self::assertInstanceOf(SimpleField::class, $baseTax); + self::assertSame(31.5, $baseTax->getFloatValue(), "'taxes.base' value mismatch"); + self::assertNotNull((string) $taxes, "'taxes'.__toString() must not be null"); + + $supplierAddress = $fields->getObjectField('supplier_address'); + self::assertNotNull($supplierAddress, "'supplier_address' field must exist"); + self::assertInstanceOf(ObjectField::class, $supplierAddress, "'supplier_address' must be an ObjectField"); + + $country = $supplierAddress->fields->get('country'); + self::assertNotNull($country, "'supplier_address.country' must exist"); + self::assertInstanceOf(SimpleField::class, $country); + self::assertSame('USA', $country->getStringValue(), 'Country mismatch'); + self::assertSame('USA', (string) $country, "'country'.__toString() mismatch"); + self::assertNotNull((string) $supplierAddress, "'supplier_address'.__toString() must not be null"); + + $customerAddr = $fields->get('customer_address'); + self::assertInstanceOf(ObjectField::class, $customerAddr); + $city = $customerAddr->fields->get('city'); + self::assertInstanceOf(SimpleField::class, $city); + self::assertSame('New York', $city->getStringValue(), 'City mismatch'); + + self::assertNull($inference->result->options ?? null, 'Options must be null'); + } + + /** + * Deep nested fields - all nested structures must be typed correctly. + */ + public function testDeepNestedFieldsMustExposeCorrectTypes(): void + { + $response = $this->loadFromResource('extraction/deep_nested_fields.json'); + $inference = $response->inference; + self::assertNotNull($inference); + + $root = $inference->result->fields; + self::assertInstanceOf(SimpleField::class, $root->get('field_simple')); + self::assertInstanceOf(ObjectField::class, $root->get('field_object')); + + $fieldObject = $root->get('field_object'); + self::assertInstanceOf(ObjectField::class, $fieldObject); + self::assertInstanceOf(SimpleField::class, $fieldObject->getSimpleField('sub_object_simple')); + self::assertInstanceOf(ListField::class, $fieldObject->getListField('sub_object_list')); + self::assertInstanceOf(ObjectField::class, $fieldObject->getObjectField('sub_object_object')); + self::assertCount(1, $fieldObject->getSimpleFields()); + self::assertCount(1, $fieldObject->getListFields()); + self::assertCount(1, $fieldObject->getObjectFields()); + $lvl1 = $fieldObject->fields; + self::assertInstanceOf(SimpleField::class, $lvl1->get('sub_object_simple')); + self::assertInstanceOf(ListField::class, $lvl1->get('sub_object_list')); + self::assertInstanceOf(ObjectField::class, $lvl1->get('sub_object_object')); + + $subObjectObject = $lvl1->get('sub_object_object'); + self::assertInstanceOf(ObjectField::class, $subObjectObject); + $lvl2 = $subObjectObject->fields; + self::assertInstanceOf(ListField::class, $lvl2->get('sub_object_object_sub_object_list')); + + $nestedList = $lvl2->get('sub_object_object_sub_object_list'); + self::assertInstanceOf(ListField::class, $nestedList); + $items = $nestedList->items; + self::assertNotEmpty($items); + self::assertInstanceOf(ObjectField::class, $items[0]); + + $firstItem = $items[0]; + self::assertInstanceOf(ObjectField::class, $firstItem); + $deepSimple = $firstItem->fields->get('sub_object_object_sub_object_list_simple'); + self::assertInstanceOf(SimpleField::class, $deepSimple); + self::assertSame('value_9', $deepSimple->getStringValue()); + } + + /** + * Standard field types - simple / object / list variants must be recognised. + */ + public function testStandardFieldTypesMustExposeCorrectTypes(): void + { + $response = $this->loadFromResource('extraction/standard_field_types.json'); + $inference = $response->inference; + self::assertNotNull($inference); + + $fields = $inference->result->fields; + + $fieldSimpleString = $fields->get('field_simple_string'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleString); + self::assertIsString($fieldSimpleString->getStringValue()); + + $fieldSimpleFloat = $fields->get('field_simple_float'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleFloat); + self::assertIsFloat($fieldSimpleFloat->getFloatValue()); + + $fieldSimpleInt = $fields->get('field_simple_int'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleInt); + self::assertIsFloat($fieldSimpleInt->getFloatValue()); + + $fieldSimpleZero = $fields->get('field_simple_zero'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleZero); + self::assertIsFloat($fieldSimpleZero->getFloatValue()); + + $fieldSimpleBool = $fields->get('field_simple_bool'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleBool); + self::assertIsBool($fieldSimpleBool->getBoolValue()); + + $fieldSimpleNull = $fields->get('field_simple_null'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleNull); + self::assertNull($fieldSimpleNull->value); + self::assertNull($fieldSimpleNull->getStringValue()); + self::assertNull($fieldSimpleNull->getFloatValue()); + self::assertNull($fieldSimpleNull->getBoolValue()); + + $fieldSimpleList = $fields->get('field_simple_list'); + self::assertInstanceOf(ListField::class, $fieldSimpleList); + $simpleItems = $fieldSimpleList->items; + self::assertCount(2, $simpleItems); + + $firstSimpleItem = $simpleItems[0]; + self::assertInstanceOf(SimpleField::class, $firstSimpleItem); + self::assertIsString($firstSimpleItem->getStringValue()); + + foreach ($fieldSimpleList->items as $item) { + self::assertInstanceOf(SimpleField::class, $item); + self::assertIsString($item->getStringValue()); + } + + $fieldObject = $fields->get('field_object'); + self::assertInstanceOf(ObjectField::class, $fieldObject); + $fieldObjectFields = $fieldObject->fields; + self::assertCount(2, $fieldObjectFields); + foreach ($fieldObjectFields as $subField) { + self::assertInstanceOf(SimpleField::class, $subField); + } + + $subfield1 = $fieldObjectFields->getSimpleField('subfield_1'); + self::assertInstanceOf(SimpleField::class, $subfield1); + self::assertIsString($subfield1->getStringValue()); + + $fieldObjectList = $fields->get('field_object_list'); + self::assertInstanceOf(ListField::class, $fieldObjectList); + $objectItems = $fieldObjectList->items; + self::assertCount(2, $objectItems); + + $firstObjectItem = $objectItems[0]; + self::assertInstanceOf(ObjectField::class, $firstObjectItem); + + $firstObjectSubfield = $firstObjectItem->fields->get('subfield_1'); + self::assertInstanceOf(SimpleField::class, $firstObjectSubfield); + self::assertIsString($firstObjectSubfield->getStringValue()); + + foreach ($fieldObjectList->items as $item) { + self::assertInstanceOf(ObjectField::class, $item); + $subfield = $item->fields->get('subfield_1'); + self::assertInstanceOf(SimpleField::class, $subfield); + self::assertIsString($subfield->getStringValue()); + } + } + + /** + * Raw texts option must be parsed and exposed. + */ + public function testRawTextsMustBeAccessible(): void + { + $response = $this->loadFromResource('extraction/raw_texts.json'); + $inference = $response->inference; + self::assertNotNull($inference); + + $activeOptions = $inference->activeOptions; + self::assertTrue($activeOptions->rawText); + self::assertFalse($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); + + $rawText = $inference->result->rawText; + self::assertNotNull($rawText); + self::assertCount(2, $rawText->pages); + + $first = $rawText->pages[0]; + self::assertSame('This is the raw text of the first page...', $first->content); + + foreach ($rawText->pages as $page) { + self::assertIsString($page->content); + } + } + + /** + * RST display must be parsed and exposed. + */ + public function testRstDisplayMustBeAccessible(): void + { + $response = $this->loadFromResource('extraction/standard_field_types.json'); + $expectedRst = $this->readFileAsString( + TestingUtilities::getV2ProductDir() . '/extraction/standard_field_types.rst' + ); + $inference = $response->inference; + self::assertNotNull($inference); + self::assertSame($expectedRst, (string) ($response->inference)); + } + + /** + * Coordinates & location data must be parsed and exposed. + */ + public function testCoordinatesAndLocationDataMustBeAccessible(): void + { + $response = $this->loadFromResource('extraction/financial_document/complete_with_coordinates.json'); + $inference = $response->inference; + self::assertNotNull($inference); + + $fields = $response->inference->result->fields; + + $dateField = $fields->getSimpleField('date'); + self::assertCount(1, $dateField->locations); + + $location = $dateField->locations[0]; + self::assertNotNull($location); + self::assertSame(0, $location->page); + self::assertSame( + 0.948979073166918, + $location->polygon->coordinates[0]->getX() + ); + self::assertSame( + 0.23097924535067715, + $location->polygon->coordinates[0]->getY() + ); + self::assertSame(0.85422, $location->polygon->coordinates[1][0]); + self::assertSame(0.230072, $location->polygon->coordinates[1][1]); + self::assertSame( + 0.8540899268330819, + $location->polygon->coordinates[2][0] + ); + self::assertSame( + 0.24365775464932288, + $location->polygon->coordinates[2][1] + ); + self::assertSame(0.948849, $location->polygon->coordinates[3][0]); + self::assertSame(0.244565, $location->polygon->coordinates[3][1]); + self::assertEquals( + new Point(0.9015345, 0.23731850000000002), + $location->polygon->getCentroid() + ); + self::assertSame(FieldConfidence::Medium, $dateField->confidence); + self::assertSame(FieldConfidence::Medium->rank(), $dateField->confidence->rank()); + self::assertTrue(FieldConfidence::Medium->equal($dateField->confidence)); + self::assertLessThan(FieldConfidence::High->rank(), $dateField->confidence->rank()); + self::assertTrue(FieldConfidence::High->greaterThan($dateField->confidence)); + self::assertTrue(FieldConfidence::Medium->greaterThanOrEqual($dateField->confidence)); + self::assertTrue(FieldConfidence::High->greaterThanOrEqual($dateField->confidence)); + self::assertGreaterThan(FieldConfidence::Low->rank(), $dateField->confidence->rank()); + self::assertTrue(FieldConfidence::Low->lessThan($dateField->confidence)); + self::assertTrue(FieldConfidence::Low->lessThanOrEqual($dateField->confidence)); + self::assertTrue(FieldConfidence::Medium->lessThanOrEqual($dateField->confidence)); + self::assertSame('Medium', $dateField->confidence->value); + + $activeOptions = $inference->activeOptions; + self::assertTrue($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); + self::assertFalse($activeOptions->rawText); + self::assertFalse($activeOptions->textContext); + } + + public function testRagMetadataWhenMatched(): void + { + $response = $this->loadFromResource('extraction/rag_matched.json'); + $inference = $response->inference; + self::assertNotNull($inference); + self::assertSame('12345abc-1234-1234-1234-123456789abc', $inference->result->rag->retrievedDocumentId); + } + + public function testRagMetadataWhenNotMatched(): void + { + $response = $this->loadFromResource('extraction/rag_not_matched.json'); + $inference = $response->inference; + self::assertNotNull($inference); + self::assertNull($inference->result->rag->retrievedDocumentId); + } + + public function testShouldLoadWith422Error(): void + { + $jsonResponse = json_decode( + file_get_contents(TestingUtilities::getV2DataDir() . '/job/fail_422.json'), + true + ); + $response = new JobResponse($jsonResponse); + self::assertNotNull($response->job); + self::assertInstanceOf(ErrorResponse::class, $response->job->error); + self::assertSame(422, $response->job->error->status); + self::assertStringStartsWith("422-", $response->job->error->code); + self::assertCount(1, $response->job->error->errors); + self::assertInstanceOf(ErrorItem::class, $response->job->error->errors[0]); + } + + public function testTextContextIsTrue(): void + { + $response = $this->loadFromResource('extraction/text_context_enabled.json'); + $inference = $response->inference; + self::assertNotNull($inference); + $activeOptions = $inference->activeOptions; + self::assertFalse($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); + self::assertFalse($activeOptions->rawText); + self::assertTrue($activeOptions->textContext); + } + + public function testTextContextIsFalse(): void + { + $response = $this->loadFromResource('extraction/financial_document/complete.json'); + $inference = $response->inference; + self::assertNotNull($inference); + $activeOptions = $inference->activeOptions; + self::assertFalse($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); + self::assertFalse($activeOptions->rawText); + self::assertFalse($activeOptions->textContext); + } +} diff --git a/tests/V2/Parsing/InferenceResponseTest.php b/tests/V2/Parsing/InferenceResponseTest.php deleted file mode 100644 index 89b9b1c6..00000000 --- a/tests/V2/Parsing/InferenceResponseTest.php +++ /dev/null @@ -1,446 +0,0 @@ -assertFileExists($fullPath, "Resource file must exist: $resourcePath"); - - $localResponse = new LocalResponse($fullPath); - return $localResponse->deserializeResponse(InferenceResponse::class); - } - - private function readFileAsString(string $path): string - { - $this->assertFileExists($path, "Resource file must exist: $path"); - - return file_get_contents($path); - } - - /** - * When the async prediction is blank - all properties must be valid. - * @return void - */ - public function testAsyncPredictWhenEmptyMustHaveValidProperties(): void - { - $response = $this->loadFromResource('extraction/financial_document/blank.json'); - $fields = $response->inference->result->fields; - - $this->assertCount(21, $fields, 'Expected 21 fields'); - - $this->assertInstanceOf( - SimpleField::class, - $fields['total_amount'], - "Field 'total_amount' must be a SimpleField" - ); - $totalAmount = $fields->getSimpleField('total_amount'); - $this->assertEmpty($totalAmount->value); - - $this->assertInstanceOf( - ListField::class, - $fields['taxes'], - "Field 'taxes' must be a ListField" - ); - $taxes = $fields->getListField('taxes'); - $this->assertEmpty($taxes->items); - - $this->assertInstanceOf( - ObjectField::class, - $fields['supplier_address'], - "Field 'supplier_address' must be an ObjectField" - ); - $supplierAddress = $fields->getObjectField('supplier_address'); - $this->assertCount(9, $supplierAddress->fields); - - foreach ($fields as $fieldName => $field) { - if ($field === null) { - continue; - } - if ($field instanceof ListField) { - $this->assertEmpty($field->items, "Field $fieldName.items must be empty"); - } elseif ($field instanceof ObjectField) { - foreach ($field->fields as $subFieldName => $subField) { - $this->assertEmpty($subField->value, "Field $fieldName.$subFieldName must be empty"); - } - } elseif ($field instanceof SimpleField) { - $this->assertIsNotObject($field->value, "Field $fieldName must be a scalar value"); - } else { - $this->fail("Unknown field type: $fieldName"); - } - } - } - - /** - * When the async prediction is complete - every exposed property must be valid and consistent. - * @return void - */ - public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void - { - $response = $this->loadFromResource('extraction/financial_document/complete.json'); - $inference = $response->inference; - - $this->assertNotNull($inference, 'Inference must not be null'); - $this->assertEquals('12345678-1234-1234-1234-123456789abc', $inference->id, 'Inference ID mismatch'); - - $model = $inference->model; - $this->assertNotNull($model, 'Model must not be null'); - $this->assertEquals('12345678-1234-1234-1234-123456789abc', $model->id, 'Model ID mismatch'); - - $file = $inference->file; - $this->assertNotNull($file, 'File must not be null'); - $this->assertEquals('complete.jpg', $file->name, 'File name mismatch'); - $this->assertEquals(1, $file->pageCount, 'File page count mismatch'); - $this->assertEquals('image/jpeg', $file->mimeType, 'File MIME type mismatch'); - $this->assertNull($file->alias ?? null, 'File alias must be null for this payload'); - - $fields = $inference->result->fields; - $this->assertCount(21, $fields, 'Expected 21 fields in the payload'); - - $date = $fields->get('date'); - $this->assertInstanceOf(SimpleField::class, $date); - $this->assertEquals('2019-11-02', $date->value, "'date' value mismatch"); - - $taxes = $fields->getListField('taxes'); - $this->assertNotNull($taxes, "'taxes' field must exist"); - $this->assertInstanceOf(ListField::class, $taxes, "'taxes' must be a ListField"); - $this->assertCount(1, $taxes->items, "'taxes' list must contain exactly one item"); - - $taxItemObj = $taxes->items[0]; - $this->assertInstanceOf(ObjectField::class, $taxItemObj, 'First item of "taxes" must be an ObjectField'); - $this->assertCount(3, $taxItemObj->fields, 'Tax ObjectField must contain 3 sub-fields'); - - $baseTax = $taxItemObj->fields->get('base'); - $this->assertInstanceOf(SimpleField::class, $baseTax); - $this->assertEquals(31.5, $baseTax->value, "'taxes.base' value mismatch"); - $this->assertNotNull(strval($taxes), "'taxes'.__toString() must not be null"); - - $supplierAddress = $fields->getObjectField('supplier_address'); - $this->assertNotNull($supplierAddress, "'supplier_address' field must exist"); - $this->assertInstanceOf(ObjectField::class, $supplierAddress, "'supplier_address' must be an ObjectField"); - - $country = $supplierAddress->fields->get('country'); - $this->assertNotNull($country, "'supplier_address.country' must exist"); - $this->assertInstanceOf(SimpleField::class, $country); - $this->assertEquals('USA', $country->value, 'Country mismatch'); - $this->assertEquals('USA', strval($country), "'country'.__toString() mismatch"); - $this->assertNotNull(strval($supplierAddress), "'supplier_address'.__toString() must not be null"); - - $customerAddr = $fields->get('customer_address'); - $this->assertInstanceOf(ObjectField::class, $customerAddr); - $city = $customerAddr->fields->get('city'); - $this->assertInstanceOf(SimpleField::class, $city); - $this->assertEquals('New York', $city->value, 'City mismatch'); - - $this->assertNull($inference->result->options ?? null, 'Options must be null'); - } - - /** - * Deep nested fields - all nested structures must be typed correctly. - * @return void - */ - public function testDeepNestedFieldsMustExposeCorrectTypes(): void - { - $response = $this->loadFromResource('extraction/deep_nested_fields.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - - $root = $inference->result->fields; - $this->assertInstanceOf(SimpleField::class, $root->get('field_simple')); - $this->assertInstanceOf(ObjectField::class, $root->get('field_object')); - - $fieldObject = $root->get('field_object'); - $this->assertInstanceOf(ObjectField::class, $fieldObject); - $this->assertInstanceOf(SimpleField::class, $fieldObject->getSimpleField('sub_object_simple')); - $this->assertInstanceOf(ListField::class, $fieldObject->getListField('sub_object_list')); - $this->assertInstanceOf(ObjectField::class, $fieldObject->getObjectField('sub_object_object')); - $this->assertEquals(1, count($fieldObject->getSimpleFields())); - $this->assertEquals(1, count($fieldObject->getListFields())); - $this->assertEquals(1, count($fieldObject->getObjectFields())); - $lvl1 = $fieldObject->fields; - $this->assertInstanceOf(SimpleField::class, $lvl1->get('sub_object_simple')); - $this->assertInstanceOf(ListField::class, $lvl1->get('sub_object_list')); - $this->assertInstanceOf(ObjectField::class, $lvl1->get('sub_object_object')); - - $subObjectObject = $lvl1->get('sub_object_object'); - $this->assertInstanceOf(ObjectField::class, $subObjectObject); - $lvl2 = $subObjectObject->fields; - $this->assertInstanceOf(ListField::class, $lvl2->get('sub_object_object_sub_object_list')); - - $nestedList = $lvl2->get('sub_object_object_sub_object_list'); - $this->assertInstanceOf(ListField::class, $nestedList); - $items = $nestedList->items; - $this->assertNotEmpty($items); - $this->assertInstanceOf(ObjectField::class, $items[0]); - - $firstItem = $items[0]; - $this->assertInstanceOf(ObjectField::class, $firstItem); - $deepSimple = $firstItem->fields->get('sub_object_object_sub_object_list_simple'); - $this->assertInstanceOf(SimpleField::class, $deepSimple); - $this->assertEquals('value_9', $deepSimple->value); - } - - /** - * Standard field types - simple / object / list variants must be recognised. - * @return void - */ - public function testStandardFieldTypesMustExposeCorrectTypes(): void - { - $response = $this->loadFromResource('extraction/standard_field_types.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - - $fields = $inference->result->fields; - - $fieldSimpleString = $fields->get('field_simple_string'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleString); - $this->assertIsString($fieldSimpleString->value); - - $fieldSimpleFloat = $fields->get('field_simple_float'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleFloat); - $this->assertIsFloat($fieldSimpleFloat->value); - - $fieldSimpleInt = $fields->get('field_simple_int'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleInt); - $this->assertIsFloat($fieldSimpleInt->value); - - $fieldSimpleZero = $fields->get('field_simple_zero'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleZero); - $this->assertIsFloat($fieldSimpleZero->value); - - $fieldSimpleBool = $fields->get('field_simple_bool'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleBool); - $this->assertIsBool($fieldSimpleBool->value); - - $fieldSimpleNull = $fields->get('field_simple_null'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleNull); - $this->assertNull($fieldSimpleNull->value); - - $fieldSimpleList = $fields->get('field_simple_list'); - $this->assertInstanceOf(ListField::class, $fieldSimpleList); - $simpleItems = $fieldSimpleList->items; - $this->assertCount(2, $simpleItems); - - $firstSimpleItem = $simpleItems[0]; - $this->assertInstanceOf(SimpleField::class, $firstSimpleItem); - $this->assertIsString($firstSimpleItem->value); - - foreach ($fieldSimpleList->items as $item) { - $this->assertInstanceOf(SimpleField::class, $item); - $this->assertIsString($item->value); - } - - $fieldObject = $fields->get('field_object'); - $this->assertInstanceOf(ObjectField::class, $fieldObject); - $fieldObjectFields = $fieldObject->fields; - $this->assertCount(2, $fieldObjectFields); - foreach ($fieldObjectFields as $fieldName => $subField) { - $this->assertInstanceOf(SimpleField::class, $subField); - } - - $subfield1 = $fieldObjectFields->getSimpleField('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $subfield1); - $this->assertIsString($subfield1->value); - - $fieldObjectList = $fields->get('field_object_list'); - $this->assertInstanceOf(ListField::class, $fieldObjectList); - $objectItems = $fieldObjectList->items; - $this->assertCount(2, $objectItems); - - $firstObjectItem = $objectItems[0]; - $this->assertInstanceOf(ObjectField::class, $firstObjectItem); - - $firstObjectSubfield = $firstObjectItem->fields->get('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $firstObjectSubfield); - $this->assertIsString($firstObjectSubfield->value); - - foreach ($fieldObjectList->items as $item) { - $this->assertInstanceOf(ObjectField::class, $item); - $subfield = $item->fields->get('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $subfield); - $this->assertIsString($subfield->value); - } - } - - /** - * Raw texts option must be parsed and exposed. - * @return void - */ - public function testRawTextsMustBeAccessible(): void - { - $response = $this->loadFromResource('extraction/raw_texts.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - - $activeOptions = $inference->activeOptions; - $this->assertTrue($activeOptions->rawText); - $this->assertFalse($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); - - $rawText = $inference->result->rawText; - $this->assertNotNull($rawText); - $this->assertCount(2, $rawText->pages); - - $first = $rawText->pages[0]; - $this->assertEquals('This is the raw text of the first page...', $first->content); - - foreach ($rawText->pages as $page) { - $this->assertIsString($page->content); - } - } - - /** - * RST display must be parsed and exposed. - * @return void - */ - public function testRstDisplayMustBeAccessible(): void - { - $response = $this->loadFromResource('extraction/standard_field_types.json'); - $expectedRst = $this->readFileAsString( - \TestingUtilities::getV2ProductDir() . '/extraction/standard_field_types.rst' - ); - $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertEquals($expectedRst, strval($response->inference)); - } - - /** - * Coordinates & location data must be parsed and exposed. - * @return void - */ - public function testCoordinatesAndLocationDataMustBeAccessible(): void - { - $response = $this->loadFromResource('extraction/financial_document/complete_with_coordinates.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - - $fields = $response->inference->result->fields; - - $dateField = $fields->getSimpleField('date'); - $this->assertCount(1, $dateField->locations); - - $location = $dateField->locations[0]; - $this->assertNotNull($location); - $this->assertEquals(0, $location->page); - $this->assertEquals( - 0.948979073166918, - $location->polygon->coordinates[0]->getX() - ); - $this->assertEquals( - 0.23097924535067715, - $location->polygon->coordinates[0]->getY() - ); - $this->assertEquals(0.85422, $location->polygon->coordinates[1][0]); - $this->assertEquals(0.230072, $location->polygon->coordinates[1][1]); - $this->assertEquals( - 0.8540899268330819, - $location->polygon->coordinates[2][0] - ); - $this->assertEquals( - 0.24365775464932288, - $location->polygon->coordinates[2][1] - ); - $this->assertEquals(0.948849, $location->polygon->coordinates[3][0]); - $this->assertEquals(0.244565, $location->polygon->coordinates[3][1]); - $this->assertEquals( - new Point(0.9015345, 0.23731850000000002), - $location->polygon->getCentroid() - ); - $this->assertEquals(FieldConfidence::Medium, $dateField->confidence); - $this->assertEquals(FieldConfidence::Medium->rank(), $dateField->confidence->rank()); - $this->assertTrue(FieldConfidence::Medium->equal($dateField->confidence)); - $this->assertLessThan(FieldConfidence::High->rank(), $dateField->confidence->rank()); - $this->assertTrue(FieldConfidence::High->greaterThan($dateField->confidence)); - $this->assertTrue(FieldConfidence::Medium->greaterThanOrEqual($dateField->confidence)); - $this->assertTrue(FieldConfidence::High->greaterThanOrEqual($dateField->confidence)); - $this->assertGreaterThan(FieldConfidence::Low->rank(), $dateField->confidence->rank()); - $this->assertTrue(FieldConfidence::Low->lessThan($dateField->confidence)); - $this->assertTrue(FieldConfidence::Low->lessThanOrEqual($dateField->confidence)); - $this->assertTrue(FieldConfidence::Medium->lessThanOrEqual($dateField->confidence)); - $this->assertEquals('Medium', $dateField->confidence->value); - - $activeOptions = $inference->activeOptions; - $this->assertTrue($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); - $this->assertFalse($activeOptions->rawText); - $this->assertFalse($activeOptions->textContext); - } - - public function testRagMetadataWhenMatched() - { - $response = $this->loadFromResource('extraction/rag_matched.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertEquals('12345abc-1234-1234-1234-123456789abc', $inference->result->rag->retrievedDocumentId); - } - - public function testRagMetadataWhenNotMatched() - { - $response = $this->loadFromResource('extraction/rag_not_matched.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertNull($inference->result->rag->retrievedDocumentId); - } - - public function testShouldLoadWith422Error() - { - $jsonResponse = json_decode( - file_get_contents(\TestingUtilities::getV2DataDir() . '/job/fail_422.json'), true - ); - $response = new JobResponse($jsonResponse); - $this->assertNotNull($response->job); - $this->assertInstanceOf(ErrorResponse::class, $response->job->error); - $this->assertEquals(422, $response->job->error->status); - $this->assertStringStartsWith("422-", $response->job->error->code); - $this->assertEquals(1, count($response->job->error->errors)); - $this->assertInstanceOf(ErrorItem::class, $response->job->error->errors[0]); - } - - public function testTextContextIsTrue(): void - { - $response = $this->loadFromResource('extraction/text_context_enabled.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - $activeOptions = $inference->activeOptions; - $this->assertFalse($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); - $this->assertFalse($activeOptions->rawText); - $this->assertTrue($activeOptions->textContext); - } - - public function testTextContextIsFalse(): void - { - $response = $this->loadFromResource('extraction/financial_document/complete.json'); - $inference = $response->inference; - $this->assertNotNull($inference); - $activeOptions = $inference->activeOptions; - $this->assertFalse($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); - $this->assertFalse($activeOptions->rawText); - $this->assertFalse($activeOptions->textContext); - } -} diff --git a/tests/V2/Parsing/JobResponseTest.php b/tests/V2/Parsing/JobResponseTest.php index 0a09d4d5..9cba008f 100644 --- a/tests/V2/Parsing/JobResponseTest.php +++ b/tests/V2/Parsing/JobResponseTest.php @@ -1,17 +1,19 @@ assertNotNull($response->job); - $this->assertSame('Processing', $response->job->status); - $this->assertNull($response->job->completedAt); - $this->assertNull($response->job->error); - $this->assertIsArray($response->job->webhooks); - $this->assertCount(0, $response->job->webhooks); + self::assertNotNull($response->job); + self::assertSame('Processing', $response->job->status); + self::assertNull($response->job->completedAt); + self::assertNull($response->job->error); + self::assertIsArray($response->job->webhooks); + self::assertCount(0, $response->job->webhooks); } /** * Should load when status is Processed. - * @return void */ public function testShouldLoadWhenStatusIsProcessed(): void { $jsonSample = self::getJobSamples('ok_processed_webhooks_ok.json'); $response = new JobResponse($jsonSample); - $this->assertNotNull($response->job); - $this->assertSame('Processed', $response->job->status); - $this->assertInstanceOf(DateTime::class, $response->job->completedAt); - $this->assertNull($response->job->error); + self::assertNotNull($response->job); + self::assertSame('Processed', $response->job->status); + self::assertInstanceOf(DateTime::class, $response->job->completedAt); + self::assertNull($response->job->error); } /** * Should load with 422 error. - * @return void */ public function testShouldLoadWith422Error(): void { $jsonSample = self::getJobSamples('fail_422.json'); $response = new JobResponse($jsonSample); - $this->assertNotNull($response->job); - $this->assertSame('Failed', $response->job->status); - $this->assertInstanceOf(DateTime::class, $response->job->completedAt); + self::assertNotNull($response->job); + self::assertSame('Failed', $response->job->status); + self::assertInstanceOf(DateTime::class, $response->job->completedAt); - $this->assertInstanceOf(ErrorResponse::class, $response->job->error); - $this->assertSame(422, $response->job->error->status); - $this->assertStringStartsWith('422-', $response->job->error->code); - $this->assertIsArray($response->job->error->errors); - $this->assertCount(1, $response->job->error->errors); - $this->assertInstanceOf(ErrorItem::class, $response->job->error->errors[0]); + self::assertInstanceOf(ErrorResponse::class, $response->job->error); + self::assertSame(422, $response->job->error->status); + self::assertStringStartsWith('422-', $response->job->error->code); + self::assertIsArray($response->job->error->errors); + self::assertCount(1, $response->job->error->errors); + self::assertInstanceOf(ErrorItem::class, $response->job->error->errors[0]); } } diff --git a/tests/V2/Parsing/SearchResponseTest.php b/tests/V2/Parsing/SearchResponseTest.php new file mode 100644 index 00000000..bc3f6fce --- /dev/null +++ b/tests/V2/Parsing/SearchResponseTest.php @@ -0,0 +1,44 @@ +models); + foreach ($response->models as $model) { + self::assertInstanceOf(SearchModel::class, $model); + self::assertNotEmpty($model->id); + self::assertNotEmpty($model->name); + } + self::assertCount(2, $response->models[0]->webhooks); + self::assertEquals("https://failure.mindee.com", $response->models[0]->webhooks[0]->url); + + self::assertEquals(50, $response->pagination->perPage); + self::assertEquals(1, $response->pagination->page); + self::assertGreaterThanOrEqual(5, $response->pagination->totalItems); + self::assertEquals(1, $response->pagination->totalPages); + } +} diff --git a/tests/V2/Product/ClassificationFunctional.php b/tests/V2/Product/ClassificationFunctional.php index 5d91bce7..641c971f 100644 --- a/tests/V2/Product/ClassificationFunctional.php +++ b/tests/V2/Product/ClassificationFunctional.php @@ -1,10 +1,11 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->classificationModelId = getenv('MINDEE_V2_CLASSIFICATION_MODEL_ID') ?: ''; } @@ -28,7 +29,6 @@ protected function setUp(): void /** * Tests the success of the classification process using a default sample file. * - * @return void */ public function testClassificationDefaultSampleMustSucceed(): void { @@ -39,17 +39,17 @@ public function testClassificationDefaultSampleMustSucceed(): void $productParams = new ClassificationParameters($this->classificationModelId); $response = $this->client->enqueueAndGetResult(ClassificationResponse::class, $inputSource, $productParams); - $this->assertNotNull($response); - $this->assertNotNull($response->inference); + self::assertNotNull($response); + self::assertNotNull($response->inference); $file = $response->inference->file; - $this->assertNotNull($file); - $this->assertSame("default_sample.jpg", $file->name); + self::assertNotNull($file); + self::assertSame("default_sample.jpg", $file->name); $result = $response->inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); $classifications = $result->classification; - $this->assertNotNull($classifications); + self::assertNotNull($classifications); } } diff --git a/tests/V2/Product/ClassificationTest.php b/tests/V2/Product/ClassificationTest.php index 4f6b9357..6f57c158 100644 --- a/tests/V2/Product/ClassificationTest.php +++ b/tests/V2/Product/ClassificationTest.php @@ -1,5 +1,7 @@ assertNotNull($response->inference); - $this->assertNotNull($response->inference->id); - $this->assertNotNull($response->inference->file); - $this->assertNotNull($response->inference->result); + self::assertNotNull($response->inference); + self::assertNotNull($response->inference->id); + self::assertNotNull($response->inference->file); + self::assertNotNull($response->inference->result); } /** * Should correctly map properties when reading a single classification JSON. - * @return void */ public function testClassificationWhenSingleMustHaveValidProperties(): void { @@ -52,15 +52,15 @@ public function testClassificationWhenSingleMustHaveValidProperties(): void $inference = $response->inference; - $this->assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); - $this->assertSame("test-model-id", $inference->model->id); - $this->assertSame("12345678-1234-1234-1234-jobid1234567", $inference->job->id); + self::assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); + self::assertSame("test-model-id", $inference->model->id); + self::assertSame("12345678-1234-1234-1234-jobid1234567", $inference->job->id); - $this->assertSame("default_sample.jpg", $inference->file->name); - $this->assertSame(1, $inference->file->pageCount); - $this->assertSame("image/jpeg", $inference->file->mimeType); + self::assertSame("default_sample.jpg", $inference->file->name); + self::assertSame(1, $inference->file->pageCount); + self::assertSame("image/jpeg", $inference->file->mimeType); $classification = $inference->result->classification; - $this->assertSame("invoice", $classification->documentType); + self::assertSame("invoice", $classification->documentType); } } diff --git a/tests/V2/Product/CropFunctional.php b/tests/V2/Product/CropFunctional.php index d509cb37..e14e484f 100644 --- a/tests/V2/Product/CropFunctional.php +++ b/tests/V2/Product/CropFunctional.php @@ -1,9 +1,11 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->cropModelId = getenv('MINDEE_V2_CROP_MODEL_ID') ?: ''; $this->cropExtractionModelId = getenv('MINDEE_V2_SE_TESTS_CROP_EXTRACTION_MODEL_ID') ?: ''; @@ -29,7 +31,6 @@ protected function setUp(): void /** * Tests the success of the crop process using a default sample file. * - * @return void */ public function testCropDefaultSampleMustSucceed(): void { @@ -40,30 +41,29 @@ public function testCropDefaultSampleMustSucceed(): void $productParams = new CropParameters($this->cropModelId); $response = $this->client->enqueueAndGetResult(CropResponse::class, $inputSource, $productParams); - $this->assertNotNull($response); - $this->assertNotNull($response->inference); + self::assertNotNull($response); + self::assertNotNull($response->inference); $file = $response->inference->file; - $this->assertNotNull($file); - $this->assertSame("default_sample.jpg", $file->name); + self::assertNotNull($file); + self::assertSame("default_sample.jpg", $file->name); $result = $response->inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); $crops = $result->crops; - $this->assertNotNull($crops); - $this->assertCount(2, $crops); + self::assertNotNull($crops); + self::assertCount(2, $crops); foreach ($crops as $crop) { - $this->assertNotNull($crop->objectType); - $this->assertNotNull($crop->location); + self::assertNotNull($crop->objectType); + self::assertNotNull($crop->location); } } /** * Tests the success of the crop and extraction process. * - * @return void */ public function testCropAndExtractionMustSucceed(): void { @@ -82,32 +82,32 @@ public function testCropAndExtractionMustSucceed(): void $productParams ); - $this->assertNotNull($response); + self::assertNotNull($response); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); $file = $inference->file; - $this->assertNotNull($file); - $this->assertSame("default_sample.jpg", $file->name); - $this->assertSame(1, $file->pageCount); + self::assertNotNull($file); + self::assertSame("default_sample.jpg", $file->name); + self::assertSame(1, $file->pageCount); - $this->assertNotNull($inference->model); - $this->assertSame($this->cropExtractionModelId, $inference->model->id); + self::assertNotNull($inference->model); + self::assertSame($this->cropExtractionModelId, $inference->model->id); $result = $inference->result; - $this->assertNotNull($result); - $this->assertCount(2, $result->crops); + self::assertNotNull($result); + self::assertCount(2, $result->crops); $crop0 = $result->crops[0]; - $this->assertSame("receipt", $crop0->objectType); - $this->assertNotNull($crop0->location->polygon); - $this->assertSame(0, $crop0->location->page); + self::assertSame("receipt", $crop0->objectType); + self::assertNotNull($crop0->location->polygon); + self::assertSame(0, $crop0->location->page); $extractionResponse0 = $crop0->extractionResponse; - $this->assertNotNull($extractionResponse0); + self::assertNotNull($extractionResponse0); $supplierName = $extractionResponse0->inference->result->fields ->getSimpleField("supplier_name")->value; - $this->assertSame("CHEZ ALAIN MIAM MIAM", $supplierName); + self::assertSame("CHEZ ALAIN MIAM MIAM", $supplierName); } } diff --git a/tests/V2/Product/CropTest.php b/tests/V2/Product/CropTest.php index eee10c35..c750abad 100644 --- a/tests/V2/Product/CropTest.php +++ b/tests/V2/Product/CropTest.php @@ -1,5 +1,6 @@ assertNotNull($response->inference); - $this->assertNotNull($response->inference->id); - $this->assertNotNull($response->inference->file); - $this->assertNotNull($response->inference->result); + self::assertNotNull($response->inference); + self::assertNotNull($response->inference->id); + self::assertNotNull($response->inference->file); + self::assertNotNull($response->inference->result); } /** * Ensures all line endings are identical before comparison so the test * behaves the same on every platform (LF vs CRLF). * @param string $input Input string to normalize. - * @return string */ private static function normalizeLineEndings(string $input): string { @@ -56,7 +53,6 @@ private static function normalizeLineEndings(string $input): string /** * Should correctly map properties when reading a single crop JSON. - * @return void */ public function testCropWhenSingleMustHaveValidProperties(): void { @@ -67,35 +63,33 @@ public function testCropWhenSingleMustHaveValidProperties(): void $inference = $response->inference; - $this->assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); - $this->assertSame("test-model-id", $inference->model->id); - $this->assertSame("12345678-1234-1234-1234-jobid1234567", $inference->job->id); + self::assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); + self::assertSame("test-model-id", $inference->model->id); + self::assertSame("12345678-1234-1234-1234-jobid1234567", $inference->job->id); - $this->assertSame("sample.jpeg", $inference->file->name); - $this->assertSame(1, $inference->file->pageCount); - $this->assertSame("image/jpeg", $inference->file->mimeType); + self::assertSame("sample.jpeg", $inference->file->name); + self::assertSame(1, $inference->file->pageCount); + self::assertSame("image/jpeg", $inference->file->mimeType); $crops = $inference->result->crops; - $this->assertNotNull($crops); - $this->assertCount(2, $crops); + self::assertNotNull($crops); + self::assertCount(2, $crops); $firstCrop = $crops[0]; - $this->assertSame("receipt", $firstCrop->objectType); - $this->assertSame(0, $firstCrop->location->page); + self::assertSame("receipt", $firstCrop->objectType); + self::assertSame(0, $firstCrop->location->page); $polygon = $firstCrop->location->polygon; - $this->assertCount(4, $polygon->getCoordinates()); + self::assertCount(4, $polygon->getCoordinates()); - // Note: Using assertEquals here instead of assertSame to allow for object value comparison - $this->assertEquals(new Point(0.214, 0.036), $polygon->getCoordinates()[0]); - $this->assertEquals(new Point(0.476, 0.036), $polygon->getCoordinates()[1]); - $this->assertEquals(new Point(0.476, 0.949), $polygon->getCoordinates()[2]); - $this->assertEquals(new Point(0.214, 0.949), $polygon->getCoordinates()[3]); + self::assertEquals(new Point(0.214, 0.036), $polygon->getCoordinates()[0]); + self::assertEquals(new Point(0.476, 0.036), $polygon->getCoordinates()[1]); + self::assertEquals(new Point(0.476, 0.949), $polygon->getCoordinates()[2]); + self::assertEquals(new Point(0.214, 0.949), $polygon->getCoordinates()[3]); } /** * Should correctly map properties when reading a multiple crop JSON. - * @return void */ public function testCropWhenMultipleMustHaveValidProperties(): void { @@ -107,45 +101,44 @@ public function testCropWhenMultipleMustHaveValidProperties(): void $inference = $response->inference; $job = $inference->job; - $this->assertSame("12345678-1234-1234-1234-jobid1234567", $job->id); + self::assertSame("12345678-1234-1234-1234-jobid1234567", $job->id); - $this->assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); - $this->assertSame("test-model-id", $inference->model->id); + self::assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); + self::assertSame("test-model-id", $inference->model->id); - $this->assertSame("default_sample.jpg", $inference->file->name); - $this->assertSame(1, $inference->file->pageCount); - $this->assertSame("image/jpeg", $inference->file->mimeType); + self::assertSame("default_sample.jpg", $inference->file->name); + self::assertSame(1, $inference->file->pageCount); + self::assertSame("image/jpeg", $inference->file->mimeType); $crops = $inference->result->crops; - $this->assertNotNull($crops); - $this->assertCount(2, $crops); + self::assertNotNull($crops); + self::assertCount(2, $crops); $firstCrop = $crops[0]; - $this->assertSame("invoice", $firstCrop->objectType); - $this->assertSame(0, $firstCrop->location->page); + self::assertSame("invoice", $firstCrop->objectType); + self::assertSame(0, $firstCrop->location->page); $firstPolygon = $firstCrop->location->polygon; - $this->assertCount(4, $firstPolygon->getCoordinates()); - $this->assertEquals(new Point(0.214, 0.079), $firstPolygon->getCoordinates()[0]); - $this->assertEquals(new Point(0.476, 0.079), $firstPolygon->getCoordinates()[1]); - $this->assertEquals(new Point(0.476, 0.979), $firstPolygon->getCoordinates()[2]); - $this->assertEquals(new Point(0.214, 0.979), $firstPolygon->getCoordinates()[3]); + self::assertCount(4, $firstPolygon->getCoordinates()); + self::assertEquals(new Point(0.214, 0.079), $firstPolygon->getCoordinates()[0]); + self::assertEquals(new Point(0.476, 0.079), $firstPolygon->getCoordinates()[1]); + self::assertEquals(new Point(0.476, 0.979), $firstPolygon->getCoordinates()[2]); + self::assertEquals(new Point(0.214, 0.979), $firstPolygon->getCoordinates()[3]); $secondCrop = $crops[1]; - $this->assertSame("receipt", $secondCrop->objectType); - $this->assertSame(0, $secondCrop->location->page); + self::assertSame("receipt", $secondCrop->objectType); + self::assertSame(0, $secondCrop->location->page); $secondPolygon = $secondCrop->location->polygon; - $this->assertCount(4, $secondPolygon->getCoordinates()); - $this->assertEquals(new Point(0.547, 0.15), $secondPolygon->getCoordinates()[0]); - $this->assertEquals(new Point(0.862, 0.15), $secondPolygon->getCoordinates()[1]); - $this->assertEquals(new Point(0.862, 0.97), $secondPolygon->getCoordinates()[2]); - $this->assertEquals(new Point(0.547, 0.97), $secondPolygon->getCoordinates()[3]); + self::assertCount(4, $secondPolygon->getCoordinates()); + self::assertEquals(new Point(0.547, 0.15), $secondPolygon->getCoordinates()[0]); + self::assertEquals(new Point(0.862, 0.15), $secondPolygon->getCoordinates()[1]); + self::assertEquals(new Point(0.862, 0.97), $secondPolygon->getCoordinates()[2]); + self::assertEquals(new Point(0.547, 0.97), $secondPolygon->getCoordinates()[3]); } /** * crop_single.rst – RST display must be parsed and exposed - * @return void */ public function testRstDisplayMustBeAccessible(): void { @@ -156,13 +149,11 @@ public function testRstDisplayMustBeAccessible(): void $rstReference = file_get_contents($rstReferencePath); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); - // Assumes your Inference class implements the __toString() magic method - // which maps to C#'s ToString() - $this->assertEquals( + self::assertSame( self::normalizeLineEndings($rstReference), - self::normalizeLineEndings((string)$inference) + self::normalizeLineEndings((string) $inference) ); } } diff --git a/tests/V2/Product/OcrFunctional.php b/tests/V2/Product/OcrFunctional.php index 70d1eb1d..ed870e60 100644 --- a/tests/V2/Product/OcrFunctional.php +++ b/tests/V2/Product/OcrFunctional.php @@ -1,9 +1,11 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->ocrModelId = getenv('MINDEE_V2_OCR_MODEL_ID') ?: ''; } /** - * Tests the success of the OCR process using a default sample file. + * Tests the success of the Ocr process using a default sample file. * - * @return void */ public function testOcrDefaultSampleMustSucceed(): void { @@ -38,18 +39,18 @@ public function testOcrDefaultSampleMustSucceed(): void $productParams = new OcrParameters($this->ocrModelId); $response = $this->client->enqueueAndGetResult(OcrResponse::class, $inputSource, $productParams); - $this->assertNotNull($response); - $this->assertNotNull($response->inference); + self::assertNotNull($response); + self::assertNotNull($response->inference); $file = $response->inference->file; - $this->assertNotNull($file); - $this->assertSame("default_sample.jpg", $file->name); + self::assertNotNull($file); + self::assertSame("default_sample.jpg", $file->name); $result = $response->inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); $pages = $result->pages; - $this->assertNotNull($pages); - $this->assertCount(1, $pages); + self::assertNotNull($pages); + self::assertCount(1, $pages); } } diff --git a/tests/V2/Product/OcrTest.php b/tests/V2/Product/OcrTest.php index 01d027b5..66d9a667 100644 --- a/tests/V2/Product/OcrTest.php +++ b/tests/V2/Product/OcrTest.php @@ -1,5 +1,7 @@ assertNotNull($response->inference); - $this->assertNotNull($response->inference->id); - $this->assertNotNull($response->inference->file); - $this->assertNotNull($response->inference->result); + self::assertNotNull($response->inference); + self::assertNotNull($response->inference->id); + self::assertNotNull($response->inference->file); + self::assertNotNull($response->inference->result); } /** - * Should correctly map properties when reading a single OCR JSON. - * @return void + * Should correctly map properties when reading a single Ocr JSON. */ public function testOcrWhenSingleMustHaveValidProperties(): void { @@ -52,33 +52,31 @@ public function testOcrWhenSingleMustHaveValidProperties(): void $inference = $response->inference; - $this->assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); - $this->assertSame("test-model-id", $inference->model->id); + self::assertSame("12345678-1234-1234-1234-123456789abc", $inference->id); + self::assertSame("test-model-id", $inference->model->id); - $this->assertSame("default_sample.jpg", $inference->file->name); - $this->assertSame(1, $inference->file->pageCount); - $this->assertSame("image/jpeg", $inference->file->mimeType); + self::assertSame("default_sample.jpg", $inference->file->name); + self::assertSame(1, $inference->file->pageCount); + self::assertSame("image/jpeg", $inference->file->mimeType); $pages = $inference->result->pages; - $this->assertNotNull($pages); - $this->assertCount(1, $pages); + self::assertNotNull($pages); + self::assertCount(1, $pages); $firstPage = $pages[0]; - $this->assertNotNull($firstPage->words); + self::assertNotNull($firstPage->words); $firstWord = $firstPage->words[0]; - $this->assertSame("Shipper:", $firstWord->content); - // Using the getCoordinates() logic from the corrected file - $this->assertCount(4, $firstWord->polygon->getCoordinates()); + self::assertSame("Shipper:", $firstWord->content); + self::assertCount(4, $firstWord->polygon->getCoordinates()); $fifthWord = $firstPage->words[4]; - $this->assertSame("INC.", $fifthWord->content); - $this->assertCount(4, $fifthWord->polygon->getCoordinates()); + self::assertSame("INC.", $fifthWord->content); + self::assertCount(4, $fifthWord->polygon->getCoordinates()); } /** - * Should correctly map properties when reading a multiple OCR JSON. - * @return void + * Should correctly map properties when reading a multiple Ocr JSON. */ public function testOcrWhenMultipleMustHaveValidProperties(): void { @@ -90,19 +88,19 @@ public function testOcrWhenMultipleMustHaveValidProperties(): void $inference = $response->inference; $job = $inference->job; - $this->assertSame("12345678-1234-1234-1234-jobid1234567", $job->id); + self::assertSame("12345678-1234-1234-1234-jobid1234567", $job->id); $model = $inference->model; - $this->assertNotNull($model); + self::assertNotNull($model); $pages = $inference->result->pages; - $this->assertNotNull($pages); - $this->assertCount(3, $pages); + self::assertNotNull($pages); + self::assertCount(3, $pages); foreach ($pages as $page) { - $this->assertNotNull($page->words); - $this->assertNotNull($page->content); - $this->assertIsString($page->content); + self::assertNotNull($page->words); + self::assertNotNull($page->content); + self::assertIsString($page->content); } } } diff --git a/tests/V2/Product/SplitFunctional.php b/tests/V2/Product/SplitFunctional.php index 92d2cbc8..24cfc73d 100644 --- a/tests/V2/Product/SplitFunctional.php +++ b/tests/V2/Product/SplitFunctional.php @@ -1,9 +1,11 @@ client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->splitModelId = getenv('MINDEE_V2_SPLIT_MODEL_ID') ?: ''; } @@ -27,7 +29,6 @@ protected function setUp(): void /** * Tests the success of the split process using a default sample file. * - * @return void */ public function testSplitDefaultSampleMustSucceed(): void { @@ -38,18 +39,18 @@ public function testSplitDefaultSampleMustSucceed(): void $productParams = new SplitParameters($this->splitModelId); $response = $this->client->enqueueAndGetResult(SplitResponse::class, $inputSource, $productParams); - $this->assertNotNull($response); - $this->assertNotNull($response->inference); + self::assertNotNull($response); + self::assertNotNull($response->inference); $file = $response->inference->file; - $this->assertNotNull($file); - $this->assertSame("default_sample.pdf", $file->name); + self::assertNotNull($file); + self::assertSame("default_sample.pdf", $file->name); $result = $response->inference->result; - $this->assertNotNull($result); + self::assertNotNull($result); $splits = $result->splits; - $this->assertNotNull($splits); - $this->assertCount(2, $splits); + self::assertNotNull($splits); + self::assertCount(2, $splits); } } diff --git a/tests/V2/Product/SplitTest.php b/tests/V2/Product/SplitTest.php index b4925cb0..2cfc67fa 100644 --- a/tests/V2/Product/SplitTest.php +++ b/tests/V2/Product/SplitTest.php @@ -1,5 +1,7 @@ assertNotNull($response->inference); - $this->assertNotNull($response->inference->id); - $this->assertNotNull($response->inference->file); - $this->assertNotNull($response->inference->result); + self::assertNotNull($response->inference); + self::assertNotNull($response->inference->id); + self::assertNotNull($response->inference->file); + self::assertNotNull($response->inference->result); } /** * Should correctly map properties when reading a single split JSON. - * @return void */ public function testSplitWhenSingleMustHaveValidProperties(): void { @@ -53,24 +53,23 @@ public function testSplitWhenSingleMustHaveValidProperties(): void $inference = $response->inference; $model = $inference->model; - $this->assertNotNull($model); + self::assertNotNull($model); $splits = $inference->result->splits; - $this->assertNotNull($splits); - $this->assertCount(1, $splits); + self::assertNotNull($splits); + self::assertCount(1, $splits); $firstSplit = $splits[0]; - $this->assertSame("receipt", $firstSplit->documentType); + self::assertSame("receipt", $firstSplit->documentType); - $this->assertNotNull($firstSplit->pageRange); - $this->assertCount(2, $firstSplit->pageRange); - $this->assertSame(0, $firstSplit->pageRange[0]); - $this->assertSame(0, $firstSplit->pageRange[1]); + self::assertNotNull($firstSplit->pageRange); + self::assertCount(2, $firstSplit->pageRange); + self::assertSame(0, $firstSplit->pageRange[0]); + self::assertSame(0, $firstSplit->pageRange[1]); } /** * Should correctly map properties when reading a multiple split JSON. - * @return void */ public function testSplitWhenMultipleMustHaveValidProperties(): void { @@ -82,26 +81,26 @@ public function testSplitWhenMultipleMustHaveValidProperties(): void $inference = $response->inference; $model = $inference->model; - $this->assertNotNull($model); + self::assertNotNull($model); $splits = $inference->result->splits; - $this->assertNotNull($splits); - $this->assertCount(3, $splits); + self::assertNotNull($splits); + self::assertCount(3, $splits); $firstSplit = $splits[0]; - $this->assertSame("passport", $firstSplit->documentType); + self::assertSame("passport", $firstSplit->documentType); - $this->assertNotNull($firstSplit->pageRange); - $this->assertCount(2, $firstSplit->pageRange); - $this->assertSame(0, $firstSplit->pageRange[0]); - $this->assertSame(0, $firstSplit->pageRange[1]); + self::assertNotNull($firstSplit->pageRange); + self::assertCount(2, $firstSplit->pageRange); + self::assertSame(0, $firstSplit->pageRange[0]); + self::assertSame(0, $firstSplit->pageRange[1]); $secondSplit = $splits[1]; - $this->assertSame("invoice", $secondSplit->documentType); + self::assertSame("invoice", $secondSplit->documentType); - $this->assertNotNull($secondSplit->pageRange); - $this->assertCount(2, $secondSplit->pageRange); - $this->assertSame(1, $secondSplit->pageRange[0]); - $this->assertSame(3, $secondSplit->pageRange[1]); + self::assertNotNull($secondSplit->pageRange); + self::assertCount(2, $secondSplit->pageRange); + self::assertSame(1, $secondSplit->pageRange[0]); + self::assertSame(3, $secondSplit->pageRange[1]); } } diff --git a/tests/resources b/tests/resources index 315efcc3..13093f3a 160000 --- a/tests/resources +++ b/tests/resources @@ -1 +1 @@ -Subproject commit 315efcc302efacfb75a6b101788058658e8c37e4 +Subproject commit 13093f3a48de212ef26889df71199c1a2a9d1478 diff --git a/whisky.json b/whisky.json new file mode 100644 index 00000000..a601d98e --- /dev/null +++ b/whisky.json @@ -0,0 +1,11 @@ +{ + "disabled": [], + "hooks": { + "pre-commit": [ + "composer lint" + ], + "pre-push": [ + "composer test:unit" + ] + } +}