diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 5a72d400..8aaf8407 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -31,14 +31,7 @@ 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..5bea3c95 100644 --- a/bin/DocumentCommandConfig.php +++ b/bin/DocumentCommandConfig.php @@ -1,5 +1,7 @@ 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. */ @@ -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. */ @@ -352,9 +356,9 @@ 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. + * @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. */ private function getFileSource(string $filePathOrUrl, Client $client, OutputInterface $output) @@ -411,7 +415,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 +431,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 +445,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 +470,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( @@ -492,7 +496,7 @@ private function executePrediction( } catch (MindeeHttpException $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 +507,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, @@ -533,10 +537,10 @@ 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( diff --git a/bin/MindeeCLIDocuments.php b/bin/MindeeCLIDocuments.php index 83411e52..d2041c43 100644 --- a/bin/MindeeCLIDocuments.php +++ b/bin/MindeeCLIDocuments.php @@ -1,7 +1,36 @@ new DocumentCommandConfig( "Custom document type from docTI", - \Mindee\Product\Generated\GeneratedV1::class, + GeneratedV1::class, false, true ), "barcode-reader" => new DocumentCommandConfig( "Barcode Reader", - \Mindee\Product\BarcodeReader\BarcodeReaderV1::class, + BarcodeReaderV1::class, true, false ), "bill-of-lading" => new DocumentCommandConfig( "Bill of Lading", - \Mindee\Product\BillOfLading\BillOfLadingV1::class, + BillOfLadingV1::class, false, true ), "business-card" => new DocumentCommandConfig( "Business Card", - \Mindee\Product\BusinessCard\BusinessCardV1::class, + BusinessCardV1::class, false, true ), "cropper" => new DocumentCommandConfig( "Cropper", - \Mindee\Product\Cropper\CropperV1::class, + CropperV1::class, true, false ), "delivery-note" => new DocumentCommandConfig( "Delivery note", - \Mindee\Product\DeliveryNote\DeliveryNoteV1::class, + DeliveryNoteV1::class, false, true ), "driver-license" => new DocumentCommandConfig( "Driver License", - \Mindee\Product\DriverLicense\DriverLicenseV1::class, + DriverLicenseV1::class, false, true ), "financial-document" => new DocumentCommandConfig( "Financial Document", - \Mindee\Product\FinancialDocument\FinancialDocumentV1::class, + FinancialDocumentV1::class, true, true ), "fr-bank-account-details" => new DocumentCommandConfig( "FR Bank Account Details", - \Mindee\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, + BankAccountDetailsV2::class, true, false ), "fr-carte-grise" => new DocumentCommandConfig( "FR Carte Grise", - \Mindee\Product\Fr\CarteGrise\CarteGriseV1::class, + CarteGriseV1::class, true, false ), "fr-energy-bill" => new DocumentCommandConfig( "FR Energy Bill", - \Mindee\Product\Fr\EnergyBill\EnergyBillV1::class, + EnergyBillV1::class, false, true ), "fr-health-card" => new DocumentCommandConfig( "FR Health Card", - \Mindee\Product\Fr\HealthCard\HealthCardV1::class, + HealthCardV1::class, false, true ), "fr-carte-nationale-d-identite" => new DocumentCommandConfig( "FR Carte Nationale d'Identité", - \Mindee\Product\Fr\IdCard\IdCardV2::class, + IdCardV2::class, true, false ), "fr-payslip" => new DocumentCommandConfig( "FR Payslip", - \Mindee\Product\Fr\Payslip\PayslipV3::class, + PayslipV3::class, false, true ), "ind-passport-india" => new DocumentCommandConfig( "IND Passport - India", - \Mindee\Product\Ind\IndianPassport\IndianPassportV1::class, + IndianPassportV1::class, false, true ), "international-id" => new DocumentCommandConfig( "International ID", - \Mindee\Product\InternationalId\InternationalIdV2::class, + InternationalIdV2::class, false, true ), "invoice" => new DocumentCommandConfig( "Invoice", - \Mindee\Product\Invoice\InvoiceV4::class, + InvoiceV4::class, true, true ), "invoice-splitter" => new DocumentCommandConfig( "Invoice Splitter", - \Mindee\Product\InvoiceSplitter\InvoiceSplitterV1::class, + InvoiceSplitterV1::class, false, true ), "multi-receipts-detector" => new DocumentCommandConfig( "Multi Receipts Detector", - \Mindee\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, + MultiReceiptsDetectorV1::class, true, false ), "nutrition-facts-label" => new DocumentCommandConfig( "Nutrition Facts Label", - \Mindee\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, + NutritionFactsLabelV1::class, false, true ), "passport" => new DocumentCommandConfig( "Passport", - \Mindee\Product\Passport\PassportV1::class, + PassportV1::class, true, false ), "receipt" => new DocumentCommandConfig( "Receipt", - \Mindee\Product\Receipt\ReceiptV5::class, + ReceiptV5::class, true, true ), "resume" => new DocumentCommandConfig( "Resume", - \Mindee\Product\Resume\ResumeV1::class, + ResumeV1::class, false, true ), "us-bank-check" => new DocumentCommandConfig( "US Bank Check", - \Mindee\Product\Us\BankCheck\BankCheckV1::class, + BankCheckV1::class, true, false ), "us-healthcare-card" => new DocumentCommandConfig( "US Healthcare Card", - \Mindee\Product\Us\HealthcareCard\HealthcareCardV1::class, + HealthcareCardV1::class, false, true ), "us-us-mail" => new DocumentCommandConfig( "US US Mail", - \Mindee\Product\Us\UsMail\UsMailV3::class, + UsMailV3::class, false, true ), diff --git a/bin/cli.php b/bin/cli.php index 976cc293..29c185f9 100755 --- a/bin/cli.php +++ b/bin/cli.php @@ -1,14 +1,15 @@ 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..a8315df5 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,6 @@ }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.38", - "squizlabs/php_codesniffer": "^3.7", "phpunit/phpunit": "^9.6", "madewithlove/license-checker": "^v1.0" }, @@ -31,5 +30,9 @@ "bin": [ "mindee", "bin/cli.php" - ] + ], + "scripts": { + "lint": "php-cs-fixer fix --dry-run --diff", + "format": "php-cs-fixer fix" + } } diff --git a/docs/code_samples/bank_account_details_v1.txt b/docs/code_samples/bank_account_details_v1.txt index dfd63f64..af944d38 100644 --- a/docs/code_samples/bank_account_details_v1.txt +++ b/docs/code_samples/bank_account_details_v1.txt @@ -1,7 +1,7 @@ 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..63fe599e 100644 --- a/docs/code_samples/v2_extraction_webhook.txt +++ b/docs/code_samples/v2_extraction_webhook.txt @@ -1,7 +1,7 @@ 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/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" + TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg" ); - } catch (\Exception $e) { + } catch (Exception $e) { 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 @@ 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"); } @@ -113,9 +119,9 @@ 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']; } @@ -132,20 +138,19 @@ public static function createErrorObj($response): array } /** - * @param string $url Remote URL the error was found on. + * @param string $url Remote URL the error was found on. * @param array|string|boolean $response Raw server response. - * @return MindeeHttpException */ - public static function handleError(string $url, $response): MindeeHttpException + public static function handleError(string $url, $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; } @@ -156,6 +161,6 @@ public static function handleError(string $url, $response): MindeeHttpException return new MindeeHttpClientException($errorObj, $url, $code); } - return new MindeeHttpException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } } diff --git a/src/Error/MindeeHttpServerException.php b/src/Error/MindeeHttpServerException.php index 085526d2..71b17d18 100644 --- a/src/Error/MindeeHttpServerException.php +++ b/src/Error/MindeeHttpServerException.php @@ -1,5 +1,7 @@ -1, "detail" => "Couldn't deserialize server error. Found: $response", "title" => "Unknown error", - "code" => "000-000" + "code" => "000-000", ] ) ); diff --git a/src/Extraction/ExtractedImage.php b/src/Extraction/ExtractedImage.php index 51039fec..1725f366 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Extraction/ExtractedImage.php @@ -1,10 +1,18 @@ image->setOption('png:compression-level', $finalQuality); - } elseif (in_array($format, ['jpg', 'jpeg'])) { - $this->image->setImageCompression(\Imagick::COMPRESSION_JPEG); + } elseif (in_array($format, ['jpg', 'jpeg'], true)) { + $this->image->setImageCompression(Imagick::COMPRESSION_JPEG); } $this->image->setImageCompressionQuality($quality); $this->image->writeImage($imagePath); @@ -91,7 +98,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/Extraction/ExtractedPdf.php b/src/Extraction/ExtractedPDF.php similarity index 94% rename from src/Extraction/ExtractedPdf.php rename to src/Extraction/ExtractedPDF.php index 860d642c..d2874e85 100644 --- a/src/Extraction/ExtractedPdf.php +++ b/src/Extraction/ExtractedPDF.php @@ -1,19 +1,23 @@ pdfBytes; } diff --git a/src/Extraction/ImageExtractor.php b/src/Extraction/ImageExtractor.php index 16bc580a..498c1df7 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Extraction/ImageExtractor.php @@ -1,7 +1,10 @@ pageImages = $this->pdfToImages($this->inputSource->readContents()[1]); } else { try { - $image = new \Imagick(); + $image = new Imagick(); $image->readImageBlob($this->inputSource->readContents()[1]); - } catch (\ImagickException $e) { + } catch (ImagickException $e) { throw new MindeePDFException( "Image couldn't be processed.", ErrorCode::IMAGE_CANT_PROCESS, @@ -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, @@ -122,8 +129,8 @@ public function getPageCount(): int /** * Extract multiple images on a given page from a list of fields having position data. * - * @param array $fields List of Fields to extract. - * @param integer $pageIndex The page index to extract, begins at 0. + * @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 @@ -137,10 +144,10 @@ public function extractImagesFromPage(array $fields, int $pageIndex, ?string $ou /** * 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 * @throws MindeeImageException Throws if the image can't be processed. @@ -166,7 +173,7 @@ public function extractPolygonsFromPage( $saveFormat ); } - } catch (\ImagickException $e) { + } catch (ImagickException $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } @@ -176,11 +183,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,7 +202,7 @@ 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; @@ -207,11 +214,11 @@ public function extractPolygonFromPage( /** * 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. + * @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. * @@ -248,7 +255,6 @@ public function extractImage( /** * Getter for the local input source. - * @return LocalInputSource */ public function getInputSource(): LocalInputSource { @@ -258,10 +264,10 @@ public function getInputSource(): LocalInputSource /** * 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. + * @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 */ @@ -286,12 +292,11 @@ protected function extractFromPage(array $fields, int $pageIndex, string $output /** * 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 +307,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; } diff --git a/src/Extraction/PdfExtractor.php b/src/Extraction/PDFExtractor.php similarity index 82% rename from src/Extraction/PdfExtractor.php rename to src/Extraction/PDFExtractor.php index 36bac699..a11f7fb1 100644 --- a/src/Extraction/PdfExtractor.php +++ b/src/Extraction/PDFExtractor.php @@ -1,21 +1,30 @@ pdfBytes = $localInput->readContents()[1]; } else { try { - $image = new \Imagick(); - } catch (\ImagickException $e) { + $image = new Imagick(); + } catch (ImagickException $e) { throw new MindeePDFException("Imagick could not process this file.\n", 0, $e); } $image->readImageBlob($localInput->readContents()[1]); @@ -79,10 +88,10 @@ public function getPageCount(): int * * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * - * @return ExtractedPdf[] list of extracted documents + * @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 { @@ -90,7 +99,7 @@ public function extractSubDocuments(mixed $pageIndexes): array 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,14 +125,14 @@ 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); } - $extractedPdfs[] = new ExtractedPdf($mergedPdfBytes, $fieldFilename); + $extractedPdfs[] = new ExtractedPDF($mergedPdfBytes, $fieldFilename); } return $extractedPdfs; @@ -133,9 +142,9 @@ 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 boolean $strict Whether to trust confidence scores or not. * - * @return ExtractedPdf[] a list of extracted invoices + * @return ExtractedPDF[] a list of extracted invoices */ public function extractInvoices(mixed $pageIndexes, bool $strict = false): array { @@ -143,7 +152,7 @@ public function extractInvoices(mixed $pageIndexes, bool $strict = false): array return []; } if (!$strict) { - $indexes = array_map(fn ($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); + $indexes = array_map(static fn($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); return $this->extractSubDocuments($indexes); } diff --git a/src/Geometry/BBox.php b/src/Geometry/BBox.php index af9e311d..e6ebac3c 100644 --- a/src/Geometry/BBox.php +++ b/src/Geometry/BBox.php @@ -1,5 +1,7 @@ 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..3e04e6ae 100644 --- a/src/Geometry/MinMax.php +++ b/src/Geometry/MinMax.php @@ -1,5 +1,7 @@ x); + $this->x = null; } elseif ($offset === 1) { - unset($this->y); + $this->y = null; } else { throw new InvalidArgumentException("Use 0 for X or 1 for Y"); } diff --git a/src/Geometry/Polygon.php b/src/Geometry/Polygon.php index 339086d0..b458eec0 100644 --- a/src/Geometry/Polygon.php +++ b/src/Geometry/Polygon.php @@ -1,7 +1,11 @@ coordinates = []; foreach ($coordinates as $point) { $this->coordinates[] = new Point($point[0], $point[1]); @@ -40,7 +44,6 @@ public function __construct(?array $coordinates = null) /** * Retrieves the centroid of the polygon. * - * @return Point */ public function getCentroid(): Point { @@ -50,7 +53,6 @@ public function getCentroid(): Point /** * Retrieves the upper and lower bounds of the y-axis. * - * @return MinMax */ public function getMinMaxY(): MinMax { @@ -63,7 +65,6 @@ public function getMinMaxY(): MinMax /** * Retrieves the upper and lower bounds of the x-axis. * - * @return MinMax */ public function getMinMaxX(): MinMax { @@ -100,7 +101,6 @@ public function isPointInX(Point $point): bool /** * Retrieves the minimum X coordinate. * - * @return float */ public function getMinX(): float { @@ -110,7 +110,6 @@ public function getMinX(): float /** * Retrieves the maximum X coordinate. * - * @return float */ public function getMaxX(): float { @@ -120,7 +119,6 @@ public function getMaxX(): float /** * Retrieves the minimum Y coordinate. * - * @return float */ public function getMinY(): float { @@ -130,7 +128,6 @@ public function getMinY(): float /** * Retrieves the maximum Y coordinate. * - * @return float */ public function getMaxY(): float { @@ -144,13 +141,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 */ public function getCoordinates(): ?array { @@ -162,7 +158,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..02297b28 100644 --- a/src/Geometry/PolygonUtils.php +++ b/src/Geometry/PolygonUtils.php @@ -1,10 +1,14 @@ getX(); $ySum += $vertex->getY(); } @@ -42,7 +45,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) { return 0; } return $sort < 0 ? -1 : 1; @@ -51,9 +54,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 +80,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; } @@ -106,12 +107,11 @@ 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 * @throws MindeeGeometryException Throws if the polygon isn't a quadrilateral. */ public static function quadrilateralFromPrediction(array $prediction): Polygon { - if (count($prediction) != 4) { + if (count($prediction) !== 4) { throw new MindeeGeometryException('Prediction must have exactly 4 points.'); } return new Polygon($prediction); @@ -121,8 +121,8 @@ public static function quadrilateralFromPrediction(array $prediction): Polygon * 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 +134,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/Image/ImageCompressor.php b/src/Image/ImageCompressor.php index 0d339f2a..1051c268 100644 --- a/src/Image/ImageCompressor.php +++ b/src/Image/ImageCompressor.php @@ -1,11 +1,15 @@ 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 = new Imagick(); $imagickHandle->readImageBlob($image); } else { throw new MindeeImageException( @@ -43,7 +53,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 +65,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..e38a2c5f 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(); } @@ -32,7 +36,6 @@ public function __construct(string $strBase64, string $fileName) /** * Reads the contents of the file. * - * @return array */ public function readContents(): array { diff --git a/src/Input/BytesInput.php b/src/Input/BytesInput.php index c356384c..a5084b16 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(); } @@ -32,7 +36,6 @@ public function __construct(string $fileBytes, string $fileName) /** * Reads the contents of the file. * - * @return array */ public function readContents(): array { diff --git a/src/Input/FileInput.php b/src/Input/FileInput.php index 14c836d8..289f2aef 100644 --- a/src/Input/FileInput.php +++ b/src/Input/FileInput.php @@ -1,9 +1,12 @@ 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 */ public function readContents(): array { 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 ); } @@ -105,7 +111,7 @@ public function __construct() public function isPDF(): bool { $this->checkMimeType(); - return $this->fileMimetype == 'application/pdf'; + return $this->fileMimetype === 'application/pdf'; } /** @@ -123,7 +129,7 @@ public function getPageCount(): int ErrorCode::USER_OPERATION_ERROR ); } - $pdf = new FPDI(); + $pdf = new Fpdi(); try { return $pdf->setSourceFile($this->fileObject->getFilename()); } catch (PdfParserException $e) { @@ -146,7 +152,6 @@ public function countDocPages(): int /** * @param string $fileBytes Raw data as bytes. - * @return void */ private function saveBytesAsFile(string $fileBytes): void { @@ -159,13 +164,12 @@ 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. */ public function mergePDFPages(array $pageNumbers): void { try { - $pdf = new FPDI(); + $pdf = new Fpdi(); $pdf->setSourceFile($this->filePath); foreach ($pageNumbers as $pageNumber) { $pdf->AddPage(); @@ -173,7 +177,7 @@ public function mergePDFPages(array $pageNumbers): void } $this->saveBytesAsFile($pdf->Output($this->fileName, 'S')); $pdf->Close(); - } catch (PdfParserException | PdfReaderException $e) { + } catch (PdfParserException|PdfReaderException $e) { throw new MindeePDFException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, @@ -192,11 +196,11 @@ public function mergePDFPages(array $pageNumbers): void 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)); @@ -206,7 +210,7 @@ public function isPDFEmpty(int $threshold = 1024): bool } $pdfPage->Close(); } - } catch (PdfParserException | PdfReaderException $e) { + } catch (PdfParserException|PdfReaderException $e) { throw new MindeePDFException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, @@ -219,11 +223,10 @@ public function isPDFEmpty(int $threshold = 1024): bool /** * Reads the contents of the file. * - * @return array */ 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,7 +235,6 @@ 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 @@ -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, @@ -324,7 +325,6 @@ 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. */ public function applyPageOptions(?PageOptions $pageOptions): void @@ -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; diff --git a/src/Input/LocalResponse.php b/src/Input/LocalResponse.php index 9a16086d..62805ef3 100644 --- a/src/Input/LocalResponse.php +++ b/src/Input/LocalResponse.php @@ -1,11 +1,17 @@ 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/URLInputSource.php b/src/Input/URLInputSource.php index 7c56fcf7..30f9c3c7 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,7 +67,6 @@ 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 { @@ -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/PDF/CustomFPDI.php b/src/PDF/CustomFPDI.php index 2b800f5f..de9ffc07 100644 --- a/src/PDF/CustomFPDI.php +++ b/src/PDF/CustomFPDI.php @@ -1,10 +1,14 @@ x; } - if ($y == -1) { + if ($y === -1) { $y = $this->y; } - if (intval($angle) != 0) { + if ((int) $angle !== 0) { $angle = -$angle; } $angle *= M_PI / 180; @@ -60,11 +63,10 @@ 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 //phpcs:ignore { - if ($this->angle != 0) { + if ($this->angle !== 0) { $this->angle = 0; $this->_out('Q'); } @@ -73,18 +75,16 @@ protected function _endpage() //phpcs:ignore /** * 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/PDF/PDFCompressor.php b/src/PDF/PDFCompressor.php index 5906f6a3..b244772a 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/PDF/PDFCompressor.php @@ -1,17 +1,24 @@ parseFile($pdfPath); - if (strlen($pdf->getText()) > 0) { + if ($pdf->getText() !== '') { if ($forceSourceTextCompression) { if (!$disableSourceText) { error_log("[WARNING] Re-writing PDF source-text is an EXPERIMENTAL feature."); @@ -65,10 +72,10 @@ public static function compress( 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); + } 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); @@ -76,8 +83,8 @@ public static function compress( $outPdf = new CustomFPDI(); for ($i = 1; $i <= $pageCount; $i++) { - list($tempJpegFile, $orientation) = static::processPdfPage($pdfPath, $i, $quality); - list($width, $height) = getimagesize($tempJpegFile); + [$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); @@ -92,12 +99,12 @@ public static function compress( $finalPDFSize = filesize($outputPath); if ($initialFileSize < $finalPDFSize) { - error_log("[WARNING] Compressed PDF for '$pdfPath' would be larger than input." . - " Aborting operation."); + 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) { + } catch (Exception $e) { throw new MindeePDFException( "Couldn't compress PDF.", ErrorCode::FILE_OPERATION_ABORTED, @@ -109,7 +116,6 @@ public static function compress( /** * @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 @@ -119,7 +125,7 @@ private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf foreach ($textElements as $element) { PDFUtils::addTextElement($outputPdf, $element); } - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeePDFException( "Couldn't inject text into the new file.", ErrorCode::PDF_CANT_EDIT, @@ -151,7 +157,7 @@ private static function createOutputPdf( $processedPdf->Output('F', $outputPath); return $outputPath; - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeePDFException( "Couldn't create output PDF.", ErrorCode::PDF_CANT_CREATE, @@ -166,7 +172,6 @@ private static function createOutputPdf( * * @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 @@ -188,7 +193,7 @@ private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): v } } } - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeePDFException( "Couldn't inject text into the new file.", ErrorCode::PDF_CANT_EDIT, @@ -207,10 +212,10 @@ private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): v * @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 + private static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array { try { - $singlePagePdf = new FPDI(); + $singlePagePdf = new Fpdi(); $singlePagePdf->setSourceFile($sourcePdfPath); $tplId = $singlePagePdf->importPage($pageIndex); $size = $singlePagePdf->getTemplateSize($tplId); @@ -221,11 +226,11 @@ private static function processPdfPage(string $sourcePdfPath, int $pageIndex, in $tempPdfFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.pdf'; $singlePagePdf->Output('F', $tempPdfFile); - $imagick = new \Imagick(); + $imagick = new Imagick(); $imagick->readImage($tempPdfFile); $imagick->setImageFormat('jpg'); - $imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE); - $imagick->setImageCompression(\Imagick::COMPRESSION_JPEG); + $imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); + $imagick->setImageCompression(Imagick::COMPRESSION_JPEG); $imagick->setImageCompressionQuality($imageQuality); $tempJpegFile = tempnam(sys_get_temp_dir(), 'pdf_page_') . '.jpg'; @@ -234,7 +239,7 @@ private static function processPdfPage(string $sourcePdfPath, int $pageIndex, in unlink($tempPdfFile); return [$tempJpegFile, $size['orientation']]; - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeePDFException( "Couldn't process PDF page $pageIndex.", ErrorCode::PDF_CANT_PROCESS, diff --git a/src/PDF/PDFUtils.php b/src/PDF/PDFUtils.php index 710cfccf..686a88fa 100644 --- a/src/PDF/PDFUtils.php +++ b/src/PDF/PDFUtils.php @@ -1,5 +1,7 @@ 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 = new Imagick(); $imagickHandle->readImageBlob($input); } else { throw new MindeePDFException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); @@ -64,7 +72,7 @@ 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() !== ''; } /** @@ -86,9 +94,7 @@ 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; } @@ -111,12 +117,12 @@ public static function extractPagesTextElements(string $pdfPath): array * @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. */ - public static function downgradePdfVersion(string $inputPath): string + 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); @@ -147,7 +153,7 @@ public static function extractTextElements(Page $page): array { try { $dataTm = $page->getDataTm(); - } catch (\Exception | \TypeError $e) { + } catch (Exception|TypeError $e) { return []; } try { @@ -156,11 +162,11 @@ 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]), ]; } } @@ -197,16 +203,15 @@ private static function standardizeFontName(string $fontName): array 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 { @@ -230,7 +235,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/Parsing/Common/SummaryHelper.php b/src/Parsing/SummaryHelper.php similarity index 66% rename from src/Parsing/Common/SummaryHelper.php rename to src/Parsing/SummaryHelper.php index 9165acfc..76b43d38 100644 --- a/src/Parsing/Common/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -1,9 +1,14 @@ 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/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/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/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/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/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/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/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/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/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/Client.php b/src/V1/Client.php similarity index 72% rename from src/Client.php rename to src/V1/Client.php index 05ea05e1..5452fad7 100644 --- a/src/Client.php +++ b/src/V1/Client.php @@ -1,24 +1,23 @@ 0 ? $endpointVersion : '1'; + $endpointVersion = $endpointVersion !== null && strlen($endpointVersion) > 0 ? $endpointVersion : '1'; - $endpointSettings = new MindeeApi($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); + $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); return new Endpoint($endpointName, $endpointOwner, $endpointVersion, $endpointSettings); } @@ -167,7 +166,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 +182,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 @@ -199,7 +196,7 @@ private function constructOTSEndpoint(string $product): Endpoint ErrorCode::INTERNAL_LIBRARY_ERROR ); } - 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 +210,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 + * @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 MindeeClientException 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) { + if (mb_strlen($endpointName, "UTF-8") === 0) { throw new MindeeClientException( "Custom endpoint requires a valid 'endpoint_name'.", ErrorCode::USER_INPUT_ERROR ); } $accountName = $this->cleanAccountName($accountName); - if (!$version || strlen($version) < 1) { + if (!$version || $version === '') { error_log("Notice: no version provided for a custom build, will attempt to poll version 1 by default."); $version = "1"; } @@ -238,11 +234,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,10 +245,9 @@ 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 + * @param string $predictionType Name of the product's class. + * @param string $queueId ID of the queue. + * @param Endpoint $endpoint Endpoint to poll. * @throws MindeeHttpException Throws if the API sent an error. */ private function makeParseQueuedRequest( @@ -274,10 +268,9 @@ 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 + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions $options Prediction Options. * @throws MindeeHttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ @@ -314,14 +307,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 + * @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 MindeeHttpException 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, @@ -329,7 +321,7 @@ private function makeWorkflowExecutionRequest( string $workflowId, PredictMethodOptions $options ): WorkflowResponse { - $workflowRouterSettings = new MindeeWorkflowApi($this->apiKey, $workflowId); + $workflowRouterSettings = new MindeeWorkflowAPI($this->apiKey, $workflowId); $options->endpoint = new WorkflowEndpoint($workflowRouterSettings); if (!$options->pageOptions->isEmpty()) { if ($inputDoc instanceof LocalInputSource) { @@ -364,10 +356,9 @@ 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 + * @param string $predictionType Name of the product's class. + * @param InputSource $inputDoc Input file. + * @param PredictMethodOptions $options Prediction Options. * @throws MindeeHttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ @@ -403,11 +394,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 +405,13 @@ public function parse( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): PredictResponse { - if ($options == null) { + if ($options === null) { $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 +421,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 +435,14 @@ public function enqueueAndParse( ?PollingOptions $asyncOptions = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options == null) { + if ($options === null) { $options = new PredictMethodOptions(); } - if ($asyncOptions == null) { + if ($asyncOptions === null) { $asyncOptions = new PollingOptions(); } - $options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint( + $options->endpoint ??= $this->constructOTSEndpoint( $predictionType, ); @@ -470,7 +459,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 +467,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 +479,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 +490,13 @@ public function enqueue( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options == null) { + if ($options === null) { $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 +505,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. */ @@ -560,11 +547,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 +558,10 @@ public function executeWorkflow( ?WorkflowOptions $options = null, ?PageOptions $pageOptions = null ): WorkflowResponse { - if ($options == null) { + if ($options === null) { $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/Input/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php similarity index 72% rename from src/Input/CommonOptions.php rename to src/V1/ClientOptions/CommonOptions.php index fca8df40..b4d6846b 100644 --- a/src/Input/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -1,6 +1,8 @@ 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/Input/PredictOptions.php b/src/V1/ClientOptions/PredictOptions.php similarity index 54% rename from src/Input/PredictOptions.php rename to src/V1/ClientOptions/PredictOptions.php index bc8daf0c..99ccb908 100644 --- a/src/Input/PredictOptions.php +++ b/src/V1/ClientOptions/PredictOptions.php @@ -1,6 +1,8 @@ includeWords = $includeWords; return $this; @@ -52,7 +54,7 @@ public function setIncludeWords(bool $includeWords): PredictOptions * @param boolean $cropper Whether to include the Cropper. * @return $this */ - public function setCropper(bool $cropper): PredictOptions + public function setCropper(bool $cropper): self { $this->cropper = $cropper; return $this; diff --git a/src/Input/WorkflowOptions.php b/src/V1/ClientOptions/WorkflowOptions.php similarity index 69% rename from src/Input/WorkflowOptions.php rename to src/V1/ClientOptions/WorkflowOptions.php index 658ce647..051ae962 100644 --- a/src/Input/WorkflowOptions.php +++ b/src/V1/ClientOptions/WorkflowOptions.php @@ -1,6 +1,8 @@ requestTimeout = $value; } @@ -98,16 +100,15 @@ protected function setTimeout(string $value) /** * Sets values from 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'], ]; 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 +120,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) { diff --git a/src/Http/BaseEndpoint.php b/src/V1/HTTP/BaseEndpoint.php similarity index 85% rename from src/Http/BaseEndpoint.php rename to src/V1/HTTP/BaseEndpoint.php index 06cdcaff..1c464083 100644 --- a/src/Http/BaseEndpoint.php +++ b/src/V1/HTTP/BaseEndpoint.php @@ -1,6 +1,8 @@ urlName = $urlName; @@ -47,7 +49,6 @@ public function __construct( * Retrieves a document from its queue ID. * * @param string $queueId ID of the queue to poll. - * @return array */ public function documentQueueReqGet(string $queueId): array { @@ -57,9 +58,8 @@ 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. */ public function predictRequestPost( InputSource $fileCurl, @@ -71,9 +71,8 @@ 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. */ public function predictAsyncRequestPost( InputSource $fileCurl, @@ -90,10 +89,9 @@ public function predictAsyncRequestPost( /** * 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. */ private function initCurlSessionPost( InputSource $inputSource, diff --git a/src/Http/MindeeApi.php b/src/V1/HTTP/MindeeAPI.php similarity index 69% rename from src/Http/MindeeApi.php rename to src/V1/HTTP/MindeeAPI.php index bf206b66..05ea91e2 100644 --- a/src/Http/MindeeApi.php +++ b/src/V1/HTTP/MindeeAPI.php @@ -1,19 +1,21 @@ apiKey || strlen($this->apiKey) == 0) { + if (!$this->apiKey || $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 ); } diff --git a/src/Http/MindeeWorkflowApi.php b/src/V1/HTTP/MindeeWorkflowAPI.php similarity index 71% rename from src/Http/MindeeWorkflowApi.php rename to src/V1/HTTP/MindeeWorkflowAPI.php index 0e0a6f2d..0603dd8e 100644 --- a/src/Http/MindeeWorkflowApi.php +++ b/src/V1/HTTP/MindeeWorkflowAPI.php @@ -1,10 +1,12 @@ apiKey || strlen($this->apiKey) == 0) { + if (!$this->apiKey || $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 ); } diff --git a/src/Http/ResponseValidation.php b/src/V1/HTTP/ResponseValidation.php similarity index 86% rename from src/Http/ResponseValidation.php rename to src/V1/HTTP/ResponseValidation.php index 74d3518d..9d1838e7 100644 --- a/src/Http/ResponseValidation.php +++ b/src/V1/HTTP/ResponseValidation.php @@ -1,10 +1,15 @@ 302 + is_nan($statusCode) + || (int) $statusCode < 200 + || (int) $statusCode > 302 ); } @@ -40,7 +45,7 @@ public static function isValidSyncResponse(array $response): bool */ public static function isValidWorkflowResponse(array $response): bool { - if (!ResponseValidation::isValidSyncResponse($response)) { + if (!self::isValidSyncResponse($response)) { return false; } if (isset($response["code"])) { @@ -65,7 +70,7 @@ public static function isValidWorkflowResponse(array $response): bool */ public static function isValidAsyncResponse(array $response): bool { - if (!ResponseValidation::isValidSyncResponse($response)) { + if (!self::isValidSyncResponse($response)) { return false; } if (isset($response["code"])) { @@ -85,7 +90,6 @@ 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 */ public static function cleanRequestData(array $response): array { @@ -97,10 +101,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 88% rename from src/Http/WorkflowEndpoint.php rename to src/V1/HTTP/WorkflowEndpoint.php index 219a70e1..71513783 100644 --- a/src/Http/WorkflowEndpoint.php +++ b/src/V1/HTTP/WorkflowEndpoint.php @@ -1,11 +1,13 @@ 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, @@ -58,7 +64,7 @@ public function __construct(string $predictionType, array $rawResponse) ); } if (array_key_exists('ocr', $rawResponse) && $rawResponse['ocr']) { - $this->ocr = new Ocr($rawResponse['ocr']); + $this->ocr = new OCR($rawResponse['ocr']); } if (array_key_exists("extras", $rawResponse['inference']) && $rawResponse['inference']['extras']) { $this->extras = new Extras($rawResponse['inference']['extras']); @@ -84,27 +90,22 @@ public function __toString(): string * Injects the results from pages' "full_text_ocr", if present. * * @param array $rawResponse Raw HTTP response. - * @return void */ 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 76% rename from src/Parsing/Common/Execution.php rename to src/V1/Parsing/Common/Execution.php index 7fb83ab8..d90e7841 100644 --- a/src/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -1,12 +1,14 @@ 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 { diff --git a/src/Parsing/Common/ExecutionFile.php b/src/V1/Parsing/Common/ExecutionFile.php similarity index 89% rename from src/Parsing/Common/ExecutionFile.php rename to src/V1/Parsing/Common/ExecutionFile.php index 6f675660..cccbf777 100644 --- a/src/Parsing/Common/ExecutionFile.php +++ b/src/V1/Parsing/Common/ExecutionFile.php @@ -1,6 +1,8 @@ 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 84% rename from src/Parsing/Common/Extras/Extras.php rename to src/V1/Parsing/Common/Extras/Extras.php index 1fdccbec..2533115b 100644 --- a/src/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -1,6 +1,8 @@ data[$varName] = $value; } @@ -46,9 +47,9 @@ public function __set(string $varName, mixed $value) 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']); @@ -63,9 +64,8 @@ public function __construct(array $rawPrediction) * Currently only used for full_text_ocr. * * @param array $rawPrediction Raw HTTP response. - * @return void */ - public function addArtificialExtra(array $rawPrediction) + public function addArtificialExtra(array $rawPrediction): void { if (isset($rawPrediction["full_text_ocr"]) && !isEmpty($rawPrediction['full_text_ocr'])) { $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); diff --git a/src/Parsing/Common/Extras/FullTextOcrExtra.php b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php similarity index 90% rename from src/Parsing/Common/Extras/FullTextOcrExtra.php rename to src/V1/Parsing/Common/Extras/FullTextOcrExtra.php index 1cf40065..8ac7d292 100644 --- a/src/Parsing/Common/Extras/FullTextOcrExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php @@ -1,8 +1,8 @@ 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 83% rename from src/Parsing/Common/Job.php rename to src/V1/Parsing/Common/Job.php index 3bc4e949..fbe468d5 100644 --- a/src/Parsing/Common/Job.php +++ b/src/V1/Parsing/Common/Job.php @@ -1,10 +1,15 @@ issuedAt = new DateTimeImmutable($rawResponse['issued_at']); - } catch (\Exception $e) { + } catch (Exception $e) { try { $this->issuedAt = new DateTimeImmutable(strtotime($rawResponse['issued_at'])); - } catch (\Exception $e2) { + } catch (Exception $e2) { throw new MindeeApiException( "Could not create date from " . $rawResponse['issued_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, @@ -60,15 +65,15 @@ public function __construct(array $rawResponse) $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) { + } catch (Exception $e2) { throw new MindeeApiException( "Could not create date from " . $rawResponse['available_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, @@ -76,8 +81,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,7 +91,6 @@ public function __construct(array $rawResponse) } /** - * @return string */ public function __toString(): string { diff --git a/src/Parsing/Common/Ocr/MVisionV1.php b/src/V1/Parsing/Common/OCR/MVisionV1.php similarity index 76% rename from src/Parsing/Common/Ocr/MVisionV1.php rename to src/V1/Parsing/Common/OCR/MVisionV1.php index 1d1c357e..cab967ec 100644 --- a/src/Parsing/Common/Ocr/MVisionV1.php +++ b/src/V1/Parsing/Common/OCR/MVisionV1.php @@ -1,6 +1,8 @@ pages = []; foreach ($rawPrediction['pages'] as $pagePrediction) { - $this->pages[] = new OcrPage($pagePrediction); + $this->pages[] = new OCRPage($pagePrediction); } } /** - * @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 80% rename from src/Parsing/Common/Ocr/Ocr.php rename to src/V1/Parsing/Common/OCR/OCR.php index 6cefb57d..12df313d 100644 --- a/src/Parsing/Common/Ocr/Ocr.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -1,14 +1,19 @@ mvisionV1); + return (string) ($this->mvisionV1); } /** @@ -40,7 +44,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 75% rename from src/Parsing/Common/Ocr/OcrLine.php rename to src/V1/Parsing/Common/OCR/OCRLine.php index 5626de3d..29873168 100644 --- a/src/Parsing/Common/Ocr/OcrLine.php +++ b/src/V1/Parsing/Common/OCR/OCRLine.php @@ -1,11 +1,15 @@ words, "Mindee\\Parsing\\Common\\Ocr\\OcrPage::getMinMaxX"); + usort($this->words, "Mindee\\V1\\Parsing\\Common\\OCR\\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 76% rename from src/Parsing/Common/Ocr/OcrPage.php rename to src/V1/Parsing/Common/OCR/OCRPage.php index 8cee1982..efaf492a 100644 --- a/src/Parsing/Common/Ocr/OcrPage.php +++ b/src/V1/Parsing/Common/OCR/OCRPage.php @@ -1,11 +1,16 @@ polygon->isPointInY($currentWord->polygon->getCentroid()); $nextInCurrent = $currentWord->polygon->isPointInY($nextWord->polygon->getCentroid()); @@ -33,15 +38,15 @@ private static function areWordsOnSameLine(OcrWord $currentWord, OcrWord $nextWo /** * Compares word positions on the X axis. Returns a sort-compliant result (0;-1;1). * - * @param OcrWord $word1 First word. - * @param OcrWord $word2 Second word. + * @param OCRWord $word1 First word. + * @param OCRWord $word2 Second word. * @return integer */ - public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int + public static function getMinMaxX(OCRWord $word1, OCRWord $word2): int { $word1X = $word1->polygon->getMinMaxX()->getMin(); $word2X = $word2->polygon->getMinMaxX()->getMin(); - if ($word1X == $word2X) { + if ($word1X === $word2X) { return 0; } return $word1X < $word2X ? -1 : 1; @@ -50,15 +55,15 @@ public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int /** * Compares word positions on the Y axis. Returns a sort-compliant result (0;-1;1). * - * @param OcrWord $word1 First word. - * @param OcrWord $word2 Second word. + * @param OCRWord $word1 First word. + * @param OCRWord $word2 Second word. * @return integer */ - public static function getMinMaxY(OcrWord $word1, OcrWord $word2): int + public static function getMinMaxY(OCRWord $word1, OCRWord $word2): int { $word1Y = $word1->polygon->getMinMaxY()->getMin(); $word2Y = $word2->polygon->getMinMaxY()->getMin(); - if ($word1Y == $word2Y) { + if ($word1Y === $word2Y) { return 0; } return $word1Y < $word2Y ? -1 : 1; @@ -67,7 +72,6 @@ public static function getMinMaxY(OcrWord $word1, OcrWord $word2): int /** * Puts all words on the page into an array of lines. * - * @return array */ private function toLines(): array { @@ -75,14 +79,14 @@ private function toLines(): array $indexes = []; $lines = []; foreach ($this->allWords as $w) { - $line = new OcrLine(); + $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 ($current === null) { $current = $word; $indexes[] = $idx; - $line = new OcrLine(); + $line = new OCRLine(); $line->add($word); } else { if ($this->areWordsOnSameLine($current, $word)) { @@ -104,7 +108,6 @@ private function toLines(): array /** * Retrieves all lines on the page. * - * @return array */ public function getAllLines(): array { @@ -117,7 +120,6 @@ public function getAllLines(): array /** * Retrieves all words on the page. * - * @return array */ public function getAllWords(): array { @@ -131,7 +133,7 @@ public function __construct(array $rawPrediction) { $this->allWords = []; foreach ($rawPrediction['all_words'] as $wordPrediction) { - $this->allWords[] = new OcrWord($wordPrediction); + $this->allWords[] = new OCRWord($wordPrediction); } usort($this->allWords, "self::getMinMaxY"); } @@ -143,7 +145,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 83% rename from src/Parsing/Common/Ocr/OcrWord.php rename to src/V1/Parsing/Common/OCR/OCRWord.php index 197862a1..24cc03d4 100644 --- a/src/Parsing/Common/Ocr/OcrWord.php +++ b/src/V1/Parsing/Common/OCR/OCRWord.php @@ -1,13 +1,15 @@ 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 = (float) ($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 90% rename from src/Parsing/Common/Page.php rename to src/V1/Parsing/Common/Page.php index 61db09ad..d2aa4626 100644 --- a/src/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -1,13 +1,17 @@ values[] = new StringField($valueStr, $this->pageId); @@ -56,9 +61,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ 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 86% rename from src/Parsing/Generated/GeneratedObjectField.php rename to src/V1/Parsing/Generated/GeneratedObjectField.php index 4660f5a5..cdff6a03 100644 --- a/src/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -1,8 +1,15 @@ 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 { @@ -86,7 +93,7 @@ public function strLevel(int $level = 0): string $outStr = ""; foreach ($this->printableValues as $attr) { $value = $this->{$attr}; - $strValue = $value !== null ? (string)$value : ""; + $strValue = $value !== null ? (string) $value : ""; $outStr .= "\n{$indent}:{$attr}: {$strValue}"; } return "\n" . $indent . trim($outStr); @@ -111,7 +118,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 82% rename from src/Parsing/Standard/AddressField.php rename to src/V1/Parsing/Standard/AddressField.php index e7eae1ff..1825ba4e 100644 --- a/src/Parsing/Standard/AddressField.php +++ b/src/V1/Parsing/Standard/AddressField.php @@ -1,6 +1,8 @@ value = number_format(floatval($rawPrediction['value']), 2, ".", ""); + $this->value = (float) ($rawPrediction['value']); } else { $this->value = null; $this->confidence = 0.0; @@ -41,6 +45,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/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php similarity index 71% rename from src/Parsing/Standard/BaseField.php rename to src/V1/Parsing/Standard/BaseField.php index 1f2b5d92..d8701c90 100644 --- a/src/Parsing/Standard/BaseField.php +++ b/src/V1/Parsing/Standard/BaseField.php @@ -1,6 +1,10 @@ pageId = $pageId; } $this->reconstructed = $reconstructed; - if (array_key_exists($valueKey, $rawPrediction) && $rawPrediction[$valueKey] != 'N/A') { + if (array_key_exists($valueKey, $rawPrediction) && $rawPrediction[$valueKey] !== 'N/A') { $this->value = $rawPrediction[$valueKey]; $this->setConfidence($rawPrediction); } else { @@ -54,9 +58,9 @@ public function __construct( * @param BaseField $obj Field to compare. * @return boolean */ - public function __compare(BaseField $obj): bool + public function __compare(self $obj): bool { - return $this->value == $obj->value; + return $this->value === $obj->value; } /** @@ -64,6 +68,6 @@ public function __compare(BaseField $obj): bool */ public function __toString(): string { - return isset($this->value) ? strval($this->value) : ''; + return isset($this->value) ? (string) ($this->value) : ''; } } diff --git a/src/Parsing/Standard/BooleanField.php b/src/V1/Parsing/Standard/BooleanField.php similarity index 60% rename from src/Parsing/Standard/BooleanField.php rename to src/V1/Parsing/Standard/BooleanField.php index ee907974..2784b79b 100644 --- a/src/Parsing/Standard/BooleanField.php +++ b/src/V1/Parsing/Standard/BooleanField.php @@ -1,16 +1,18 @@ value); + return SummaryHelperV1::formatForDisplay($this->value); } } diff --git a/src/Parsing/Standard/ClassificationField.php b/src/V1/Parsing/Standard/ClassificationField.php similarity index 63% rename from src/Parsing/Standard/ClassificationField.php rename to src/V1/Parsing/Standard/ClassificationField.php index d530f90d..6b8c25bb 100644 --- a/src/Parsing/Standard/ClassificationField.php +++ b/src/V1/Parsing/Standard/ClassificationField.php @@ -1,6 +1,8 @@ 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 86% rename from src/Parsing/Standard/DateField.php rename to src/V1/Parsing/Standard/DateField.php index 356ae224..f44afa8b 100644 --- a/src/Parsing/Standard/DateField.php +++ b/src/V1/Parsing/Standard/DateField.php @@ -1,6 +1,8 @@ confidence = $rawPrediction['confidence']; diff --git a/src/Parsing/Standard/FieldPositionMixin.php b/src/V1/Parsing/Standard/FieldPositionMixin.php similarity index 83% rename from src/Parsing/Standard/FieldPositionMixin.php rename to src/V1/Parsing/Standard/FieldPositionMixin.php index 9be9acc9..5105cbbe 100644 --- a/src/Parsing/Standard/FieldPositionMixin.php +++ b/src/V1/Parsing/Standard/FieldPositionMixin.php @@ -1,11 +1,14 @@ 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 70% rename from src/Parsing/Standard/LocaleField.php rename to src/V1/Parsing/Standard/LocaleField.php index 4e66795f..eddd61db 100644 --- a/src/Parsing/Standard/LocaleField.php +++ b/src/V1/Parsing/Standard/LocaleField.php @@ -1,6 +1,10 @@ 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 68% rename from src/Parsing/Standard/PaymentDetailsField.php rename to src/V1/Parsing/Standard/PaymentDetailsField.php index e9096f8a..d8be70aa 100644 --- a/src/Parsing/Standard/PaymentDetailsField.php +++ b/src/V1/Parsing/Standard/PaymentDetailsField.php @@ -1,6 +1,11 @@ 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->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; } diff --git a/src/Parsing/Standard/StringField.php b/src/V1/Parsing/Standard/StringField.php similarity index 65% rename from src/Parsing/Standard/StringField.php rename to src/V1/Parsing/Standard/StringField.php index f0319e87..e16b872f 100644 --- a/src/Parsing/Standard/StringField.php +++ b/src/V1/Parsing/Standard/StringField.php @@ -1,14 +1,18 @@ 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; } @@ -76,9 +81,9 @@ 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 +96,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 +110,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 74% rename from src/Parsing/Standard/Taxes.php rename to src/V1/Parsing/Standard/Taxes.php index d07a5712..935bff89 100644 --- a/src/Parsing/Standard/Taxes.php +++ b/src/V1/Parsing/Standard/Taxes.php @@ -1,15 +1,19 @@ getIterator(); if (!$iterator->valid()) { @@ -51,7 +54,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 @@ +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 63% rename from src/Product/BarcodeReader/BarcodeReaderV1Document.php rename to src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php index 82d9a6ef..dfe635b7 100644 --- a/src/Product/BarcodeReader/BarcodeReaderV1Document.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php @@ -1,11 +1,13 @@ codes1D = $rawPrediction["codes_1d"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->codes1D = $rawPrediction["codes_1d"] === null ? [] : 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 = $rawPrediction["codes_2d"] === null ? [] : array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_2d"] ); } @@ -60,6 +62,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/BillOfLading/BillOfLadingV1.php b/src/V1/Product/BillOfLading/BillOfLadingV1.php similarity index 82% rename from src/Product/BillOfLading/BillOfLadingV1.php rename to src/V1/Product/BillOfLading/BillOfLadingV1.php index efec526b..f5c5ce7c 100644 --- a/src/Product/BillOfLading/BillOfLadingV1.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1.php @@ -1,12 +1,14 @@ pages[] = new Page(BillOfLadingV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php similarity index 65% rename from src/Product/BillOfLading/BillOfLadingV1Carrier.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php index 55b196e9..41e6fb38 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Carrier.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php @@ -1,18 +1,20 @@ name); - $outArr["professionalNumber"] = SummaryHelper::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelper::formatForDisplay($this->scac); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); + $outArr["scac"] = SummaryHelperV1::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); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); + $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -87,6 +86,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php new file mode 100644 index 00000000..6cb3fe62 --- /dev/null +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php @@ -0,0 +1,118 @@ +setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->description = $rawPrediction["description"] ?? null; + $this->grossWeight = isset($rawPrediction["gross_weight"]) + ? (float) ($rawPrediction["gross_weight"]) : null; + $this->measurement = isset($rawPrediction["measurement"]) + ? (float) ($rawPrediction["measurement"]) : null; + $this->measurementUnit = $rawPrediction["measurement_unit"] ?? null; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; + $this->weightUnit = $rawPrediction["weight_unit"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); + $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); + $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); + $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); + $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["grossWeight"], 12); + $outStr .= SummaryHelperV1::padString($printable["measurement"], 11); + $outStr .= SummaryHelperV1::padString($printable["measurementUnit"], 16); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["weightUnit"], 11); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php similarity index 86% rename from src/Product/BillOfLading/BillOfLadingV1CarrierItems.php rename to src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index b579173e..fdaeb392 100644 --- a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -1,15 +1,19 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -95,6 +94,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Document.php b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php similarity index 85% rename from src/Product/BillOfLading/BillOfLadingV1Document.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Document.php index 8e836c2e..591e0709 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Document.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php @@ -1,12 +1,14 @@ 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); + $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 = (string) ($this->carrierItems); $outStr = ":Bill of Lading Number: $this->billOfLadingNumber :Shipper: $shipperToFieldList @@ -166,6 +168,6 @@ public function __toString(): string :Date of issue: $this->dateOfIssue :Departure Date: $this->departureDate "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php similarity index 64% rename from src/Product/BillOfLading/BillOfLadingV1NotifyParty.php rename to src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index ec96befb..0ad3fd4b 100644 --- a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -1,18 +1,20 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -95,6 +94,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php similarity index 63% rename from src/Product/BillOfLading/BillOfLadingV1Shipper.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php index bd3ae072..bd1aa623 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Shipper.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php @@ -1,18 +1,20 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -95,6 +94,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BusinessCard/BusinessCardV1.php b/src/V1/Product/BusinessCard/BusinessCardV1.php similarity index 82% rename from src/Product/BusinessCard/BusinessCardV1.php rename to src/V1/Product/BusinessCard/BusinessCardV1.php index f5697c46..ece609a6 100644 --- a/src/Product/BusinessCard/BusinessCardV1.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1.php @@ -1,12 +1,14 @@ 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..605a7556 100644 --- a/src/Product/BusinessCard/BusinessCardV1Document.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1Document.php @@ -1,11 +1,13 @@ socialMedia = $rawPrediction["social_media"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->socialMedia = $rawPrediction["social_media"] === null ? [] : 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 82% rename from src/Product/Cropper/CropperV1.php rename to src/V1/Product/Cropper/CropperV1.php index e3863ffa..536e8032 100644 --- a/src/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -1,12 +1,14 @@ 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 69% rename from src/Product/Cropper/CropperV1Document.php rename to src/V1/Product/Cropper/CropperV1Document.php index aecf0b65..d59ac678 100644 --- a/src/Product/Cropper/CropperV1Document.php +++ b/src/V1/Product/Cropper/CropperV1Document.php @@ -1,8 +1,10 @@ cropping = $rawPrediction["cropping"] == null ? [] : array_map( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->cropping = $rawPrediction["cropping"] === null ? [] : 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/DeliveryNote/DeliveryNoteV1.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php similarity index 82% rename from src/Product/DeliveryNote/DeliveryNoteV1.php rename to src/V1/Product/DeliveryNote/DeliveryNoteV1.php index 11c34e03..cde32f1b 100644 --- a/src/Product/DeliveryNote/DeliveryNoteV1.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php @@ -1,12 +1,14 @@ pages[] = new Page(DeliveryNoteV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php similarity index 87% rename from src/Product/DeliveryNote/DeliveryNoteV1Document.php rename to src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php index 426646b5..be6e9440 100644 --- a/src/Product/DeliveryNote/DeliveryNoteV1Document.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php @@ -1,13 +1,15 @@ customerAddress :Total Amount: $this->totalAmount "; - 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 82% rename from src/Product/DriverLicense/DriverLicenseV1.php rename to src/V1/Product/DriverLicense/DriverLicenseV1.php index 43c2468a..d78cc2f7 100644 --- a/src/Product/DriverLicense/DriverLicenseV1.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1.php @@ -1,12 +1,14 @@ 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 92% rename from src/Product/DriverLicense/DriverLicenseV1Document.php rename to src/V1/Product/DriverLicense/DriverLicenseV1Document.php index c3ddb431..b0a40d36 100644 --- a/src/Product/DriverLicense/DriverLicenseV1Document.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php @@ -1,12 +1,14 @@ 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 82% rename from src/Product/FinancialDocument/FinancialDocumentV1.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1.php index 5c153e3e..8290f702 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php @@ -1,12 +1,14 @@ 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 90% rename from src/Product/FinancialDocument/FinancialDocumentV1Document.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php index e070e7f6..1a153aad 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1Document.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php @@ -1,19 +1,21 @@ customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] == null ? [] : array_map( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : 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 = $rawPrediction["reference_numbers"] === null ? [] : 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 = $rawPrediction["supplier_company_registrations"] === null ? [] : 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 = $rawPrediction["supplier_payment_details"] === null ? [] : 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..04377842 --- /dev/null +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -0,0 +1,136 @@ +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. + * + */ + 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; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + 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 87% rename from src/Product/FinancialDocument/FinancialDocumentV1LineItems.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index b9340c2c..cdfb1ce1 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -1,15 +1,19 @@ 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 80% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php index ceb8cc30..ca8e3105 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php @@ -1,11 +1,13 @@ 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 82% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php index 532eaf80..7fa92f54 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php @@ -1,12 +1,14 @@ 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 64% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index 94297e1b..a94f77c0 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -1,18 +1,20 @@ 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; } /** * Return values for printing as an 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 +94,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 81% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php index dfc3043a..056a1bab 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php @@ -1,11 +1,13 @@ bban != null ? $this->bban->toFieldList() : ""; + $bbanToFieldList = $this->bban !== null ? $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 82% rename from src/Product/Fr/CarteGrise/CarteGriseV1.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index ede84373..0715991a 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -1,12 +1,14 @@ 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 97% rename from src/Product/Fr/CarteGrise/CarteGriseV1Document.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php index 9342649a..e3e204a6 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1Document.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php @@ -1,12 +1,14 @@ mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php similarity index 82% rename from src/Product/Fr/EnergyBill/EnergyBillV1.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1.php index d027d1be..deffd538 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php @@ -1,12 +1,14 @@ pages[] = new Page(EnergyBillV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php similarity index 85% rename from src/Product/Fr/EnergyBill/EnergyBillV1Document.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php index 9667b67b..64cd5e06 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php @@ -1,13 +1,15 @@ 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() : ""; + $energySupplierToFieldList = $this->energySupplier !== null ? $this->energySupplier->toFieldList() : ""; + $energyConsumerToFieldList = $this->energyConsumer !== null ? $this->energyConsumer->toFieldList() : ""; + $subscriptionSummary = (string) ($this->subscription); + $energyUsageSummary = (string) ($this->energyUsage); + $taxesAndContributionsSummary = (string) ($this->taxesAndContributions); + $meterDetailsToFieldList = $this->meterDetails !== null ? $this->meterDetails->toFieldList() : ""; $outStr = ":Invoice Number: $this->invoiceNumber :Contract ID: $this->contractId @@ -205,6 +207,6 @@ public function __toString(): string :Taxes and Contributions: $taxesAndContributionsSummary :Meter Details: $meterDetailsToFieldList "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php similarity index 65% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php index c09a048a..b7bc5164 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php @@ -1,18 +1,20 @@ address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -79,6 +78,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/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php similarity index 65% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php index b95eafc3..67c60e04 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php @@ -1,18 +1,20 @@ address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -79,6 +78,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php new file mode 100644 index 00000000..cce84b0c --- /dev/null +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php @@ -0,0 +1,135 @@ +setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->consumption = isset($rawPrediction["consumption"]) + ? (float) ($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"]) + ? (float) ($rawPrediction["tax_rate"]) : null; + $this->total = isset($rawPrediction["total"]) + ? (float) ($rawPrediction["total"]) : null; + $this->unit = $rawPrediction["unit"] ?? null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["consumption"], 11); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $outStr .= SummaryHelperV1::padString($printable["unit"], 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/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php similarity index 87% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 39f0b4c7..9c782786 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -1,15 +1,19 @@ meterNumber); - $outArr["meterType"] = SummaryHelper::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); + $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); + $outArr["unit"] = SummaryHelperV1::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); + $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); + $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -87,6 +86,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php new file mode 100644 index 00000000..eb5e4839 --- /dev/null +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php @@ -0,0 +1,118 @@ +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"]) + ? (float) ($rawPrediction["tax_rate"]) : null; + $this->total = isset($rawPrediction["total"]) + ? (float) ($rawPrediction["total"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $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/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php similarity index 86% rename from src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index 78d4818f..1f2c2416 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -1,15 +1,19 @@ 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"]) + ? (float) ($rawPrediction["tax_rate"]) : null; + $this->total = isset($rawPrediction["total"]) + ? (float) ($rawPrediction["total"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $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/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php similarity index 86% rename from src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 477416e1..2a0a3e95 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php @@ -1,15 +1,19 @@ pages[] = new Page(HealthCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/HealthCard/HealthCardV1Document.php b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php similarity index 77% rename from src/Product/Fr/HealthCard/HealthCardV1Document.php rename to src/V1/Product/Fr/HealthCard/HealthCardV1Document.php index 94f2d774..92cfc1c6 100644 --- a/src/Product/Fr/HealthCard/HealthCardV1Document.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php @@ -1,12 +1,14 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["issuance_date"])) { @@ -81,6 +83,6 @@ public function __toString(): string :Social Security Number: $this->socialSecurity :Issuance Date: $this->issuanceDate "; - 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 82% rename from src/Product/Fr/IdCard/IdCardV1.php rename to src/V1/Product/Fr/IdCard/IdCardV1.php index 16af405a..9d53b4e3 100644 --- a/src/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -1,12 +1,14 @@ 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..928097a0 100644 --- a/src/Product/Fr/IdCard/IdCardV1Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Document.php @@ -1,12 +1,14 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["id_number"])) { @@ -153,6 +155,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 68% rename from src/Product/Fr/IdCard/IdCardV1Page.php rename to src/V1/Product/Fr/IdCard/IdCardV1Page.php index 4239fca1..96024e7b 100644 --- a/src/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -1,9 +1,11 @@ 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 82% rename from src/Product/Fr/IdCard/IdCardV2.php rename to src/V1/Product/Fr/IdCard/IdCardV2.php index a4455598..690dfa37 100644 --- a/src/Product/Fr/IdCard/IdCardV2.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2.php @@ -1,12 +1,14 @@ 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 91% rename from src/Product/Fr/IdCard/IdCardV2Document.php rename to src/V1/Product/Fr/IdCard/IdCardV2Document.php index 45b38d16..32c60cea 100644 --- a/src/Product/Fr/IdCard/IdCardV2Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Document.php @@ -1,12 +1,14 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : 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 74% rename from src/Product/Fr/IdCard/IdCardV2Page.php rename to src/V1/Product/Fr/IdCard/IdCardV2Page.php index e96774bf..92824cab 100644 --- a/src/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -1,9 +1,11 @@ documentSide "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/Payslip/PayslipV3.php b/src/V1/Product/Fr/Payslip/PayslipV3.php similarity index 82% rename from src/Product/Fr/Payslip/PayslipV3.php rename to src/V1/Product/Fr/Payslip/PayslipV3.php index b58461ea..ea597350 100644 --- a/src/Product/Fr/Payslip/PayslipV3.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3.php @@ -1,12 +1,14 @@ pages[] = new Page(PayslipV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php similarity index 64% rename from src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php rename to src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php index 7cdbb5a6..6532cb1a 100644 --- a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php @@ -1,18 +1,20 @@ bankName); - $outArr["iban"] = SummaryHelper::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelper::formatForDisplay($this->swift); + $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); + $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); + $outArr["swift"] = SummaryHelperV1::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); + $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); + $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); + $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -87,6 +86,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/Payslip/PayslipV3Document.php b/src/V1/Product/Fr/Payslip/PayslipV3Document.php similarity index 78% rename from src/Product/Fr/Payslip/PayslipV3Document.php rename to src/V1/Product/Fr/Payslip/PayslipV3Document.php index 012dcc82..5ad88e01 100644 --- a/src/Product/Fr/Payslip/PayslipV3Document.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Document.php @@ -1,10 +1,12 @@ 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); + $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 = (string) ($this->salaryDetails); + $payDetailToFieldList = $this->payDetail !== null ? $this->payDetail->toFieldList() : ""; + $paidTimeOffSummary = (string) ($this->paidTimeOff); $outStr = ":Pay Period: $payPeriodToFieldList :Employee: $employeeToFieldList @@ -132,6 +134,6 @@ public function __toString(): string :Pay Detail: $payDetailToFieldList :Paid Time Off: $paidTimeOffSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php similarity index 62% rename from src/Product/Fr/Payslip/PayslipV3Employee.php rename to src/V1/Product/Fr/Payslip/PayslipV3Employee.php index cfec9c3f..c1d0d17a 100644 --- a/src/Product/Fr/Payslip/PayslipV3Employee.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php @@ -1,18 +1,20 @@ 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); + $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); + $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); + $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); + $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); + $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); + $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -119,6 +118,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/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php similarity index 62% rename from src/Product/Fr/Payslip/PayslipV3Employer.php rename to src/V1/Product/Fr/Payslip/PayslipV3Employer.php index a46a7689..d3fb3b48 100644 --- a/src/Product/Fr/Payslip/PayslipV3Employer.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php @@ -1,18 +1,20 @@ 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); + $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); + $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); return $outArr; } /** * 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); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); + $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); + $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -119,6 +118,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/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php similarity index 62% rename from src/Product/Fr/Payslip/PayslipV3Employment.php rename to src/V1/Product/Fr/Payslip/PayslipV3Employment.php index 2ab159f3..975ffed6 100644 --- a/src/Product/Fr/Payslip/PayslipV3Employment.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php @@ -1,18 +1,20 @@ 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); + $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); + $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); + $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); + $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); + $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); + $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); return $outArr; } /** * 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); + $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); + $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); + $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); + $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); + $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); + $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -119,6 +118,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php new file mode 100644 index 00000000..33af14ac --- /dev/null +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php @@ -0,0 +1,110 @@ +setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->accrued = isset($rawPrediction["accrued"]) + ? (float) ($rawPrediction["accrued"]) : null; + $this->period = $rawPrediction["period"] ?? null; + $this->ptoType = $rawPrediction["pto_type"] ?? null; + $this->remaining = isset($rawPrediction["remaining"]) + ? (float) ($rawPrediction["remaining"]) : null; + $this->used = isset($rawPrediction["used"]) + ? (float) ($rawPrediction["used"]) : null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); + $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period, 6); + $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType, 11); + $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); + $outArr["used"] = SummaryHelperV1::formatFloat($this->used); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); + $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period); + $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType); + $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); + $outArr["used"] = SummaryHelperV1::formatFloat($this->used); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["accrued"], 9); + $outStr .= SummaryHelperV1::padString($printable["period"], 6); + $outStr .= SummaryHelperV1::padString($printable["ptoType"], 11); + $outStr .= SummaryHelperV1::padString($printable["remaining"], 9); + $outStr .= SummaryHelperV1::padString($printable["used"], 9); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php similarity index 85% rename from src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php rename to src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index 464ca86d..c6ae3cfe 100644 --- a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php @@ -1,15 +1,19 @@ 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; + $this->grossSalary = isset($rawPrediction["gross_salary"]) + ? (float) ($rawPrediction["gross_salary"]) : null; + $this->grossSalaryYtd = isset($rawPrediction["gross_salary_ytd"]) + ? (float) ($rawPrediction["gross_salary_ytd"]) : null; + $this->incomeTaxRate = isset($rawPrediction["income_tax_rate"]) + ? (float) ($rawPrediction["income_tax_rate"]) : null; + $this->incomeTaxWithheld = isset($rawPrediction["income_tax_withheld"]) + ? (float) ($rawPrediction["income_tax_withheld"]) : null; + $this->netPaid = isset($rawPrediction["net_paid"]) + ? (float) ($rawPrediction["net_paid"]) : null; + $this->netPaidBeforeTax = isset($rawPrediction["net_paid_before_tax"]) + ? (float) ($rawPrediction["net_paid_before_tax"]) : null; + $this->netTaxable = isset($rawPrediction["net_taxable"]) + ? (float) ($rawPrediction["net_taxable"]) : null; + $this->netTaxableYtd = isset($rawPrediction["net_taxable_ytd"]) + ? (float) ($rawPrediction["net_taxable_ytd"]) : null; + $this->totalCostEmployer = isset($rawPrediction["total_cost_employer"]) + ? (float) ($rawPrediction["total_cost_employer"]) : null; + $this->totalTaxesAndDeductions = isset($rawPrediction["total_taxes_and_deductions"]) + ? (float) ($rawPrediction["total_taxes_and_deductions"]) : null; } /** * Return values for printing inside an RST table. * - * @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); + $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); + $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); + $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); + $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); + $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); + $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); + $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); + $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); + $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); + $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); return $outArr; } /** * 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); + $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); + $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); + $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); + $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); + $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); + $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); + $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); + $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); + $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); + $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -153,6 +152,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/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php similarity index 63% rename from src/Product/Fr/Payslip/PayslipV3PayPeriod.php rename to src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index 19e9742d..bb824668 100644 --- a/src/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -1,18 +1,20 @@ 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); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); + $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } /** * 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); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); + $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -103,6 +102,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php new file mode 100644 index 00000000..a3c1ec22 --- /dev/null +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php @@ -0,0 +1,111 @@ +setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->amount = isset($rawPrediction["amount"]) + ? (float) ($rawPrediction["amount"]) : null; + $this->base = isset($rawPrediction["base"]) + ? (float) ($rawPrediction["base"]) : null; + $this->description = $rawPrediction["description"] ?? null; + $this->number = isset($rawPrediction["number"]) + ? (float) ($rawPrediction["number"]) : null; + $this->rate = isset($rawPrediction["rate"]) + ? (float) ($rawPrediction["rate"]) : null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["base"] = SummaryHelperV1::formatFloat($this->base); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["number"] = SummaryHelperV1::formatFloat($this->number); + $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["base"] = SummaryHelperV1::formatFloat($this->base); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["number"] = SummaryHelperV1::formatFloat($this->number); + $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["amount"], 12); + $outStr .= SummaryHelperV1::padString($printable["base"], 9); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["number"], 6); + $outStr .= SummaryHelperV1::padString($printable["rate"], 9); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php similarity index 86% rename from src/Product/Fr/Payslip/PayslipV3SalaryDetails.php rename to src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index 2a8dd8da..b8534e43 100644 --- a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php @@ -1,15 +1,19 @@ {$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 63% rename from src/Product/Generated/GeneratedV1Page.php rename to src/V1/Product/Generated/GeneratedV1Page.php index 4a1cf546..a5ec62e1 100644 --- a/src/Product/Generated/GeneratedV1Page.php +++ b/src/V1/Product/Generated/GeneratedV1Page.php @@ -1,10 +1,16 @@ {$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 86% rename from src/Product/Generated/GeneratedV1Prediction.php rename to src/V1/Product/Generated/GeneratedV1Prediction.php index 44e83225..36381bfd 100644 --- a/src/Product/Generated/GeneratedV1Prediction.php +++ b/src/V1/Product/Generated/GeneratedV1Prediction.php @@ -1,16 +1,20 @@ 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/Ind/IndianPassport/IndianPassportV1.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php similarity index 82% rename from src/Product/Ind/IndianPassport/IndianPassportV1.php rename to src/V1/Product/Ind/IndianPassport/IndianPassportV1.php index a77be27b..b28bbcfd 100644 --- a/src/Product/Ind/IndianPassport/IndianPassportV1.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php @@ -1,12 +1,14 @@ pages[] = new Page(IndianPassportV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php similarity index 95% rename from src/Product/Ind/IndianPassport/IndianPassportV1Document.php rename to src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php index 0de52578..bee6ada5 100644 --- a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php @@ -1,13 +1,15 @@ address3 :File Number: $this->fileNumber "; - 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 82% rename from src/Product/InternationalId/InternationalIdV2.php rename to src/V1/Product/InternationalId/InternationalIdV2.php index 361ee315..faf9401b 100644 --- a/src/Product/InternationalId/InternationalIdV2.php +++ b/src/V1/Product/InternationalId/InternationalIdV2.php @@ -1,12 +1,14 @@ 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..9286248c 100644 --- a/src/Product/InternationalId/InternationalIdV2Document.php +++ b/src/V1/Product/InternationalId/InternationalIdV2Document.php @@ -1,13 +1,15 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : 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 = $rawPrediction["surnames"] === null ? [] : 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 82% rename from src/Product/Invoice/InvoiceV4.php rename to src/V1/Product/Invoice/InvoiceV4.php index dcdb975d..52d05382 100644 --- a/src/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -1,12 +1,14 @@ 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 90% rename from src/Product/Invoice/InvoiceV4Document.php rename to src/V1/Product/Invoice/InvoiceV4Document.php index c485aa61..6e6ef5b3 100644 --- a/src/Product/Invoice/InvoiceV4Document.php +++ b/src/V1/Product/Invoice/InvoiceV4Document.php @@ -1,19 +1,21 @@ customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] == null ? [] : array_map( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : 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 = $rawPrediction["reference_numbers"] === null ? [] : 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 = $rawPrediction["supplier_company_registrations"] === null ? [] : 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 = $rawPrediction["supplier_payment_details"] === null ? [] : 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..016a73e3 --- /dev/null +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -0,0 +1,136 @@ +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. + * + */ + 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; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + 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 88% rename from src/Product/Invoice/InvoiceV4LineItems.php rename to src/V1/Product/Invoice/InvoiceV4LineItems.php index e3e399bc..2cd8f84e 100644 --- a/src/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -1,15 +1,19 @@ 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 67% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php index dccce3ad..9b4b8e36 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php @@ -1,10 +1,12 @@ 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 69% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index b0c83c20..58ca99fe 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -1,18 +1,20 @@ 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 +70,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 83% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index ea90083b..e45521c7 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -1,15 +1,19 @@ 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..3ecb87d6 100644 --- a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php @@ -1,11 +1,13 @@ receipts = $rawPrediction["receipts"] == null ? [] : array_map( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->receipts = $rawPrediction["receipts"] === null ? [] : 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/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php similarity index 82% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php index 6dd5e427..f966c8cc 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php @@ -1,12 +1,14 @@ pages[] = new Page(NutritionFactsLabelV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php index d8b0a3d2..ebd7881d 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php similarity index 59% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index 48dc38b3..25e3f0f5 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 593ef85f..65d6f30f 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index bcba21c4..89cfbe7b 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php similarity index 80% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php index 4059714e..27f8f65b 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php @@ -1,11 +1,13 @@ 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); + $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 = (string) ($this->nutrients); $outStr = ":Serving per Box: $this->servingPerBox :Serving Size: $servingSizeToFieldList @@ -209,6 +211,6 @@ public function __toString(): string :sodium: $sodiumToFieldList :nutrients: $nutrientsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php new file mode 100644 index 00000000..4eee0bf5 --- /dev/null +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php @@ -0,0 +1,110 @@ +setConfidence($rawPrediction); + $this->setPosition($rawPrediction); + $this->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->name = $rawPrediction["name"] ?? null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($rawPrediction["per_serving"]) : null; + $this->unit = $rawPrediction["unit"] ?? null; + } + + /** + * Return values for printing inside an RST table. + * + */ + private function tablePrintableValues(): array + { + $outArr = []; + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + return $outArr; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + public function toTableLine(): string + { + $printable = $this->tablePrintableValues(); + $outStr = "| "; + $outStr .= SummaryHelperV1::padString($printable["dailyValue"], 11); + $outStr .= SummaryHelperV1::padString($printable["name"], 20); + $outStr .= SummaryHelperV1::padString($printable["per100G"], 8); + $outStr .= SummaryHelperV1::padString($printable["perServing"], 11); + $outStr .= SummaryHelperV1::padString($printable["unit"], 4); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return SummaryHelperV1::cleanOutString($this->toTableLine()); + } +} diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php similarity index 85% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 17ae8072..17cf7bb1 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php @@ -1,15 +1,19 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index 25517a74..e2b4411c 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php similarity index 62% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index 901d9fe5..a3330f4d 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -1,18 +1,20 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) ? - floatval($rawPrediction["amount"]) : null; + $this->amount = isset($rawPrediction["amount"]) + ? (float) ($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); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["unit"] = SummaryHelperV1::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); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -80,6 +79,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php similarity index 59% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index f7d897d2..9a3732d6 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -98,6 +97,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index 51de30f7..3f19e755 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php similarity index 59% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index af421e6c..d6a9722b 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php similarity index 60% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index cd122c34..12efdc4d 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php similarity index 59% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index e3aded8f..a62150fa 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -1,18 +1,20 @@ 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->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($rawPrediction["daily_value"]) : null; + $this->per100G = isset($rawPrediction["per_100g"]) + ? (float) ($rawPrediction["per_100g"]) : null; + $this->perServing = isset($rawPrediction["per_serving"]) + ? (float) ($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); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -90,6 +89,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php similarity index 82% rename from src/Product/Passport/PassportV1.php rename to src/V1/Product/Passport/PassportV1.php index 1a45b867..a0341058 100644 --- a/src/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -1,12 +1,14 @@ 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..455a9b65 100644 --- a/src/Product/Passport/PassportV1Document.php +++ b/src/V1/Product/Passport/PassportV1Document.php @@ -1,12 +1,14 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : 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 82% rename from src/Product/Receipt/ReceiptV5.php rename to src/V1/Product/Receipt/ReceiptV5.php index 681a87f4..9eb95949 100644 --- a/src/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -1,12 +1,14 @@ 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 89% rename from src/Product/Receipt/ReceiptV5Document.php rename to src/V1/Product/Receipt/ReceiptV5Document.php index fca27398..475fac30 100644 --- a/src/Product/Receipt/ReceiptV5Document.php +++ b/src/V1/Product/Receipt/ReceiptV5Document.php @@ -1,17 +1,19 @@ supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] == null ? [] : array_map( - fn ($prediction) => new CompanyRegistrationField($prediction, $pageId), + $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : 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..c20758fc --- /dev/null +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -0,0 +1,102 @@ +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. + * + */ + 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; + } + + /** + * Return values for printing as an array. + * + */ + private function printableValues(): array + { + $outArr = []; + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); + return $outArr; + } + /** + * Output in a format suitable for inclusion in an rST table. + * + */ + 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 85% rename from src/Product/Receipt/ReceiptV5LineItems.php rename to src/V1/Product/Receipt/ReceiptV5LineItems.php index f684ff43..0f2a2ecc 100644 --- a/src/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -1,15 +1,19 @@ pages[] = new Page(ResumeV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php similarity index 54% rename from src/Product/Resume/ResumeV1Certificate.php rename to src/V1/Product/Resume/ResumeV1Certificate.php index 48e12144..e581be91 100644 --- a/src/Product/Resume/ResumeV1Certificate.php +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -1,18 +1,20 @@ grade, 10); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 30); - $outArr["provider"] = SummaryHelper::formatForDisplay($this->provider, 25); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); + $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; } /** * 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); + $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $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)); } /** @@ -95,6 +94,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php similarity index 85% rename from src/Product/Resume/ResumeV1Certificates.php rename to src/V1/Product/Resume/ResumeV1Certificates.php index c13366f1..07c2c7c3 100644 --- a/src/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -1,15 +1,19 @@ givenNames = $rawPrediction["given_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->givenNames = $rawPrediction["given_names"] === null ? [] : 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 = $rawPrediction["hard_skills"] === null ? [] : 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 = $rawPrediction["soft_skills"] === null ? [] : 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 = $rawPrediction["surnames"] === null ? [] : 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/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php similarity index 51% rename from src/Product/Resume/ResumeV1Education.php rename to src/V1/Product/Resume/ResumeV1Education.php index 00600645..811f24ed 100644 --- a/src/Product/Resume/ResumeV1Education.php +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -1,18 +1,20 @@ 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); + $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; } /** * 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); + $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain); + $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $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)); } /** @@ -119,6 +118,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php similarity index 87% rename from src/Product/Resume/ResumeV1Educations.php rename to src/V1/Product/Resume/ResumeV1Educations.php index 6549826c..7848a327 100644 --- a/src/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -1,15 +1,19 @@ language); - $outArr["level"] = SummaryHelper::formatForDisplay($this->level, 20); + $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); + $outArr["level"] = SummaryHelperV1::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); + $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); + $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $outStr .= SummaryHelperV1::padString($printable["language"], 8); + $outStr .= SummaryHelperV1::padString($printable["level"], 20); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -79,6 +78,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php similarity index 84% rename from src/Product/Resume/ResumeV1Languages.php rename to src/V1/Product/Resume/ResumeV1Languages.php index 612a5ad7..8587e2b4 100644 --- a/src/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -1,15 +1,19 @@ 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); + $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; } /** * 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); + $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType); + $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $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)); } /** @@ -135,6 +134,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php similarity index 88% rename from src/Product/Resume/ResumeV1ProfessionalExperiences.php rename to src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index 84cfecca..c1509b4c 100644 --- a/src/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -1,15 +1,19 @@ name, 20); - $outArr["url"] = SummaryHelper::formatForDisplay($this->url, 50); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); + $outArr["url"] = SummaryHelperV1::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); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $outStr .= SummaryHelperV1::padString($printable["name"], 20); + $outStr .= SummaryHelperV1::padString($printable["url"], 50); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -79,6 +78,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php similarity index 84% rename from src/Product/Resume/ResumeV1SocialNetworksUrls.php rename to src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index 9b9b0a13..162c7eb1 100644 --- a/src/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -1,15 +1,19 @@ 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..cfbae322 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Document.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php @@ -1,13 +1,15 @@ payees = $rawPrediction["payees"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->payees = $rawPrediction["payees"] === null ? [] : 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 70% rename from src/Product/Us/BankCheck/BankCheckV1Page.php rename to src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 8642f35c..32a80475 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -1,9 +1,11 @@ signaturesPositions = $rawPrediction["signatures_positions"] == null ? [] : array_map( - fn ($prediction) => new PositionField($prediction, $pageId), + $this->signaturesPositions = $rawPrediction["signatures_positions"] === null ? [] : 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/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php similarity index 82% rename from src/Product/Us/HealthcareCard/HealthcareCardV1.php rename to src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php index 0aa6d05f..16f992b8 100644 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php @@ -1,12 +1,14 @@ pages[] = new Page(HealthcareCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php similarity index 55% rename from src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php rename to src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php index 8fc4287a..8d451fb0 100644 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php @@ -1,18 +1,20 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->serviceFees = isset($rawPrediction["service_fees"]) ? - floatval($rawPrediction["service_fees"]) : null; + $this->serviceFees = isset($rawPrediction["service_fees"]) + ? (float) ($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); + $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); + $outArr["serviceName"] = SummaryHelperV1::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); + $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); + $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $outStr .= SummaryHelperV1::padString($printable["serviceFees"], 12); + $outStr .= SummaryHelperV1::padString($printable["serviceName"], 20); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -80,6 +79,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php similarity index 83% rename from src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php rename to src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index 0722d305..880a53e5 100644 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php @@ -1,15 +1,19 @@ dependents = $rawPrediction["dependents"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->dependents = $rawPrediction["dependents"] === null ? [] : array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["dependents"] ); if (!isset($rawPrediction["enrollment_date"])) { @@ -185,7 +187,7 @@ public function __toString(): string "\n ", $this->dependents ); - $copaysSummary = strval($this->copays); + $copaysSummary = (string) ($this->copays); $outStr = ":Company Name: $this->companyName :Plan Name: $this->planName @@ -202,6 +204,6 @@ public function __toString(): string :Copays: $copaysSummary :Enrollment Date: $this->enrollmentDate "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php similarity index 82% rename from src/Product/Us/UsMail/UsMailV3.php rename to src/V1/Product/Us/UsMail/UsMailV3.php index eee81dd3..2a151540 100644 --- a/src/Product/Us/UsMail/UsMailV3.php +++ b/src/V1/Product/Us/UsMail/UsMailV3.php @@ -1,12 +1,14 @@ pages[] = new Page(UsMailV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/UsMail/UsMailV3Document.php b/src/V1/Product/Us/UsMail/UsMailV3Document.php similarity index 78% rename from src/Product/Us/UsMail/UsMailV3Document.php rename to src/V1/Product/Us/UsMail/UsMailV3Document.php index c83f9bcb..58095f7d 100644 --- a/src/Product/Us/UsMail/UsMailV3Document.php +++ b/src/V1/Product/Us/UsMail/UsMailV3Document.php @@ -1,12 +1,14 @@ recipientNames = $rawPrediction["recipient_names"] == null ? [] : array_map( - fn ($prediction) => new StringField($prediction, $pageId), + $this->recipientNames = $rawPrediction["recipient_names"] === null ? [] : array_map( + static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["recipient_names"] ); if (!isset($rawPrediction["sender_address"])) { @@ -82,12 +84,12 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $senderAddressToFieldList = $this->senderAddress != null ? $this->senderAddress->toFieldList() : ""; + $senderAddressToFieldList = $this->senderAddress !== null ? $this->senderAddress->toFieldList() : ""; $recipientNames = implode( "\n ", $this->recipientNames ); - $recipientAddressesSummary = strval($this->recipientAddresses); + $recipientAddressesSummary = (string) ($this->recipientAddresses); $outStr = ":Sender Name: $this->senderName :Sender Address: $senderAddressToFieldList @@ -95,6 +97,6 @@ public function __toString(): string :Recipient Addresses: $recipientAddressesSummary :Return to Sender: $this->isReturnToSender "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php similarity index 50% rename from src/Product/Us/UsMail/UsMailV3RecipientAddress.php rename to src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index 472de2ef..ccfcbf6c 100644 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -1,18 +1,20 @@ 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); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); + $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); + $outArr["unit"] = SummaryHelperV1::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); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); + $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** * Output in a format suitable for inclusion in an rST table. * - * @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)); + $outStr .= SummaryHelperV1::padString($printable["city"], 15); + $outStr .= SummaryHelperV1::padString($printable["complete"], 35); + $outStr .= SummaryHelperV1::padString($printable["isAddressChange"], 17); + $outStr .= SummaryHelperV1::padString($printable["postalCode"], 11); + $outStr .= SummaryHelperV1::padString($printable["privateMailboxNumber"], 22); + $outStr .= SummaryHelperV1::padString($printable["state"], 5); + $outStr .= SummaryHelperV1::padString($printable["street"], 25); + $outStr .= SummaryHelperV1::padString($printable["unit"], 15); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -127,6 +126,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php similarity index 87% rename from src/Product/Us/UsMail/UsMailV3RecipientAddresses.php rename to src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php index 42e4c573..28362408 100644 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php @@ -1,15 +1,19 @@ 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); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); return $outArr; } /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { $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); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); return $outArr; } /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { @@ -103,6 +102,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/ClientV2.php b/src/V2/Client.php similarity index 62% rename from src/ClientV2.php rename to src/V2/Client.php index fc0ab147..4ad08ef1 100644 --- a/src/ClientV2.php +++ b/src/V2/Client.php @@ -1,27 +1,30 @@ mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); + $this->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. + * @param InputSource $inputSource File to parse. + * @param ExtractionParameters $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 + ExtractionParameters $params ): JobResponse { return $this->enqueue($inputSource, $params); } /** * 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 +67,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 +86,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 +109,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 +155,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 +172,8 @@ 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" ); } } diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index a156fb3e..c54c6b33 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -1,8 +1,10 @@ |null $webhooksIds List of webhook IDs. */ - public PollingOptions $pollingOptions; - - /** - * @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. - */ - public function __construct(string $modelId, ?string $alias, ?array $webhooksIds, ?PollingOptions $pollingOptions) + public function __construct(string $modelId, ?string $alias, ?array $webhooksIds) { $this->modelId = $modelId; @@ -47,10 +43,6 @@ public function __construct(string $modelId, ?string $alias, ?array $webhooksIds } else { $this->webhooksIds = []; } - if (!$pollingOptions) { - $pollingOptions = new PollingOptions(); - } - $this->pollingOptions = $pollingOptions; } /** diff --git a/src/V2/FileOperations/Crop.php b/src/V2/FileOperations/Crop.php index 56dc6d4f..1be4e189 100644 --- a/src/V2/FileOperations/Crop.php +++ b/src/V2/FileOperations/Crop.php @@ -1,5 +1,7 @@ $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..01ad0eee 100644 --- a/src/V2/FileOperations/CropFiles.php +++ b/src/V2/FileOperations/CropFiles.php @@ -1,16 +1,22 @@ + * * @extends ArrayObject */ -class CropFiles extends \ArrayObject +class CropFiles extends ArrayObject { /** * Builds a new CropFiles collection. @@ -25,13 +31,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, @@ -49,7 +54,7 @@ public function saveAllToDisk( try { $crop->writeToFile($path, $format, $quality); - } catch (\ImagickException $e) { + } 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..93015574 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -1,10 +1,12 @@ extractSplits([$split])[0]; } @@ -65,8 +67,8 @@ public function extractSingleSplit(array $split): ExtractedPdf */ public function extractSplits(array $splits): SplitFiles { - $pdfExtractor = new PdfExtractor($this->localInput); - $expandedPageIndexes = array_map(fn (array $split) => self::expandRange($split[0], $split[1]), $splits); + $pdfExtractor = new PDFExtractor($this->localInput); + $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..50b11f49 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -1,23 +1,31 @@ + * * @extends ArrayObject */ -class SplitFiles extends \ArrayObject +class SplitFiles extends ArrayObject { /** * Builds a new SplitFiles collection. * - * @param ExtractedPdf ...$items Items. + * @param ExtractedPDF ...$items Items. */ - public function __construct(ExtractedPdf ...$items) + public function __construct(ExtractedPDF ...$items) { parent::__construct($items); } @@ -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,7 +55,7 @@ public function saveAllToDisk(string $path, string $prefix = 'split'): void try { $split->writeToFile($filePath); - } catch (\Exception $e) { + } catch (Exception $e) { throw new MindeeException('Failed to save split to disk.', 0, $e->getMessage()); } diff --git a/src/Http/MindeeApiV2.php b/src/V2/HTTP/MindeeAPIV2.php similarity index 86% rename from src/Http/MindeeApiV2.php rename to src/V2/HTTP/MindeeAPIV2.php index 38c9957f..eba9adf8 100644 --- a/src/Http/MindeeApiV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -1,39 +1,43 @@ baseUrl = API_V2_BASE_URL_DEFAULT; $this->requestTimeout = API_V2_TIMEOUT_DEFAULT; $this->setFromEnv(); - if (!$this->apiKey || strlen($this->apiKey) == 0) { + if (!$this->apiKey || $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_KEY_ENV_NAME . ' environment variable.', ErrorCode::USER_INPUT_ERROR ); } @@ -114,7 +117,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,7 +126,6 @@ protected function setBaseUrl(string $value): void /** * Sets values from environment, if needed. * - * @return void */ private function setFromEnv(): void { @@ -133,7 +134,7 @@ private function setFromEnv(): void 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,7 +147,6 @@ private function setFromEnv(): void * Sets the API key. * * @param string|null $apiKey Optional API key. - * @return void */ protected function setApiKey(?string $apiKey = null): void { @@ -160,9 +160,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 +181,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. */ @@ -232,22 +232,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. @@ -270,7 +254,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. @@ -301,7 +285,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. */ @@ -361,9 +345,8 @@ 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. * @throws MindeeException Throws if the cURL operation doesn't go succeed. */ private function documentEnqueuePost( @@ -398,7 +381,6 @@ private function documentEnqueuePost( /** * @param array $result Raw HTTP response array with 'data' and 'code' keys. - * @return void * @throws MindeeV2HttpException Throws if the HTTP status indicates an error. * @throws MindeeV2HttpUnknownException Throws if the server sends an unexpected reply. */ diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/BaseInference.php index 27dcb0f9..d25df119 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -1,11 +1,13 @@ 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']); + $this->errors = array_map(static fn($error) => new ErrorItem($error), $serverResponse['errors']); } else { $this->errors = []; } diff --git a/src/Parsing/V2/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php similarity index 89% rename from src/Parsing/V2/BaseResponse.php rename to src/V2/Parsing/Inference/BaseResponse.php index 783f7c3e..5ec3ab3e 100644 --- a/src/Parsing/V2/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -1,6 +1,8 @@ fields[$fieldName]; - if ($field == null) { + if ($field === null) { throw new InvalidArgumentException("Field $fieldName does not exist."); } return $field; @@ -102,7 +106,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 +113,7 @@ public function toString(?int $indent = 0): string return ''; } - $indent = $indent ?? $this->indentLevel; + $indent ??= $this->indentLevel; $padding = str_repeat(' ', $indent); $lines = []; @@ -125,7 +128,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 82% rename from src/Parsing/V2/Field/ListField.php rename to src/V2/Parsing/Inference/Field/ListField.php index 87676d28..5fb69016 100644 --- a/src/Parsing/V2/Field/ListField.php +++ b/src/V2/Parsing/Inference/Field/ListField.php @@ -1,9 +1,15 @@ + * @var ObjectField */ public array $items; /** - * @param array $serverResponse Raw server response array. - * @param integer $indentLevel Level of indentation for rst display. + * @param array $serverResponse 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) @@ -38,7 +44,6 @@ public function __construct(array $serverResponse, int $indentLevel = 0) } /** - * @return string */ public function __toString(): string { diff --git a/src/Parsing/V2/Field/ObjectField.php b/src/V2/Parsing/Inference/Field/ObjectField.php similarity index 88% rename from src/Parsing/V2/Field/ObjectField.php rename to src/V2/Parsing/Inference/Field/ObjectField.php index cfd440d0..48425d68 100644 --- a/src/Parsing/V2/Field/ObjectField.php +++ b/src/V2/Parsing/Inference/Field/ObjectField.php @@ -1,6 +1,8 @@ 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/Parsing/V2/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php similarity index 65% rename from src/Parsing/V2/Field/SimpleField.php rename to src/V2/Parsing/Inference/Field/SimpleField.php index f5177f2b..be162ce7 100644 --- a/src/Parsing/V2/Field/SimpleField.php +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -1,6 +1,12 @@ value ? 'True' : 'False'; } if (is_numeric($this->value)) { - return number_format($this->value, 1, '.', ''); + return number_format((float) $this->value, 1, '.', ''); } - return $this->value !== null ? (string)$this->value : ''; + return $this->value !== null ? (string) $this->value : ''; } } diff --git a/src/Parsing/V2/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php similarity index 77% rename from src/Parsing/V2/InferenceActiveOptions.php rename to src/V2/Parsing/Inference/InferenceActiveOptions.php index 743cc4c8..edb8ce8d 100644 --- a/src/Parsing/V2/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -1,8 +1,11 @@ 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..5ee94dab 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.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 $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Crop/CropInference.php b/src/V2/Product/Crop/CropInference.php index 9eb13d07..cdecf2c8 100644 --- a/src/V2/Product/Crop/CropInference.php +++ b/src/V2/Product/Crop/CropInference.php @@ -1,5 +1,7 @@ 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; } /** diff --git a/src/V2/Product/Crop/CropResponse.php b/src/V2/Product/Crop/CropResponse.php index cfd07e29..f0a08c62 100644 --- a/src/V2/Product/Crop/CropResponse.php +++ b/src/V2/Product/Crop/CropResponse.php @@ -1,8 +1,10 @@ crops = array_map(fn ($crop) => new CropItem($crop), $rawResponse['crops']); + $this->crops = array_map(static fn($crop) => new CropItem($crop), $rawResponse['crops']); } /** diff --git a/src/V2/Product/Crop/Params/CropParameters.php b/src/V2/Product/Crop/Params/CropParameters.php index f7547cc1..1daacedb 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 $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/Parsing/V2/Inference.php b/src/V2/Product/Extraction/ExtractionInference.php similarity index 66% rename from src/Parsing/V2/Inference.php rename to src/V2/Product/Extraction/ExtractionInference.php index 81dfecaa..83027850 100644 --- a/src/Parsing/V2/Inference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -1,14 +1,17 @@ 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/Parsing/V2/InferenceResponse.php b/src/V2/Product/Extraction/ExtractionResponse.php similarity index 52% rename from src/Parsing/V2/InferenceResponse.php rename to src/V2/Product/Extraction/ExtractionResponse.php index cbb3ea87..10037ad0 100644 --- a/src/Parsing/V2/InferenceResponse.php +++ b/src/V2/Product/Extraction/ExtractionResponse.php @@ -1,16 +1,20 @@ inference = new Inference($rawResponse['inference']); + $this->inference = new ExtractionInference($rawResponse['inference']); } } diff --git a/src/Parsing/V2/InferenceResult.php b/src/V2/Product/Extraction/ExtractionResult.php similarity index 73% rename from src/Parsing/V2/InferenceResult.php rename to src/V2/Product/Extraction/ExtractionResult.php index 78ccaabd..9d91bbf4 100644 --- a/src/Parsing/V2/InferenceResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -1,13 +1,17 @@ rag = isset( $serverResponse['rag'] - ) ? new RagMetadata($serverResponse['rag']) : null; + ) ? new RAGMetadata($serverResponse['rag']) : null; } /** diff --git a/src/Input/DataSchema.php b/src/V2/Product/Extraction/Params/DataSchema.php similarity index 84% rename from src/Input/DataSchema.php rename to src/V2/Product/Extraction/Params/DataSchema.php index c86b1cb7..54f6de67 100644 --- a/src/Input/DataSchema.php +++ b/src/V2/Product/Extraction/Params/DataSchema.php @@ -1,9 +1,14 @@ replace = $dataSchema->replace; return; } @@ -54,7 +59,7 @@ private static function fixLineSpaces(string $line): string } $i = 0; foreach (str_split($line) as $char) { - if ($char == ' ') { + if ($char === ' ') { $i++; continue; } diff --git a/src/Parsing/V2/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php similarity index 89% rename from src/Parsing/V2/DataSchemaActiveOption.php rename to src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index 93235543..5003ab40 100644 --- a/src/Parsing/V2/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -1,6 +1,8 @@ fields = array_map(fn ($field) => new DataSchemaField($field), $serverResponse['fields']); + $this->fields = array_map(static fn($field) => new DataSchemaField($field), $serverResponse['fields']); } /** @@ -35,7 +40,7 @@ public function __construct(array $serverResponse) */ public function toJson(): array { - return [ 'fields' => array_map(fn ($field) => $field->toJson(), $this->fields)]; + return [ 'fields' => array_map(static fn($field) => $field->toJson(), $this->fields)]; } /** diff --git a/src/Input/InferenceParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php similarity index 63% rename from src/Input/InferenceParameters.php rename to src/V2/Product/Extraction/Params/ExtractionParameters.php index 1cc3f51b..16b635e8 100644 --- a/src/Input/InferenceParameters.php +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -1,13 +1,15 @@ |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. + * @param string $modelId ID of the model. + * @param boolean|null $rag Whether to enable Retrieval-Augmented Generation. + * @param boolean|null $rawText Whether to extract the full text content from the + * document as strings. + * @param boolean|null $polygon Whether to calculate bounding box polygons for all + * fields. + * @param boolean|null $confidence Whether to calculate confidence scores for all fields. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. + * @param string|null $textContext Additional text context used by the model during + * inference. + * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during + * inference. */ public function __construct( string $modelId, @@ -73,9 +74,8 @@ public function __construct( ?array $webhooksIds = null, ?string $textContext = null, DataSchema|string|array|null $dataSchema = null, - ?PollingOptions $pollingOptions = null, ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); $this->rag = $rag; $this->rawText = $rawText; @@ -111,7 +111,7 @@ public function asHash(): array $outHash['text_context'] = $this->textContext; } if (isset($this->dataSchema)) { - $outHash['data_schema'] = strval($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..50dd3b97 100644 --- a/src/V2/Product/Ocr/OcrInference.php +++ b/src/V2/Product/Ocr/OcrInference.php @@ -1,5 +1,7 @@ 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']; } diff --git a/src/V2/Product/Ocr/OcrResponse.php b/src/V2/Product/Ocr/OcrResponse.php index 1861964e..9912da67 100644 --- a/src/V2/Product/Ocr/OcrResponse.php +++ b/src/V2/Product/Ocr/OcrResponse.php @@ -1,8 +1,10 @@ pages = array_map(fn ($page) => new OcrPage($page), $rawResponse['pages']); + $this->pages = array_map(static fn($page) => new OcrPage($page), $rawResponse['pages']); } /** diff --git a/src/V2/Product/Ocr/OcrWord.php b/src/V2/Product/Ocr/OcrWord.php index 48c070ab..4f4d8e68 100644 --- a/src/V2/Product/Ocr/OcrWord.php +++ b/src/V2/Product/Ocr/OcrWord.php @@ -1,5 +1,7 @@ |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 $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Split/Params/SplitParameters.php b/src/V2/Product/Split/Params/SplitParameters.php index 7d0d61f2..8f5e790e 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 $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Split/SplitInference.php b/src/V2/Product/Split/SplitInference.php index f1071710..a601d3e2 100644 --- a/src/V2/Product/Split/SplitInference.php +++ b/src/V2/Product/Split/SplitInference.php @@ -1,5 +1,7 @@ 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; } /** diff --git a/src/V2/Product/Split/SplitResponse.php b/src/V2/Product/Split/SplitResponse.php index d012af8a..d1ba75be 100644 --- a/src/V2/Product/Split/SplitResponse.php +++ b/src/V2/Product/Split/SplitResponse.php @@ -1,8 +1,10 @@ splits = array_map(fn ($split) => new SplitRange($split), $rawResponse['splits']); + $this->splits = array_map(static fn($split) => new SplitRange($split), $rawResponse['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 +50,45 @@ protected function tearDown(): void putenv('MINDEE_API_KEY=' . $this->oldKey); } - public function testParsePathWithoutToken() + public function testParsePathWithoutToken(): void { $this->expectException(MindeeHttpClientException::class); - $inputDoc = $this->emptyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = $this->emptyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->emptyClient->parse(InvoiceV4::class, $inputDoc); } - public function testParsePathWithEnvToken() + public function testParsePathWithEnvToken(): void { $this->expectException(MindeeHttpException::class); - $inputDoc = $this->envClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = $this->envClient->sourceFromPath(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"); + $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/receipt.txt"); } - public function testParsePathWithWrongToken() + public function testParsePathWithWrongToken(): void { $this->expectException(MindeeHttpClientException::class); - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = $this->dummyClient->sourceFromPath(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 = $this->dummyClient->sourceFromPath(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(MindeeHttpClientException::class); $this->dummyClient->parse( GeneratedV1::class, $inputDoc, @@ -93,33 +96,33 @@ public function testInterfaceVersion() ); } - public function testCutOptions() + public function testCutOptions(): void { - $inputDoc = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->expectException(MindeeHttpClientException::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"); @@ -129,30 +132,30 @@ public function testPredictOptionsWrongInputType() $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"); + self::assertTrue($predictOptions->pageOptions->isEmpty()); + $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->expectException(MindeeHttpClientException::class); $this->dummyClient->parse(InvoiceV4::class, $inputDoc, $predictOptions); $this->expectException(MindeeHttpClientException::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 similarity index 56% rename from tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php rename to tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php index 766d8016..775bb962 100644 --- a/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php +++ b/tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php @@ -1,32 +1,35 @@ 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"); - new PdfExtractor($inputObj); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + new PDFExtractor($inputObj); } - public function testNoExtractedImage() + public function testNoExtractedImage(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; @@ -34,11 +37,11 @@ public function testNoExtractedImage() $saveFormat = "pdf"; new ExtractedImage($inputImage, $filename, $saveFormat, 0, 0); } - public function testNoExtractedPdf() + public function testNoExtractedPDF(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; $filename = "dummy"; - new ExtractedPdf($inputImage, $filename); + new ExtractedPDF($inputImage, $filename); } } diff --git a/tests/Dependencies/DependencyCheckerPdfTest.php b/tests/Dependencies/DependencyCheckerPDFTest.php similarity index 57% rename from tests/Dependencies/DependencyCheckerPdfTest.php rename to tests/Dependencies/DependencyCheckerPDFTest.php index ff3f59b3..22dd7ede 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..45868b52 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..13f06f46 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,61 +69,58 @@ 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) { + } catch (PdfParserException|PdfReaderException $e) { throw new MindeePDFException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, @@ -127,145 +129,145 @@ 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"); + $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"); + $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); + $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); } - public function testShouldRaiseErrorForBrokenUnfixablePdf() + public function testShouldRaiseErrorForBrokenUnfixablePDF(): void { $this->expectException(MindeeSourceException::class); - $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); + $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); } - public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf() + public function testShouldSendCorrectResultsForBrokenFixableInvoicePDF(): void { $sourceDocOriginal = $this->dummyClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' + 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 = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); + self::assertSame($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); } - public function testImageQualityCompressionFromInputSource() + public function testImageQualityCompressionFromInputSource(): void { - $receiptInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = $this->dummyClient->sourceFromPath(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 = $this->dummyClient->sourceFromPath(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,55 +278,55 @@ 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 = $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'); + 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" + 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' + 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), @@ -332,10 +334,10 @@ public function testCompressPDFFromCompressor() 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 +348,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" + 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 index bb43f4ae..275991d3 100644 --- a/tests/Input/URLInputSourceTest.php +++ b/tests/Input/URLInputSourceTest.php @@ -1,13 +1,15 @@ oldKey); } - public function testInputFromHTTPShouldNotThrow() + public function testInputFromHTTPShouldNotThrow(): void { $inputDoc = $this->dummyClient->sourceFromUrl("https://example.com/invoice.pdf"); - $this->assertInstanceOf(URLInputSource::class, $inputDoc); + self::assertInstanceOf(URLInputSource::class, $inputDoc); } - public function testInputFromHTTPShouldThrow() + public function testInputFromHTTPShouldThrow(): void { $this->expectException(MindeeSourceException::class); new URLInputSource(url: "http://example.com/invoice.pdf"); } - public function testDownloadFileFails(){ + public function testDownloadFileFails(): void + { $dummyAddress = "addressthatdoesntworkforcipurposes"; $urlSource = $this->dummyClient->sourceFromUrl("https://$dummyAddress"); $this->expectException(MindeeSourceException::class); @@ -45,7 +48,8 @@ public function testDownloadFileFails(){ $urlSource->asLocalInputSource("test.pdf"); } - public function testInvalidFileName(){ + public function testInvalidFileName(): void + { $urlSource = $this->dummyClient->sourceFromUrl("https://addressthatdoesntworkforcipurposes"); $this->expectException(MindeeSourceException::class); $this->expectExceptionMessage("Filename must end with an extension."); 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->filePath = TestingUtilities::getFileTypesDir() . "/pdf/blank_1.pdf"; $this->apiKey = getenv('MINDEE_API_KEY'); } - public function testInvalidFilePath() + public function testInvalidFilePath(): void { $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'.")); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains($cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); } - public function testInvalidKey() + public function testInvalidKey(): void { $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")); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains(implode(" ", $cmdOutput["output"]), "Invalid token provided")); } - public function testInvalidProduct() + public function testInvalidProduct(): void { $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")); + self::assertSame(1, $cmdOutput["code"]); + self::assertTrue(str_contains($cmdOutput["output"][0], "Invalid product: invalid-product")); } } diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/CLI/MindeeCLICommandTestFunctional.php index 285a8dd6..b5d287f4 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/CLI/MindeeCLICommandTestFunctional.php @@ -1,5 +1,7 @@ apiKey]; if ($initialArgs) { $args = array_merge($args, $initialArgs); @@ -33,12 +36,12 @@ private function runValidCall($productName, $async = false, $initialArgs = []): } - 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") { + if ($productName !== "custom" && $productName !== "generated") { if ($productSpecs->isSync) { $data[] = [$productName, false]; } @@ -51,13 +54,13 @@ 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( + self::assertSame(0, $cmdOutput["code"], $productName . ($async ? " async" : " sync") . " test (code)."); + self::assertTrue( str_contains($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 index b7ed9b13..b6247db1 100644 --- a/tests/V1/CLI/MindeeCLITestingUtilities.php +++ b/tests/V1/CLI/MindeeCLITestingUtilities.php @@ -1,8 +1,8 @@ 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" + TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf" ); } - public function testHTTPClientErrorShouldRaise() + public function testHTTPClientErrorShouldRaise(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->parse(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueClientException() + public function testHTTPEnqueueClientException(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPParseClientException() + public function testHTTPParseClientException(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueAndParseClientException() + public function testHTTPEnqueueAndParseClientException(): void { $this->expectException(MindeeHttpClientException::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); + self::assertSame(400, $error400->statusCode); + self::assertSame("SomeCode", $error400->apiCode); + self::assertSame("Some scary message here", $error400->apiMessage); + self::assertNull($error400->apiDetails); $this->expectException(MindeeHttpClientException::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); + 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(MindeeHttpClientException::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); + 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(MindeeHttpClientException::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); + 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(MindeeHttpClientException::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); + 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(MindeeHttpClientException::class); throw $error500; } diff --git a/tests/V1/Extraction/ImageExtractorTest.php b/tests/V1/Extraction/ImageExtractorTest.php index 15c25af3..380af8fe 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Extraction/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/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php index 064752dd..5097b008 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php @@ -1,19 +1,21 @@ enqueueAndParse(InvoiceSplitterV1::class, $invoiceSplitterInput); $inference = $response->document->inference; - $pdfExtractor = new PdfExtractor($invoiceSplitterInput); - $this->assertEquals(2, $pdfExtractor->getPageCount()); + $pdfExtractor = new PDFExtractor($invoiceSplitterInput); + 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/Extraction/PDFExtractorTest.php b/tests/V1/Extraction/PDFExtractorTest.php new file mode 100644 index 00000000..aa1c516b --- /dev/null +++ b/tests/V1/Extraction/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/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..4cb8af19 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); + $settings = new MindeeAPI("my-api-key", InvoiceSplitterV1::$endpointName); + 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); + $settings = new MindeeAPI("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); + 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 . '='); - new MindeeApi(null, InvoiceSplitterV1::$endpointName); + new MindeeAPI(null, InvoiceSplitterV1::$endpointName); } } 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 index 432de859..b672f42f 100644 --- a/tests/V1/Input/URLInputSourceTestFunctional.php +++ b/tests/V1/Input/URLInputSourceTestFunctional.php @@ -1,10 +1,13 @@ client = new Client(); - $this->outputFilePath = \TestingUtilities::getRootDataDir() . "/output/"; + $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"); + unlink(TestingUtilities::getRootDataDir() . "/output/blank_1.pdf"); + unlink(TestingUtilities::getRootDataDir() . "/output/customFileName.pdf"); } - public function testLoadLocalFile() + public function testLoadLocalFile(): void { $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); + self::assertSame(1, $result->document->nPages); + self::assertSame("blank_1.pdf", $result->document->filename); } - public function testCustomFileName() + public function testCustomFileName(): void { $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); + self::assertSame(1, $result->document->nPages); + self::assertSame("customName.pdf", $result->document->filename); } - public function testSaveFile() + public function testSaveFile(): void { $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); $urlSource->saveToFile($this->outputFilePath); - $this->assertFileExists($this->outputFilePath . "blank_1.pdf"); + self::assertFileExists($this->outputFilePath . "blank_1.pdf"); } - public function testSaveFileWithFilename() + public function testSaveFileWithFilename(): void { $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); $urlSource->saveToFile($this->outputFilePath, "customFileName.pdf"); - $this->assertFileExists($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..eddb9966 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..3b93413f 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -1,13 +1,19 @@ client->sourceFromPath( - \TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg" + TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg" ); $predictOptions = new PredictOptions(); $predictOptions->setCropper(true); @@ -30,14 +36,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" + TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" ); $predictOptions = new PredictOptions(); $predictOptions->setFullText(true); @@ -45,7 +51,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($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..90774d3d 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 new file mode 100644 index 00000000..1fa20a6d --- /dev/null +++ b/tests/V1/Parsing/Common/OCR/OCRTest.php @@ -0,0 +1,57 @@ +ocrObject = new OCR($jsonData["document"]["ocr"]); + } + public function testResponse(): void + { + $expectedText = file_get_contents( + TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" + ); + self::assertSame($expectedText, (string) ($this->ocrObject)); + self::assertSame($expectedText, (string) ($this->ocrObject->mvisionV1->pages[0])); + } + + public function testFindOneLineByRegex(): void + { + $regexFilter = '/platinum[\w\s]*\$65\.00/i'; + $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); + self::assertNotNull($matchingLines); + self::assertSame( + "Platinum web hosting package $65.00 $65.00", + (string) ($matchingLines[0][0]) + ); + } + + public function testFindMultipleLinesByRegex(): void + { + $regexFilter = '/^.*\$.*$/m'; + $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); + self::assertNotNull($matchingLines); + self::assertCount(8, $matchingLines[0]); + self::assertSame( + "Amount Due (USD): $2,608.20", + (string) ($matchingLines[0][0]) + ); + self::assertSame( + "Amount due (CAD): $2,608.20", + (string) ($matchingLines[0][7]) + ); + } +} diff --git a/tests/V1/Parsing/Common/Ocr/OcrTest.php b/tests/V1/Parsing/Common/Ocr/OcrTest.php deleted file mode 100644 index 0fd958d3..00000000 --- a/tests/V1/Parsing/Common/Ocr/OcrTest.php +++ /dev/null @@ -1,53 +0,0 @@ -ocrObject = new Ocr($jsonData["document"]["ocr"]); - } - public function testResponse() - { - $expectedText = file_get_contents( - \TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" - ); - $this->assertEquals($expectedText, strval($this->ocrObject)); - $this->assertEquals($expectedText, strval($this->ocrObject->mvisionV1->pages[0])); - } - - public function testFindOneLineByRegex() - { - $regexFilter = '/platinum[\w\s]*\$65\.00/i'; - $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals( - "Platinum web hosting package $65.00 $65.00", - strval($matchingLines[0][0]) - ); - } - - public function testFindMultipleLinesByRegex() - { - $regexFilter = '/^.*\$.*$/m'; - $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals(8, count($matchingLines[0])); - $this->assertEquals( - "Amount Due (USD): $2,608.20", - strval($matchingLines[0][0]) - ); - $this->assertEquals( - "Amount due (CAD): $2,608.20", - strval($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/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 index 9970cdc8..a4e68e53 100644 --- a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php +++ b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(BillOfLading\BillOfLadingV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BillOfLading\BillOfLadingV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(BillOfLadingV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(BillOfLadingV1::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->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); + self::assertNull($prediction->billOfLadingNumber->value); + self::assertNull($prediction->shipper->address); + self::assertNull($prediction->shipper->email); + self::assertNull($prediction->shipper->name); + self::assertNull($prediction->shipper->phone); + self::assertNull($prediction->consignee->address); + self::assertNull($prediction->consignee->email); + self::assertNull($prediction->consignee->name); + self::assertNull($prediction->consignee->phone); + self::assertNull($prediction->notifyParty->address); + self::assertNull($prediction->notifyParty->email); + self::assertNull($prediction->notifyParty->name); + self::assertNull($prediction->notifyParty->phone); + self::assertNull($prediction->carrier->name); + self::assertNull($prediction->carrier->professionalNumber); + self::assertNull($prediction->carrier->scac); + self::assertCount(0, $prediction->carrierItems); + self::assertNull($prediction->portOfLoading->value); + self::assertNull($prediction->portOfDischarge->value); + self::assertNull($prediction->placeOfDelivery->value); + self::assertNull($prediction->dateOfIssue->value); + self::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 index 2ff3f366..da3ab166 100644 --- a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php +++ b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(DeliveryNoteV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(DeliveryNoteV1::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->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); + self::assertNull($prediction->deliveryDate->value); + self::assertNull($prediction->deliveryNumber->value); + self::assertNull($prediction->supplierName->value); + self::assertNull($prediction->supplierAddress->value); + self::assertNull($prediction->customerName->value); + self::assertNull($prediction->customerAddress->value); + self::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 index 20c64e57..08b37113 100644 --- a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php +++ b/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(EnergyBill\EnergyBillV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(EnergyBill\EnergyBillV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(EnergyBillV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(EnergyBillV1::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->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); + self::assertNull($prediction->invoiceNumber->value); + self::assertNull($prediction->contractId->value); + self::assertNull($prediction->deliveryPoint->value); + self::assertNull($prediction->invoiceDate->value); + self::assertNull($prediction->dueDate->value); + self::assertNull($prediction->totalBeforeTaxes->value); + self::assertNull($prediction->totalTaxes->value); + self::assertNull($prediction->totalAmount->value); + self::assertNull($prediction->energySupplier->address); + self::assertNull($prediction->energySupplier->name); + self::assertNull($prediction->energyConsumer->address); + self::assertNull($prediction->energyConsumer->name); + self::assertCount(0, $prediction->subscription); + self::assertCount(0, $prediction->energyUsage); + self::assertCount(0, $prediction->taxesAndContributions); + self::assertNull($prediction->meterDetails->meterNumber); + self::assertNull($prediction->meterDetails->meterType); + self::assertNull($prediction->meterDetails->unit); } } diff --git a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php b/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php index b9e53ab8..cd38fe07 100644 --- a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php +++ b/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(HealthCard\HealthCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthCard\HealthCardV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(HealthCardV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(HealthCardV1::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->givenNames)); - $this->assertNull($prediction->surname->value); - $this->assertNull($prediction->socialSecurity->value); - $this->assertNull($prediction->issuanceDate->value); + self::assertCount(0, $prediction->givenNames); + self::assertNull($prediction->surname->value); + self::assertNull($prediction->socialSecurity->value); + self::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 index 1dd77e2d..5c8cbb0a 100644 --- a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php +++ b/tests/V1/Product/Fr/Payslip/PayslipV3Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(Payslip\PayslipV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Payslip\PayslipV3::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(PayslipV3::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(PayslipV3::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->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)); + self::assertNull($prediction->payPeriod->endDate); + self::assertNull($prediction->payPeriod->month); + self::assertNull($prediction->payPeriod->paymentDate); + self::assertNull($prediction->payPeriod->startDate); + self::assertNull($prediction->payPeriod->year); + self::assertNull($prediction->employee->address); + self::assertNull($prediction->employee->dateOfBirth); + self::assertNull($prediction->employee->firstName); + self::assertNull($prediction->employee->lastName); + self::assertNull($prediction->employee->phoneNumber); + self::assertNull($prediction->employee->registrationNumber); + self::assertNull($prediction->employee->socialSecurityNumber); + self::assertNull($prediction->employer->address); + self::assertNull($prediction->employer->companyId); + self::assertNull($prediction->employer->companySite); + self::assertNull($prediction->employer->nafCode); + self::assertNull($prediction->employer->name); + self::assertNull($prediction->employer->phoneNumber); + self::assertNull($prediction->employer->urssafNumber); + self::assertNull($prediction->bankAccountDetails->bankName); + self::assertNull($prediction->bankAccountDetails->iban); + self::assertNull($prediction->bankAccountDetails->swift); + self::assertNull($prediction->employment->category); + self::assertNull($prediction->employment->coefficient); + self::assertNull($prediction->employment->collectiveAgreement); + self::assertNull($prediction->employment->jobTitle); + self::assertNull($prediction->employment->positionLevel); + self::assertNull($prediction->employment->seniorityDate); + self::assertNull($prediction->employment->startDate); + self::assertCount(0, $prediction->salaryDetails); + self::assertNull($prediction->payDetail->grossSalary); + self::assertNull($prediction->payDetail->grossSalaryYtd); + self::assertNull($prediction->payDetail->incomeTaxRate); + self::assertNull($prediction->payDetail->incomeTaxWithheld); + self::assertNull($prediction->payDetail->netPaid); + self::assertNull($prediction->payDetail->netPaidBeforeTax); + self::assertNull($prediction->payDetail->netTaxable); + self::assertNull($prediction->payDetail->netTaxableYtd); + self::assertNull($prediction->payDetail->totalCostEmployer); + self::assertNull($prediction->payDetail->totalTaxesAndDeductions); + self::assertCount(0, $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 index 09e8735e..7b79bc5f 100644 --- a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php +++ b/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(IndianPassport\IndianPassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IndianPassport\IndianPassportV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(IndianPassportV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(IndianPassportV1::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->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); + self::assertNull($prediction->country->value); + self::assertNull($prediction->idNumber->value); + self::assertNull($prediction->givenNames->value); + self::assertNull($prediction->surname->value); + self::assertNull($prediction->birthDate->value); + self::assertNull($prediction->birthPlace->value); + self::assertNull($prediction->issuancePlace->value); + self::assertNull($prediction->issuanceDate->value); + self::assertNull($prediction->expiryDate->value); + self::assertNull($prediction->mrz1->value); + self::assertNull($prediction->mrz2->value); + self::assertNull($prediction->legalGuardian->value); + self::assertNull($prediction->nameOfSpouse->value); + self::assertNull($prediction->nameOfMother->value); + self::assertNull($prediction->oldPassportDateOfIssue->value); + self::assertNull($prediction->oldPassportNumber->value); + self::assertNull($prediction->oldPassportPlaceOfIssue->value); + self::assertNull($prediction->address1->value); + self::assertNull($prediction->address2->value); + self::assertNull($prediction->address3->value); + self::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 index ead37651..2972b3b1 100644 --- a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php +++ b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(NutritionFactsLabelV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(NutritionFactsLabelV1::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->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)); + self::assertNull($prediction->servingPerBox->value); + self::assertNull($prediction->servingSize->amount); + self::assertNull($prediction->servingSize->unit); + self::assertNull($prediction->calories->dailyValue); + self::assertNull($prediction->calories->per100G); + self::assertNull($prediction->calories->perServing); + self::assertNull($prediction->totalFat->dailyValue); + self::assertNull($prediction->totalFat->per100G); + self::assertNull($prediction->totalFat->perServing); + self::assertNull($prediction->saturatedFat->dailyValue); + self::assertNull($prediction->saturatedFat->per100G); + self::assertNull($prediction->saturatedFat->perServing); + self::assertNull($prediction->transFat->dailyValue); + self::assertNull($prediction->transFat->per100G); + self::assertNull($prediction->transFat->perServing); + self::assertNull($prediction->cholesterol->dailyValue); + self::assertNull($prediction->cholesterol->per100G); + self::assertNull($prediction->cholesterol->perServing); + self::assertNull($prediction->totalCarbohydrate->dailyValue); + self::assertNull($prediction->totalCarbohydrate->per100G); + self::assertNull($prediction->totalCarbohydrate->perServing); + self::assertNull($prediction->dietaryFiber->dailyValue); + self::assertNull($prediction->dietaryFiber->per100G); + self::assertNull($prediction->dietaryFiber->perServing); + self::assertNull($prediction->totalSugars->dailyValue); + self::assertNull($prediction->totalSugars->per100G); + self::assertNull($prediction->totalSugars->perServing); + self::assertNull($prediction->addedSugars->dailyValue); + self::assertNull($prediction->addedSugars->per100G); + self::assertNull($prediction->addedSugars->perServing); + self::assertNull($prediction->protein->dailyValue); + self::assertNull($prediction->protein->per100G); + self::assertNull($prediction->protein->perServing); + self::assertNull($prediction->sodium->dailyValue); + self::assertNull($prediction->sodium->per100G); + self::assertNull($prediction->sodium->perServing); + self::assertNull($prediction->sodium->unit); + self::assertCount(0, $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 index 48d3fe02..a276fa84 100644 --- a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php +++ b/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(HealthcareCard\HealthcareCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthcareCard\HealthcareCardV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(HealthcareCardV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(HealthcareCardV1::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->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); + self::assertNull($prediction->companyName->value); + self::assertNull($prediction->planName->value); + self::assertNull($prediction->memberName->value); + self::assertNull($prediction->memberId->value); + self::assertNull($prediction->issuer80840->value); + self::assertCount(0, $prediction->dependents); + self::assertNull($prediction->groupNumber->value); + self::assertNull($prediction->payerId->value); + self::assertNull($prediction->rxBin->value); + self::assertNull($prediction->rxId->value); + self::assertNull($prediction->rxGrp->value); + self::assertNull($prediction->rxPcn->value); + self::assertCount(0, $prediction->copays); + self::assertNull($prediction->enrollmentDate->value); } } diff --git a/tests/V1/Product/Us/UsMail/UsMailV3Test.php b/tests/V1/Product/Us/UsMail/UsMailV3Test.php index 38172d24..772edbf2 100644 --- a/tests/V1/Product/Us/UsMail/UsMailV3Test.php +++ b/tests/V1/Product/Us/UsMail/UsMailV3Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(UsMail\UsMailV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(UsMail\UsMailV3::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(UsMailV3::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(UsMailV3::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->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); + self::assertNull($prediction->senderName->value); + self::assertNull($prediction->senderAddress->city); + self::assertNull($prediction->senderAddress->complete); + self::assertNull($prediction->senderAddress->postalCode); + self::assertNull($prediction->senderAddress->state); + self::assertNull($prediction->senderAddress->street); + self::assertCount(0, $prediction->recipientNames); + self::assertCount(0, $prediction->recipientAddresses); + self::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..df4ad42d 100644 --- a/tests/V1/Workflow/WorkflowTestFunctional.php +++ b/tests/V1/Workflow/WorkflowTestFunctional.php @@ -1,12 +1,15 @@ workflowId = getenv('WORKFLOW_ID') ?: ''; $this->predictionType = FinancialDocumentV1::class; $this->inputSource = $this->mindeeClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . "/products/financial_document/default_sample.jpg" + 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 +41,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 +59,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 +73,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..6d7cc135 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..7c49181e 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -1,25 +1,29 @@ getProperty('mindeeApi'); $property->setAccessible(true); $property->setValue($client, $mockedApi); @@ -28,80 +32,83 @@ 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()) + $predictable = $this->createMock(MindeeAPIV2::class); + $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); - $this->assertNotNull($response, 'enqueue() must return a response'); - $this->assertInstanceOf(JobResponse::class, $response); + self::assertNotNull($response, 'enqueue() must return a response'); + self::assertInstanceOf(JobResponse::class, $response); } public function testDocumentGetJobAsync(): void { - /** @var MindeeApiV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeApiV2::class); + /** @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 { - /** @var MindeeApiV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeApiV2::class); + /** @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,24 +117,24 @@ 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( + self::assertSame( 'John Smith', $supplierName, 'Supplier name mismatch' @@ -141,10 +148,10 @@ 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) { putenv('MINDEE_V2_BASE_URL'); diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index e2e70991..c532676b 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); } 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); } 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, @@ -153,9 +156,9 @@ public function testInvalidWebhookIDsMustThrowError() try { $this->mindeeClient->enqueueInference($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); } } @@ -163,18 +166,18 @@ public function testUrlInputSourceMustNotRaiseErrors(): void { $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, + webhooksIds: [ + 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..66de7fa7 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,61 @@ 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); + self::assertNotNull($response); + self::assertCount(2, $response->inference->result->crops); $cropOperation = new Crop($inputSource); $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); - $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 + 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); - $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..0f6e1022 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 @@ -28,15 +30,15 @@ public function testProcessesSinglePageCropSplitCorrectly(): void $cropOperation = new Crop($inputSample); $extractedCrops = $cropOperation->extractCrops($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 @@ -49,20 +51,20 @@ public function testProcessesMultiPageReceiptSplitCorrectly(): void $cropOperation = new Crop($inputSample); $extractedCrops = $cropOperation->extractCrops($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..39314f38 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -1,19 +1,26 @@ 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 +51,38 @@ 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 testExtractSplitsFromPdfCorrectly(): void + 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) + array_map(static fn($s) => $s->pageRange, $response->inference->result->splits) ); - $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 +92,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..5591c26a 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->extractSplits(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->extractSplits(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..2d3dc131 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..30cae739 --- /dev/null +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -0,0 +1,442 @@ +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::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 ($field === null) { + 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->value, "'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->value, "'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->value, '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->value, '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->value); + } + + /** + * 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->value); + + $fieldSimpleFloat = $fields->get('field_simple_float'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleFloat); + self::assertIsFloat($fieldSimpleFloat->value); + + $fieldSimpleInt = $fields->get('field_simple_int'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleInt); + self::assertIsFloat($fieldSimpleInt->value); + + $fieldSimpleZero = $fields->get('field_simple_zero'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleZero); + self::assertIsFloat($fieldSimpleZero->value); + + $fieldSimpleBool = $fields->get('field_simple_bool'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleBool); + self::assertIsBool($fieldSimpleBool->value); + + $fieldSimpleNull = $fields->get('field_simple_null'); + self::assertInstanceOf(SimpleField::class, $fieldSimpleNull); + self::assertNull($fieldSimpleNull->value); + + $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->value); + + foreach ($fieldSimpleList->items as $item) { + self::assertInstanceOf(SimpleField::class, $item); + self::assertIsString($item->value); + } + + $fieldObject = $fields->get('field_object'); + self::assertInstanceOf(ObjectField::class, $fieldObject); + $fieldObjectFields = $fieldObject->fields; + self::assertCount(2, $fieldObjectFields); + foreach ($fieldObjectFields as $fieldName => $subField) { + self::assertInstanceOf(SimpleField::class, $subField); + } + + $subfield1 = $fieldObjectFields->getSimpleField('subfield_1'); + self::assertInstanceOf(SimpleField::class, $subfield1); + self::assertIsString($subfield1->value); + + $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->value); + + foreach ($fieldObjectList->items as $item) { + self::assertInstanceOf(ObjectField::class, $item); + $subfield = $item->fields->get('subfield_1'); + self::assertInstanceOf(SimpleField::class, $subfield); + self::assertIsString($subfield->value); + } + } + + /** + * 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..1bd8e662 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/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..974d29e7 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') ?: ''; } @@ -27,7 +29,6 @@ protected function setUp(): void /** * 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..784dd7fb 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 */ 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 */ 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]); } }