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/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') @@ -106,7 +112,7 @@ protected function configure() /** * @return void Sets main properties regarding polling/parsing. */ - private function configureMainOptions() + private function configureMainOptions(): void { $this->addOption( 'async', @@ -171,7 +177,7 @@ private function configureMainOptions() /** * @return void Sets custom options. */ - private function configureCustomOptions() + private function configureCustomOptions(): void { $this ->addOption( @@ -197,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(); @@ -215,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. */ @@ -276,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. */ @@ -292,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; @@ -310,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 @@ -333,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. */ @@ -351,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) @@ -410,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( @@ -426,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( @@ -440,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'; @@ -465,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( @@ -491,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; } @@ -502,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, @@ -532,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 21c34140..d2041c43 100644 --- a/bin/MindeeCLIDocuments.php +++ b/bin/MindeeCLIDocuments.php @@ -1,7 +1,36 @@ new DocumentCommandConfig( "Custom document type from docTI", - \Mindee\V1\Product\Generated\GeneratedV1::class, + GeneratedV1::class, false, true ), "barcode-reader" => new DocumentCommandConfig( "Barcode Reader", - \Mindee\V1\Product\BarcodeReader\BarcodeReaderV1::class, + BarcodeReaderV1::class, true, false ), "bill-of-lading" => new DocumentCommandConfig( "Bill of Lading", - \Mindee\V1\Product\BillOfLading\BillOfLadingV1::class, + BillOfLadingV1::class, false, true ), "business-card" => new DocumentCommandConfig( "Business Card", - \Mindee\V1\Product\BusinessCard\BusinessCardV1::class, + BusinessCardV1::class, false, true ), "cropper" => new DocumentCommandConfig( "Cropper", - \Mindee\V1\Product\Cropper\CropperV1::class, + CropperV1::class, true, false ), "delivery-note" => new DocumentCommandConfig( "Delivery note", - \Mindee\V1\Product\DeliveryNote\DeliveryNoteV1::class, + DeliveryNoteV1::class, false, true ), "driver-license" => new DocumentCommandConfig( "Driver License", - \Mindee\V1\Product\DriverLicense\DriverLicenseV1::class, + DriverLicenseV1::class, false, true ), "financial-document" => new DocumentCommandConfig( "Financial Document", - \Mindee\V1\Product\FinancialDocument\FinancialDocumentV1::class, + FinancialDocumentV1::class, true, true ), "fr-bank-account-details" => new DocumentCommandConfig( "FR Bank Account Details", - \Mindee\V1\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, + BankAccountDetailsV2::class, true, false ), "fr-carte-grise" => new DocumentCommandConfig( "FR Carte Grise", - \Mindee\V1\Product\Fr\CarteGrise\CarteGriseV1::class, + CarteGriseV1::class, true, false ), "fr-energy-bill" => new DocumentCommandConfig( "FR Energy Bill", - \Mindee\V1\Product\Fr\EnergyBill\EnergyBillV1::class, + EnergyBillV1::class, false, true ), "fr-health-card" => new DocumentCommandConfig( "FR Health Card", - \Mindee\V1\Product\Fr\HealthCard\HealthCardV1::class, + HealthCardV1::class, false, true ), "fr-carte-nationale-d-identite" => new DocumentCommandConfig( "FR Carte Nationale d'Identité", - \Mindee\V1\Product\Fr\IdCard\IdCardV2::class, + IdCardV2::class, true, false ), "fr-payslip" => new DocumentCommandConfig( "FR Payslip", - \Mindee\V1\Product\Fr\Payslip\PayslipV3::class, + PayslipV3::class, false, true ), "ind-passport-india" => new DocumentCommandConfig( "IND Passport - India", - \Mindee\V1\Product\Ind\IndianPassport\IndianPassportV1::class, + IndianPassportV1::class, false, true ), "international-id" => new DocumentCommandConfig( "International ID", - \Mindee\V1\Product\InternationalId\InternationalIdV2::class, + InternationalIdV2::class, false, true ), "invoice" => new DocumentCommandConfig( "Invoice", - \Mindee\V1\Product\Invoice\InvoiceV4::class, + InvoiceV4::class, true, true ), "invoice-splitter" => new DocumentCommandConfig( "Invoice Splitter", - \Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1::class, + InvoiceSplitterV1::class, false, true ), "multi-receipts-detector" => new DocumentCommandConfig( "Multi Receipts Detector", - \Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, + MultiReceiptsDetectorV1::class, true, false ), "nutrition-facts-label" => new DocumentCommandConfig( "Nutrition Facts Label", - \Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, + NutritionFactsLabelV1::class, false, true ), "passport" => new DocumentCommandConfig( "Passport", - \Mindee\V1\Product\Passport\PassportV1::class, + PassportV1::class, true, false ), "receipt" => new DocumentCommandConfig( "Receipt", - \Mindee\V1\Product\Receipt\ReceiptV5::class, + ReceiptV5::class, true, true ), "resume" => new DocumentCommandConfig( "Resume", - \Mindee\V1\Product\Resume\ResumeV1::class, + ResumeV1::class, false, true ), "us-bank-check" => new DocumentCommandConfig( "US Bank Check", - \Mindee\V1\Product\Us\BankCheck\BankCheckV1::class, + BankCheckV1::class, true, false ), "us-healthcare-card" => new DocumentCommandConfig( "US Healthcare Card", - \Mindee\V1\Product\Us\HealthcareCard\HealthcareCardV1::class, + HealthcareCardV1::class, false, true ), "us-us-mail" => new DocumentCommandConfig( "US US Mail", - \Mindee\V1\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/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/ClientOptions/PollingOptions.php b/src/ClientOptions/PollingOptions.php index 99f4b5f1..a7ded11a 100644 --- a/src/ClientOptions/PollingOptions.php +++ b/src/ClientOptions/PollingOptions.php @@ -1,5 +1,7 @@ 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 1045305f..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 index 6c8e003d..d2874e85 100644 --- a/src/Extraction/ExtractedPDF.php +++ b/src/Extraction/ExtractedPDF.php @@ -1,5 +1,7 @@ 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 index e6e6b39c..a11f7fb1 100644 --- a/src/Extraction/PDFExtractor.php +++ b/src/Extraction/PDFExtractor.php @@ -1,5 +1,7 @@ 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]); @@ -81,8 +90,8 @@ public function getPageCount(): int * * @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,9 +125,9 @@ 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); @@ -133,7 +142,7 @@ public function extractSubDocuments(mixed $pageIndexes): array * Extracts invoices as complete PDFs from the document. * * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. - * @param 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 */ @@ -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 e88dedba..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 5ec84f23..b244772a 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/PDF/PDFCompressor.php @@ -1,5 +1,7 @@ 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."); @@ -66,8 +73,8 @@ public static function compress( $fpdi = new CustomFPDI(); $pageCount = $fpdi->setSourceFile($pdfPath); } catch (CrossReferenceException) { - error_log("[WARNING] PDF format for '$pdfPath' is not directly supported." . - " Output PDF will be rasterized and source text won't be available."); + 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); @@ -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, @@ -210,7 +215,7 @@ private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): v 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 63047e35..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; } @@ -115,8 +121,8 @@ 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/SummaryHelper.php b/src/Parsing/SummaryHelper.php index c9c54381..76b43d38 100644 --- a/src/Parsing/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -1,7 +1,12 @@ 0 ? $endpointVersion : '1'; + $endpointVersion = $endpointVersion !== null && strlen($endpointVersion) > 0 ? $endpointVersion : '1'; $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); @@ -168,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 { @@ -185,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 @@ -200,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 @@ -214,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"; } @@ -239,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); } @@ -251,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( @@ -275,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. */ @@ -315,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, @@ -365,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. */ @@ -404,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, @@ -416,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, ); @@ -432,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( @@ -447,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, ); @@ -471,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); @@ -479,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, @@ -491,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, @@ -503,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); @@ -518,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. */ @@ -561,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, @@ -573,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/V1/ClientOptions/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php index adeee460..b4d6846b 100644 --- a/src/V1/ClientOptions/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -1,5 +1,7 @@ predictOptions = $predictOptions; return $this; @@ -64,7 +66,7 @@ public function setPredictOptions(PredictOptions $predictOptions): PredictMethod * @param WorkflowOptions $workflowOptions Prediction Options. * @return $this */ - public function setWorkflowOptions(WorkflowOptions $workflowOptions): PredictMethodOptions + public function setWorkflowOptions(WorkflowOptions $workflowOptions): self { $this->workflowOptions = $workflowOptions; return $this; @@ -74,7 +76,7 @@ public function setWorkflowOptions(WorkflowOptions $workflowOptions): PredictMet * @param PageOptions $pageOptions Page Options. * @return $this */ - public function setPageOptions(PageOptions $pageOptions): PredictMethodOptions + public function setPageOptions(PageOptions $pageOptions): self { $this->pageOptions = $pageOptions; return $this; @@ -84,7 +86,7 @@ public function setPageOptions(PageOptions $pageOptions): PredictMethodOptions * @param Endpoint $customEndpoint Endpoint. * @return $this */ - public function setEndpoint(Endpoint $customEndpoint): PredictMethodOptions + public function setEndpoint(Endpoint $customEndpoint): self { $this->endpoint = $customEndpoint; return $this; @@ -94,7 +96,7 @@ public function setEndpoint(Endpoint $customEndpoint): PredictMethodOptions * @param boolean $rag Whether to enable Retrieval-Augmented Generation. * @return $this */ - public function setRag(bool $rag): PredictMethodOptions + public function setRag(bool $rag): self { $this->rag = $rag; return $this; @@ -106,7 +108,7 @@ public function setRag(bool $rag): PredictMethodOptions * @param string $workflowId The unique workflow ID to be set. * @return $this */ - public function setWorkflowId(string $workflowId): PredictMethodOptions + public function setWorkflowId(string $workflowId): self { $this->workflowId = $workflowId; return $this; diff --git a/src/V1/ClientOptions/PredictOptions.php b/src/V1/ClientOptions/PredictOptions.php index f13df923..99ccb908 100644 --- a/src/V1/ClientOptions/PredictOptions.php +++ b/src/V1/ClientOptions/PredictOptions.php @@ -1,5 +1,7 @@ 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/V1/ClientOptions/WorkflowOptions.php b/src/V1/ClientOptions/WorkflowOptions.php index 672eda87..051ae962 100644 --- a/src/V1/ClientOptions/WorkflowOptions.php +++ b/src/V1/ClientOptions/WorkflowOptions.php @@ -1,5 +1,7 @@ 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/V1/HTTP/BaseEndpoint.php b/src/V1/HTTP/BaseEndpoint.php index 29b64073..1c464083 100644 --- a/src/V1/HTTP/BaseEndpoint.php +++ b/src/V1/HTTP/BaseEndpoint.php @@ -1,5 +1,7 @@ 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/V1/HTTP/MindeeWorkflowAPI.php b/src/V1/HTTP/MindeeWorkflowAPI.php index 38a57953..0603dd8e 100644 --- a/src/V1/HTTP/MindeeWorkflowAPI.php +++ b/src/V1/HTTP/MindeeWorkflowAPI.php @@ -1,5 +1,7 @@ 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/V1/HTTP/ResponseValidation.php b/src/V1/HTTP/ResponseValidation.php index 047ce24d..9d1838e7 100644 --- a/src/V1/HTTP/ResponseValidation.php +++ b/src/V1/HTTP/ResponseValidation.php @@ -1,11 +1,16 @@ 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/V1/HTTP/WorkflowEndpoint.php b/src/V1/HTTP/WorkflowEndpoint.php index 16932d5f..71513783 100644 --- a/src/V1/HTTP/WorkflowEndpoint.php +++ b/src/V1/HTTP/WorkflowEndpoint.php @@ -1,5 +1,7 @@ $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/V1/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php index 6d115454..d90e7841 100644 --- a/src/V1/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Common/ExecutionFile.php b/src/V1/Parsing/Common/ExecutionFile.php index f51abaa1..cccbf777 100644 --- a/src/V1/Parsing/Common/ExecutionFile.php +++ b/src/V1/Parsing/Common/ExecutionFile.php @@ -1,5 +1,7 @@ croppings as $cropping) { - $croppingsStr[] = strval($cropping); + $croppingsStr[] = (string) $cropping; } return implode("\n ", $croppingsStr); } diff --git a/src/V1/Parsing/Common/Extras/Extras.php b/src/V1/Parsing/Common/Extras/Extras.php index c9ef071c..2533115b 100644 --- a/src/V1/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Common/Extras/FullTextOcrExtra.php b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php index 65c9b4b4..8ac7d292 100644 --- a/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Common/Job.php b/src/V1/Parsing/Common/Job.php index 660de4cc..fbe468d5 100644 --- a/src/V1/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/V1/Parsing/Common/OCR/MVisionV1.php b/src/V1/Parsing/Common/OCR/MVisionV1.php index 79cf8501..cab967ec 100644 --- a/src/V1/Parsing/Common/OCR/MVisionV1.php +++ b/src/V1/Parsing/Common/OCR/MVisionV1.php @@ -1,5 +1,7 @@ pages as $page) { - $pagesStr[] = strval($page); + $pagesStr[] = (string) $page; } return implode("\n", $pagesStr); } diff --git a/src/V1/Parsing/Common/OCR/OCR.php b/src/V1/Parsing/Common/OCR/OCR.php index 9b610afb..12df313d 100644 --- a/src/V1/Parsing/Common/OCR/OCR.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -1,7 +1,12 @@ 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/V1/Parsing/Common/OCR/OCRLine.php b/src/V1/Parsing/Common/OCR/OCRLine.php index 56dbca1d..29873168 100644 --- a/src/V1/Parsing/Common/OCR/OCRLine.php +++ b/src/V1/Parsing/Common/OCR/OCRLine.php @@ -1,7 +1,11 @@ words, "Mindee\\V1\\Parsing\\Common\\OCR\\OCRPage::getMinMaxX"); } @@ -34,9 +37,8 @@ public function sortOnX() * Appends a word to the line. * * @param OCRWord $word Word to add. - * @return void */ - public function add(OCRWord $word) + public function add(OCRWord $word): void { $this->words[] = $word; } diff --git a/src/V1/Parsing/Common/OCR/OCRPage.php b/src/V1/Parsing/Common/OCR/OCRPage.php index 67e4b783..efaf492a 100644 --- a/src/V1/Parsing/Common/OCR/OCRPage.php +++ b/src/V1/Parsing/Common/OCR/OCRPage.php @@ -1,7 +1,12 @@ polygon->getMinMaxX()->getMin(); $word2X = $word2->polygon->getMinMaxX()->getMin(); - if ($word1X == $word2X) { + if ($word1X === $word2X) { return 0; } return $word1X < $word2X ? -1 : 1; @@ -58,7 +63,7 @@ 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 { @@ -78,8 +82,8 @@ private function toLines(): array $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(); @@ -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 { @@ -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/V1/Parsing/Common/OCR/OCRWord.php b/src/V1/Parsing/Common/OCR/OCRWord.php index 1ac5d46c..24cc03d4 100644 --- a/src/V1/Parsing/Common/OCR/OCRWord.php +++ b/src/V1/Parsing/Common/OCR/OCRWord.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Common/Page.php b/src/V1/Parsing/Common/Page.php index 2c7f7b05..d2aa4626 100644 --- a/src/V1/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Generated/GeneratedObjectField.php b/src/V1/Parsing/Generated/GeneratedObjectField.php index 37fb3555..cdff6a03 100644 --- a/src/V1/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -1,9 +1,16 @@ 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/V1/Parsing/Standard/AddressField.php b/src/V1/Parsing/Standard/AddressField.php index 2a4e718d..1825ba4e 100644 --- a/src/V1/Parsing/Standard/AddressField.php +++ b/src/V1/Parsing/Standard/AddressField.php @@ -1,5 +1,7 @@ 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/V1/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php index 56860288..d8701c90 100644 --- a/src/V1/Parsing/Standard/BaseField.php +++ b/src/V1/Parsing/Standard/BaseField.php @@ -1,7 +1,11 @@ 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/V1/Parsing/Standard/BooleanField.php b/src/V1/Parsing/Standard/BooleanField.php index d2c9d039..2784b79b 100644 --- a/src/V1/Parsing/Standard/BooleanField.php +++ b/src/V1/Parsing/Standard/BooleanField.php @@ -1,5 +1,7 @@ confidence = $rawPrediction['confidence']; diff --git a/src/V1/Parsing/Standard/FieldPositionMixin.php b/src/V1/Parsing/Standard/FieldPositionMixin.php index dffd45cd..5105cbbe 100644 --- a/src/V1/Parsing/Standard/FieldPositionMixin.php +++ b/src/V1/Parsing/Standard/FieldPositionMixin.php @@ -1,10 +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/V1/Parsing/Standard/LocaleField.php b/src/V1/Parsing/Standard/LocaleField.php index 53c43b1e..eddd61db 100644 --- a/src/V1/Parsing/Standard/LocaleField.php +++ b/src/V1/Parsing/Standard/LocaleField.php @@ -1,7 +1,11 @@ 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/V1/Parsing/Standard/PaymentDetailsField.php b/src/V1/Parsing/Standard/PaymentDetailsField.php index dc9e6d22..d8be70aa 100644 --- a/src/V1/Parsing/Standard/PaymentDetailsField.php +++ b/src/V1/Parsing/Standard/PaymentDetailsField.php @@ -1,7 +1,12 @@ 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/V1/Parsing/Standard/StringField.php b/src/V1/Parsing/Standard/StringField.php index 1ca7e6b9..e16b872f 100644 --- a/src/V1/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/V1/Parsing/Standard/Taxes.php b/src/V1/Parsing/Standard/Taxes.php index 4bfcfdc3..935bff89 100644 --- a/src/V1/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 index b0a7dda3..60a06730 100644 --- a/src/V1/Parsing/SummaryHelperV1.php +++ b/src/V1/Parsing/SummaryHelperV1.php @@ -1,5 +1,7 @@ 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"] ); } diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1.php b/src/V1/Product/BillOfLading/BillOfLadingV1.php index 54ed298f..f5c5ce7c 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1.php @@ -1,5 +1,7 @@ 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->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"]) ? - floatval($rawPrediction["quantity"]) : null; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; $this->weightUnit = $rawPrediction["weight_unit"] ?? null; } /** * Return values for printing inside an RST table. * - * @return array */ private function tablePrintableValues(): array { @@ -78,7 +79,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -94,7 +94,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index 89b38c3c..fdaeb392 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -1,15 +1,19 @@ 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 diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index 25376e97..0ad3fd4b 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -1,5 +1,7 @@ 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"])) { diff --git a/src/V1/Product/Cropper/CropperV1.php b/src/V1/Product/Cropper/CropperV1.php index 51718551..536e8032 100644 --- a/src/V1/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -1,5 +1,7 @@ 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"] ); } diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php index 57232190..cde32f1b 100644 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php index c1722c8f..04377842 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -1,5 +1,7 @@ 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->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"]) ? - floatval($rawPrediction["unit_price"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; } /** * Return values for printing inside an RST table. * - * @return array */ private function tablePrintableValues(): array { @@ -92,7 +93,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -110,7 +110,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index ca69c2e1..cdfb1ce1 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -1,15 +1,19 @@ bban != null ? $this->bban->toFieldList() : ""; + $bbanToFieldList = $this->bban !== null ? $this->bban->toFieldList() : ""; $outStr = ":Account Holder's Names: $this->accountHoldersNames :Basic Bank Account Number: $bbanToFieldList diff --git a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index d1557163..0715991a 100644 --- a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php index 3ebf9b14..b7bc5164 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php @@ -1,5 +1,7 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->consumption = isset($rawPrediction["consumption"]) ? - floatval($rawPrediction["consumption"]) : null; + $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"]) ? - floatval($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) ? - floatval($rawPrediction["total"]) : 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"]) ? - floatval($rawPrediction["unit_price"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; } /** * Return values for printing inside an RST table. * - * @return array */ private function tablePrintableValues(): array { @@ -91,7 +92,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -109,7 +109,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 8a100ab5..9c782786 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -1,15 +1,19 @@ 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; + $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. * - * @return array */ private function tablePrintableValues(): array { @@ -78,7 +79,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -94,7 +94,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index 91d16dde..1f2c2416 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -1,15 +1,19 @@ 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; + $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. * - * @return array */ private function tablePrintableValues(): array { @@ -78,7 +79,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -94,7 +94,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 167d4354..2a0a3e95 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.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["issuance_date"])) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV1.php b/src/V1/Product/Fr/IdCard/IdCardV1.php index 15049893..9d53b4e3 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -1,5 +1,7 @@ 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"])) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV1Page.php b/src/V1/Product/Fr/IdCard/IdCardV1Page.php index 05c7cdd0..96024e7b 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -1,5 +1,7 @@ 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"])) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV2Page.php b/src/V1/Product/Fr/IdCard/IdCardV2Page.php index d8bcea68..92824cab 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php index a557d7cc..c1d0d17a 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php @@ -1,5 +1,7 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->accrued = isset($rawPrediction["accrued"]) ? - floatval($rawPrediction["accrued"]) : null; + $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"]) ? - floatval($rawPrediction["remaining"]) : null; - $this->used = isset($rawPrediction["used"]) ? - floatval($rawPrediction["used"]) : 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. * - * @return array */ private function tablePrintableValues(): array { @@ -72,7 +73,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -87,7 +87,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index 49c44c9e..c6ae3cfe 100644 --- a/src/V1/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 { @@ -109,7 +110,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -129,7 +129,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index 6a2999cb..bb824668 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -1,5 +1,7 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) ? - floatval($rawPrediction["amount"]) : null; - $this->base = isset($rawPrediction["base"]) ? - floatval($rawPrediction["base"]) : null; + $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"]) ? - floatval($rawPrediction["number"]) : null; - $this->rate = isset($rawPrediction["rate"]) ? - floatval($rawPrediction["rate"]) : 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. * - * @return array */ private function tablePrintableValues(): array { @@ -73,7 +74,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -88,7 +88,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index 074332b3..b8534e43 100644 --- a/src/V1/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/V1/Product/Generated/GeneratedV1Page.php b/src/V1/Product/Generated/GeneratedV1Page.php index b8fc6c1a..a5ec62e1 100644 --- a/src/V1/Product/Generated/GeneratedV1Page.php +++ b/src/V1/Product/Generated/GeneratedV1Page.php @@ -1,11 +1,17 @@ {$fieldName} = $fieldContentsStr['value'] . ".0"; } else { - $fieldContentsStr['value'] = strval($fieldContents['value']); + $fieldContentsStr['value'] = (string) ($fieldContents['value']); } } else { $fieldContentsStr['value'] = null; diff --git a/src/V1/Product/Generated/GeneratedV1Prediction.php b/src/V1/Product/Generated/GeneratedV1Prediction.php index 94071663..36381bfd 100644 --- a/src/V1/Product/Generated/GeneratedV1Prediction.php +++ b/src/V1/Product/Generated/GeneratedV1Prediction.php @@ -1,5 +1,7 @@ values[$i]}\n"; + ) + . "{$fieldValue->values[$i]}\n"; } } $strValue = rtrim($strValue); } else { - $strValue = strval($fieldValue); + $strValue = (string) $fieldValue; } $outStr .= ":{$fieldName}: {$strValue}\n"; } diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php index e226ba9b..b28bbcfd 100644 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php @@ -1,5 +1,7 @@ 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"] ); } diff --git a/src/V1/Product/Invoice/InvoiceV4.php b/src/V1/Product/Invoice/InvoiceV4.php index 6a71817d..52d05382 100644 --- a/src/V1/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php index 1fc175e9..016a73e3 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItem.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -1,5 +1,7 @@ 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->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"]) ? - floatval($rawPrediction["unit_price"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; } /** * Return values for printing inside an RST table. * - * @return array */ private function tablePrintableValues(): array { @@ -92,7 +93,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -110,7 +110,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php index fe934b74..2cd8f84e 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -1,15 +1,19 @@ invoicePageGroups); + $invoicePageGroupsSummary = (string) ($this->invoicePageGroups); $outStr = ":Invoice Page Groups: $invoicePageGroupsSummary "; diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index 7abd3232..58ca99fe 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -1,5 +1,7 @@ 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"] ); } diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php index d2631236..f966c8cc 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index ae7801a1..25e3f0f5 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 1666d7d4..65d6f30f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index 1bc987f2..89cfbe7b 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php index ae63f951..27f8f65b 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php index e0898968..4eee0bf5 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php @@ -1,5 +1,7 @@ setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) ? - floatval($rawPrediction["daily_value"]) : null; + $this->dailyValue = isset($rawPrediction["daily_value"]) + ? (float) ($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->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 { @@ -72,7 +73,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -87,7 +87,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 657adba0..17cf7bb1 100644 --- a/src/V1/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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index 21512f28..e2b4411c 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index 7513fb0d..a3330f4d 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -1,5 +1,7 @@ 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 { @@ -52,7 +53,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -64,7 +64,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index 4c8a4064..9a3732d6 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -1,5 +1,7 @@ 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 { @@ -66,7 +67,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -80,7 +80,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index f5c3f2db..3f19e755 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index 7915d6c1..d6a9722b 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index c2ee82ac..12efdc4d 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index a5c973f8..a62150fa 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -1,5 +1,7 @@ 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 { @@ -60,7 +61,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -73,7 +73,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in a field list. * - * @return string */ public function toFieldList(): string { diff --git a/src/V1/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php index ef460a7b..a0341058 100644 --- a/src/V1/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -1,5 +1,7 @@ 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"])) { diff --git a/src/V1/Product/Receipt/ReceiptV5.php b/src/V1/Product/Receipt/ReceiptV5.php index d6e29029..9eb95949 100644 --- a/src/V1/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php index 01d62900..c20758fc 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItem.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -1,5 +1,7 @@ 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; + $this->quantity = isset($rawPrediction["quantity"]) + ? (float) ($rawPrediction["quantity"]) : null; + $this->totalAmount = isset($rawPrediction["total_amount"]) + ? (float) ($rawPrediction["total_amount"]) : null; + $this->unitPrice = isset($rawPrediction["unit_price"]) + ? (float) ($rawPrediction["unit_price"]) : null; } /** * Return values for printing inside an RST table. * - * @return array */ private function tablePrintableValues(): array { @@ -66,7 +67,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -80,7 +80,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php index a6ac2077..0f2a2ecc 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.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 diff --git a/src/V1/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php index e4801161..811f24ed 100644 --- a/src/V1/Product/Resume/ResumeV1Education.php +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -1,5 +1,7 @@ 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"])) { diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 9b204900..32a80475 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -1,5 +1,7 @@ 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"] ); } diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php index 8f97a490..16f992b8 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php @@ -1,5 +1,7 @@ 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 { @@ -52,7 +53,6 @@ private function tablePrintableValues(): array /** * Return values for printing as an array. * - * @return array */ private function printableValues(): array { @@ -64,7 +64,6 @@ private function printableValues(): array /** * Output in a format suitable for inclusion in an rST table. * - * @return string */ public function toTableLine(): string { diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index 29bfbe0c..880a53e5 100644 --- a/src/V1/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 diff --git a/src/V1/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php index 0dd5ed7b..2a151540 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3.php +++ b/src/V1/Product/Us/UsMail/UsMailV3.php @@ -1,5 +1,7 @@ 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 diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index ebcdd5df..ccfcbf6c 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -1,5 +1,7 @@ $responseClass - * @param string $resultUrl URL of the result. + * @param string $resultUrl URL of the result. * @return BaseResponse A response containing parsing results. */ public function getResultFromUrl( @@ -84,7 +86,7 @@ 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. + * @param string $resultId ID of the result. * @return BaseResponse A response containing parsing results. */ public function getResult( @@ -112,10 +114,10 @@ public function getJob(string $jobId): JobResponse * 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. + * @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. @@ -153,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); @@ -170,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 f175d564..c54c6b33 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -1,7 +1,11 @@ |null $webhooksIds List of webhook IDs. */ public function __construct(string $modelId, ?string $alias, ?array $webhooksIds) 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 2d0371c1..93015574 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -1,5 +1,7 @@ localInput); - $expandedPageIndexes = array_map(fn (array $split) => self::expandRange($split[0], $split[1]), $splits); + $expandedPageIndexes = array_map(static fn(array $split) => self::expandRange($split[0], $split[1]), $splits); return new SplitFiles(...$pdfExtractor->extractSubDocuments($expandedPageIndexes)); } diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index fe2935ce..50b11f49 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -1,16 +1,24 @@ + * * @extends ArrayObject */ -class SplitFiles extends \ArrayObject +class SplitFiles extends ArrayObject { /** * Builds a new SplitFiles collection. @@ -25,11 +33,10 @@ public function __construct(ExtractedPDF ...$items) /** * Save all extracted splits to disk. * - * @param string $path The directory path to save the extracted splits to. + * @param string $path The directory path to save the extracted splits to. * @param string $prefix Prefix to add to the filename. * * @throws MindeeException If directory creation fails. - * @return void */ public function saveAllToDisk(string $path, string $prefix = 'split'): void { @@ -48,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/V2/HTTP/MindeeAPIV2.php b/src/V2/HTTP/MindeeAPIV2.php index 0a68fb24..eba9adf8 100644 --- a/src/V2/HTTP/MindeeAPIV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -1,5 +1,7 @@ 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 ); } @@ -113,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 { @@ -123,7 +126,6 @@ protected function setBaseUrl(string $value): void /** * Sets values from environment, if needed. * - * @return void */ private function setFromEnv(): void { @@ -132,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.'); @@ -145,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 { @@ -159,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 @@ -180,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. */ @@ -253,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. @@ -284,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. */ @@ -344,9 +345,8 @@ private function sendGetRequest(string $url): array /** * Starts a CURL session using POST. * - * @param InputSource $inputSource File to upload. - * @param BaseParameters $params 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( @@ -381,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 3195b931..d25df119 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -1,5 +1,7 @@ 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/V2/Parsing/Inference/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php index 3f762d17..5ec3ab3e 100644 --- a/src/V2/Parsing/Inference/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -1,5 +1,7 @@ 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/V2/Parsing/Inference/Field/ListField.php b/src/V2/Parsing/Inference/Field/ListField.php index 747ecf85..5fb69016 100644 --- a/src/V2/Parsing/Inference/Field/ListField.php +++ b/src/V2/Parsing/Inference/Field/ListField.php @@ -1,9 +1,15 @@ fields->get($key); - if (!($field instanceof ObjectField)) { + if (!($field instanceof self)) { throw new InvalidArgumentException("Field $key is not a simple field."); } return $field; @@ -138,7 +134,7 @@ public function getObjectFields(): array { $out = []; foreach ($this->fields->getArrayCopy() as $field) { - if ($field instanceof ObjectField) { + if ($field instanceof self) { $out[] = $field; } } diff --git a/src/V2/Parsing/Inference/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php index 910706d5..be162ce7 100644 --- a/src/V2/Parsing/Inference/Field/SimpleField.php +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -1,7 +1,13 @@ 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/V2/Parsing/Inference/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php index c3b6b8df..edb8ce8d 100644 --- a/src/V2/Parsing/Inference/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -1,5 +1,7 @@ documentType = $rawPrediction['document_type']; - $this->extractionResponse = isset($rawPrediction['extraction_response']) ? - new ExtractionResponse($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 1d922c85..5ee94dab 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.php @@ -1,5 +1,7 @@ |null $webhooksIds List of webhook IDs. */ public function __construct( 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 ExtractionResponse($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 434d7564..f0a08c62 100644 --- a/src/V2/Product/Crop/CropResponse.php +++ b/src/V2/Product/Crop/CropResponse.php @@ -1,5 +1,7 @@ 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 077836e1..1daacedb 100644 --- a/src/V2/Product/Crop/Params/CropParameters.php +++ b/src/V2/Product/Crop/Params/CropParameters.php @@ -1,5 +1,7 @@ |null $webhooksIds List of webhook IDs. */ public function __construct( diff --git a/src/V2/Product/Extraction/ExtractionInference.php b/src/V2/Product/Extraction/ExtractionInference.php index b46f7587..83027850 100644 --- a/src/V2/Product/Extraction/ExtractionInference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -1,5 +1,7 @@ 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/V2/Product/Extraction/Params/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index 247e6f19..5003ab40 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -1,5 +1,7 @@ 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/V2/Product/Extraction/Params/ExtractionParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php index 87f9a4fe..16b635e8 100644 --- a/src/V2/Product/Extraction/Params/ExtractionParameters.php +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -1,5 +1,7 @@ |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 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, @@ -109,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 4c5f47d8..9912da67 100644 --- a/src/V2/Product/Ocr/OcrResponse.php +++ b/src/V2/Product/Ocr/OcrResponse.php @@ -1,5 +1,7 @@ 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. */ public function __construct( diff --git a/src/V2/Product/Split/Params/SplitParameters.php b/src/V2/Product/Split/Params/SplitParameters.php index 9571b7cc..8f5e790e 100644 --- a/src/V2/Product/Split/Params/SplitParameters.php +++ b/src/V2/Product/Split/Params/SplitParameters.php @@ -1,5 +1,7 @@ |null $webhooksIds List of webhook IDs. */ public function __construct( 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 ExtractionResponse($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 4d315db0..d1ba75be 100644 --- a/src/V2/Product/Split/SplitResponse.php +++ b/src/V2/Product/Split/SplitResponse.php @@ -1,5 +1,7 @@ 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 eb4e7782..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 index 2dd31ce2..775bb962 100644 --- a/tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php +++ b/tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php @@ -1,5 +1,7 @@ expectException(MindeeUnhandledException::class); - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); new ImageExtractor($inputObj); } - public function testNoPDFExtractor() + public function testNoPDFExtractor(): void { $this->expectException(MindeeUnhandledException::class); - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); new PDFExtractor($inputObj); } - public function testNoExtractedImage() + public function testNoExtractedImage(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; @@ -34,7 +37,7 @@ public function testNoExtractedImage() $saveFormat = "pdf"; new ExtractedImage($inputImage, $filename, $saveFormat, 0, 0); } - public function testNoExtractedPDF() + public function testNoExtractedPDF(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; diff --git a/tests/Dependencies/DependencyCheckerPDFTest.php b/tests/Dependencies/DependencyCheckerPDFTest.php index 4fa6b1d0..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 413e4ad0..13f06f46 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -1,5 +1,7 @@ assertEquals(12, $inputObj->getPageCount()); + self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFReconstructOK() + public function testPDFReconstructOK(): void { $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"); $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->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" ); $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"); $basePdf->setSourceFile($inputObj->fileObject->getFilename()); @@ -116,7 +120,7 @@ public function testPDFCutNPages(array $indexes) } $basePdf->Close(); $cutPdf->Close(); - } catch (PdfParserException | PdfReaderException $e) { + } catch (PdfParserException|PdfReaderException $e) { throw new MindeePDFException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, @@ -125,55 +129,55 @@ 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->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->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->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->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->applyPageOptions(new PageOptions([16], REMOVE, 2)); - $this->assertEquals(12, $inputObj->getPageCount()); + self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFKeepNoPages() + public function testPDFKeepNoPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->expectException(MindeePDFException::class); $inputObj->applyPageOptions(new PageOptions([], KEEP_ONLY, 2)); } - public function testPDFRemoveAllPages() + public function testPDFRemoveAllPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->expectException(MindeePDFException::class); @@ -181,59 +185,59 @@ public function testPDFRemoveAllPages() $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"); $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"); $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"); $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); } - public function testShouldRaiseErrorForBrokenUnfixablePDF() + public function testShouldRaiseErrorForBrokenUnfixablePDF(): void { $this->expectException(MindeeSourceException::class); $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' ); $sourceDocFixed = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); - $this->assertEquals($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); + self::assertSame($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); } - public function testImageQualityCompressionFromInputSource() + public function testImageQualityCompressionFromInputSource(): void { $receiptInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $receiptInput->compress(80); @@ -243,10 +247,10 @@ public function testImageQualityCompressionFromInputSource() ); $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg"); - $this->assertGreaterThan($sizeCompressed, $sizeOriginal); + 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'); @@ -255,7 +259,7 @@ public function testDirectImageQualityCompression() 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 = [ @@ -274,29 +278,29 @@ 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."); + 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" ); - $this->assertFalse($pdfInput->hasSourceText()); + self::assertFalse($pdfInput->hasSourceText()); file_put_contents( TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", @@ -304,7 +308,7 @@ public function testCompressPDFFromInputSource() ); $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/pdf/not_blank_image_only.pdf'); $sizeIgnored = filesize(TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf"); - $this->assertEquals($sizeIgnored, $sizeOriginal); + self::assertSame($sizeIgnored, $sizeOriginal); $pdfInput->compress(90, null, null, true, false); file_put_contents( @@ -312,17 +316,17 @@ public function testCompressPDFFromInputSource() file_get_contents($pdfInput->fileObject->getFilename()) ); $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . '/output/compress_indirect.pdf'); - $this->assertLessThan($sizeOriginal, $sizeCompressed); + self::assertLessThan($sizeOriginal, $sizeCompressed); } - public function testCompressPDFFromCompressor() + public function testCompressPDFFromCompressor(): void { $pdfInput = $this->dummyClient->sourceFromPath( 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), @@ -344,20 +348,20 @@ 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" ); - $this->assertTrue($pdfInput->hasSourceText()); + self::assertTrue($pdfInput->hasSourceText()); $pdfInput->compress(5, null, null, true, false); file_put_contents( @@ -366,9 +370,9 @@ public function testSourceTextPDFCompression() ); $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $sizeTextCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); - $this->assertEquals($sizeTextCompressed, $sizeOriginal); + self::assertSame($sizeTextCompressed, $sizeOriginal); - $this->assertEquals( + self::assertSame( str_repeat('*', 650), implode('', str_replace(" ", "", PDFUtils::extractPagesTextElements(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) ); diff --git a/tests/Input/URLInputSourceTest.php b/tests/Input/URLInputSourceTest.php index a3c05e99..275991d3 100644 --- a/tests/Input/URLInputSourceTest.php +++ b/tests/Input/URLInputSourceTest.php @@ -1,11 +1,14 @@ 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); @@ -44,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"]); - $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 d38c2451..380af8fe 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Extraction/ImageExtractorTest.php @@ -1,5 +1,7 @@ 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 ea698572..5097b008 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php @@ -1,5 +1,7 @@ enqueueAndParse(InvoiceSplitterV1::class, $invoiceSplitterInput); $inference = $response->document->inference; $pdfExtractor = new PDFExtractor($invoiceSplitterInput); - $this->assertEquals(2, $pdfExtractor->getPageCount()); + self::assertSame(2, $pdfExtractor->getPageCount()); $extractedPdfsStrict = $pdfExtractor->extractInvoices($inference->prediction->invoicePageGroups); - $this->assertCount(2, $extractedPdfsStrict); - $this->assertEquals('default_sample_001-001.pdf', $extractedPdfsStrict[0]->getFilename()); - $this->assertEquals('default_sample_002-002.pdf', $extractedPdfsStrict[1]->getFilename()); + self::assertCount(2, $extractedPdfsStrict); + self::assertSame('default_sample_001-001.pdf', $extractedPdfsStrict[0]->getFilename()); + self::assertSame('default_sample_002-002.pdf', $extractedPdfsStrict[1]->getFilename()); $invoice0 = $client->parse(InvoiceV4::class, $extractedPdfsStrict[0]->asInputSource()); @@ -54,11 +56,11 @@ public function testPDFShouldExtractInvoicesStrict() invoicePrediction: $invoice0->document ); - $this->assertGreaterThan( + self::assertGreaterThan( 0.90, TestingUtilities::levenshteinRatio( $testStringRstInvoice0, - (string)$invoice0->document + (string) $invoice0->document ) ); } diff --git a/tests/V1/Extraction/PDFExtractorTest.php b/tests/V1/Extraction/PDFExtractorTest.php index 4a16da31..aa1c516b 100644 --- a/tests/V1/Extraction/PDFExtractorTest.php +++ b/tests/V1/Extraction/PDFExtractorTest.php @@ -1,5 +1,6 @@ dummyClient = new Client("dummy-key"); } - public function testGivenAnImageShouldExtractAPDF() + public function testGivenAnImageShouldExtractAPDF(): void { - $jpg = \TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; + $jpg = TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; $localInput = new PathInput($jpg); - $this->assertFalse($localInput->isPDF()); + self::assertFalse($localInput->isPDF()); $extractor = new PDFExtractor($localInput); - $this->assertEquals(1, $extractor->getPageCount()); + self::assertSame(1, $extractor->getPageCount()); } /** - * @test + * */ - public function testGivenAPDFShouldExtractInvoicesNoStrict() + public function testGivenAPDFShouldExtractInvoicesNoStrict(): void { - $pdf = new PathInput(\TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); + $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); $response = $this->getPrediction(); - $this->assertNotNull($response); + self::assertNotNull($response); $inference = $response->document->inference; $extractor = new PDFExtractor($pdf); - $this->assertEquals(5, $extractor->getPageCount()); + self::assertSame(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()); + 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()); } /** - * @test + * */ - public function testGivenAPDFShouldExtractInvoicesStrict() + public function testGivenAPDFShouldExtractInvoicesStrict(): void { - $pdf = new PathInput(\TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); + $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); $response = $this->getPrediction(); - $this->assertNotNull($response); + self::assertNotNull($response); $inference = $response->document->inference; $extractor = new PDFExtractor($pdf); - $this->assertEquals(5, $extractor->getPageCount()); + self::assertSame(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()); + 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"; + $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 5776a4a8..4cb8af19 100644 --- a/tests/V1/Http/MindeeApiTest.php +++ b/tests/V1/Http/MindeeApiTest.php @@ -1,11 +1,15 @@ 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\V1\Client::DEFAULT_OWNER, $settings->accountName); - $this->assertEquals("1", $settings->version); + self::assertSame("my-api-key", $settings->apiKey); + self::assertSame(InvoiceSplitterV1::$endpointName, $settings->endpointName); + self::assertSame(Client::DEFAULT_OWNER, $settings->accountName); + self::assertSame("1", $settings->version); } - public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated() + public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated(): void { $settings = new MindeeAPI("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); - $this->assertEquals("my-api-key", $settings->apiKey); - $this->assertEquals("custom-endpoint-name", $settings->endpointName); - $this->assertEquals("custom-owner-name", $settings->accountName); - $this->assertEquals("1.3", $settings->version); + self::assertSame("my-api-key", $settings->apiKey); + self::assertSame("custom-endpoint-name", $settings->endpointName); + self::assertSame("custom-owner-name", $settings->accountName); + self::assertSame("1.3", $settings->version); } - public function testGivenInvalidApiKeyAnExceptionShouldBeThrown() + public function testGivenInvalidApiKeyAnExceptionShouldBeThrown(): void { $this->expectException(MindeeException::class); putenv(API_KEY_ENV_NAME . '='); diff --git a/tests/V1/Input/LocalResponseV1Test.php b/tests/V1/Input/LocalResponseV1Test.php index faaea2b3..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 { $stream = fopen('php://memory', 'r+'); fwrite($stream, file_get_contents($this->filePath)); @@ -80,22 +83,22 @@ public function testValidStreamLocalResponse() $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' ); @@ -103,26 +106,26 @@ public function testValidStreamLocalResponse() 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 20800724..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 4911915c..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 7805073a..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 35486c32..3b93413f 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -1,5 +1,7 @@ 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 124daa7e..90774d3d 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php @@ -1,34 +1,39 @@ extrasDir = \TestingUtilities::getV1DataDir() . "/extras"; + $this->extrasDir = TestingUtilities::getV1DataDir() . "/extras"; } private function loadDocument() { - $dummyClient = new \Mindee\V1\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))); + self::assertSame(trim($expectedText), trim((string) $fullTextOcr)); } } diff --git a/tests/V1/Parsing/Common/OCR/OCRTest.php b/tests/V1/Parsing/Common/OCR/OCRTest.php index 334bd12f..1fa20a6d 100644 --- a/tests/V1/Parsing/Common/OCR/OCRTest.php +++ b/tests/V1/Parsing/Common/OCR/OCRTest.php @@ -1,53 +1,57 @@ ocrObject = new OCR($jsonData["document"]["ocr"]); } - public function testResponse() + public function testResponse(): void { $expectedText = file_get_contents( - \TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" + TestingUtilities::getV1DataDir() . "/extras/ocr/ocr.txt" ); - $this->assertEquals($expectedText, strval($this->ocrObject)); - $this->assertEquals($expectedText, strval($this->ocrObject->mvisionV1->pages[0])); + self::assertSame($expectedText, (string) ($this->ocrObject)); + self::assertSame($expectedText, (string) ($this->ocrObject->mvisionV1->pages[0])); } - public function testFindOneLineByRegex() + public function testFindOneLineByRegex(): void { $regexFilter = '/platinum[\w\s]*\$65\.00/i'; $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals( + self::assertNotNull($matchingLines); + self::assertSame( "Platinum web hosting package $65.00 $65.00", - strval($matchingLines[0][0]) + (string) ($matchingLines[0][0]) ); } - public function testFindMultipleLinesByRegex() + public function testFindMultipleLinesByRegex(): void { $regexFilter = '/^.*\$.*$/m'; $matchingLines = $this->ocrObject->findLineByRegex($regexFilter); - $this->assertNotNull($matchingLines); - $this->assertEquals(8, count($matchingLines[0])); - $this->assertEquals( + self::assertNotNull($matchingLines); + self::assertCount(8, $matchingLines[0]); + self::assertSame( "Amount Due (USD): $2,608.20", - strval($matchingLines[0][0]) + (string) ($matchingLines[0][0]) ); - $this->assertEquals( + self::assertSame( "Amount due (CAD): $2,608.20", - strval($matchingLines[0][7]) + (string) ($matchingLines[0][7]) ); } } diff --git a/tests/V1/Parsing/Common/PredictResponseTest.php b/tests/V1/Parsing/Common/PredictResponseTest.php index aa2bd5db..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 6ee6fc17..bda66885 100644 --- a/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php +++ b/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\BarcodeReader\BarcodeReaderV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 1eb0e60b..a4e68e53 100644 --- a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php +++ b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\BillOfLading\BillOfLadingV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 9096142b..acf6727a 100644 --- a/tests/V1/Product/BusinessCard/BusinessCardV1Test.php +++ b/tests/V1/Product/BusinessCard/BusinessCardV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\BusinessCard\BusinessCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 cb081218..f1af6ef3 100644 --- a/tests/V1/Product/Cropper/CropperV1Test.php +++ b/tests/V1/Product/Cropper/CropperV1Test.php @@ -1,11 +1,15 @@ completeDoc = new Document(\Mindee\V1\Product\Cropper\CropperV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Cropper\CropperV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(\Mindee\V1\Product\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 083b6c47..da3ab166 100644 --- a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php +++ b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\DeliveryNote\DeliveryNoteV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 18722d57..7d674eef 100644 --- a/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php +++ b/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\DriverLicense\DriverLicenseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 c26adc17..9a37dce4 100644 --- a/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php +++ b/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php @@ -1,11 +1,15 @@ completeDocInvoice = new Document(\Mindee\V1\Product\FinancialDocument\FinancialDocumentV1::class, $completeDocJSONInvoice["document"]); - $this->completeDocReceipt = new Document(\Mindee\V1\Product\FinancialDocument\FinancialDocumentV1::class, $completeDocJSONReceipt["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\FinancialDocument\FinancialDocumentV1::class, $emptyDocJSON["document"]); - $this->completePage0Invoice = new Page(\Mindee\V1\Product\FinancialDocument\FinancialDocumentV1Document::class, $completeDocJSONInvoice["document"]["inference"]["pages"][0]); - $this->completePage0Receipt = new Page(\Mindee\V1\Product\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 0afebde3..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(\Mindee\V1\Product\Fr\BankAccountDetails\BankAccountDetailsV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 7b92f2ca..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(\Mindee\V1\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 57d859ad..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(\Mindee\V1\Product\Fr\CarteGrise\CarteGriseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 1d8166e0..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(\Mindee\V1\Product\Fr\EnergyBill\EnergyBillV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 802e6d2c..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(\Mindee\V1\Product\Fr\HealthCard\HealthCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 0fecdcb8..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(\Mindee\V1\Product\Fr\IdCard\IdCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\IdCard\IdCardV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(\Mindee\V1\Product\Fr\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 13716008..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(\Mindee\V1\Product\Fr\IdCard\IdCardV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\IdCard\IdCardV2::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(\Mindee\V1\Product\Fr\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 0fb56070..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(\Mindee\V1\Product\Fr\Payslip\PayslipV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Fr\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 25dac487..b12b80f7 100644 --- a/tests/V1/Product/Generated/GeneratedV1Test.php +++ b/tests/V1/Product/Generated/GeneratedV1Test.php @@ -1,5 +1,7 @@ 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 ffa89d39..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(\Mindee\V1\Product\Ind\IndianPassport\IndianPassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Ind\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 f83381f9..4c2b4ed8 100644 --- a/tests/V1/Product/InternationalId/InternationalIdV2Test.php +++ b/tests/V1/Product/InternationalId/InternationalIdV2Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\InternationalId\InternationalIdV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 c81b7367..5c47e975 100644 --- a/tests/V1/Product/Invoice/InvoiceV4Test.php +++ b/tests/V1/Product/Invoice/InvoiceV4Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\Invoice\InvoiceV4::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 f931b1c7..3bc4ed80 100644 --- a/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php +++ b/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 fa738fc4..3af1af4c 100644 --- a/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php +++ b/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 b5593e22..2972b3b1 100644 --- a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php +++ b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 d3748026..a3fc5296 100644 --- a/tests/V1/Product/Passport/PassportV1Test.php +++ b/tests/V1/Product/Passport/PassportV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\Passport\PassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 d92c110e..00e0b82e 100644 --- a/tests/V1/Product/Receipt/ReceiptV5Test.php +++ b/tests/V1/Product/Receipt/ReceiptV5Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\Receipt\ReceiptV5::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 39ff71de..0dc24b2f 100644 --- a/tests/V1/Product/Resume/ResumeV1Test.php +++ b/tests/V1/Product/Resume/ResumeV1Test.php @@ -1,10 +1,13 @@ completeDoc = new Document(\Mindee\V1\Product\Resume\ResumeV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\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 e20c40cf..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(\Mindee\V1\Product\Us\BankCheck\BankCheckV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Us\BankCheck\BankCheckV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(\Mindee\V1\Product\Us\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 3f09a552..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(\Mindee\V1\Product\Us\HealthcareCard\HealthcareCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Us\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 e3a70c24..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(\Mindee\V1\Product\Us\UsMail\UsMailV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(\Mindee\V1\Product\Us\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 cf3f654b..06754acd 100644 --- a/tests/V1/Standard/AmountFieldTest.php +++ b/tests/V1/Standard/AmountFieldTest.php @@ -1,5 +1,7 @@ "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 78f11227..149fa9b0 100644 --- a/tests/V1/Standard/ClassificationFieldTest.php +++ b/tests/V1/Standard/ClassificationFieldTest.php @@ -1,5 +1,7 @@ "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 15b7e5d5..82ae2468 100644 --- a/tests/V1/Standard/CompanyRegistrationFieldTest.php +++ b/tests/V1/Standard/CompanyRegistrationFieldTest.php @@ -1,5 +1,7 @@ "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 3f55410a..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 48805178..6ac75a60 100644 --- a/tests/V1/Standard/LocaleFieldTest.php +++ b/tests/V1/Standard/LocaleFieldTest.php @@ -1,5 +1,7 @@ 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 785e7468..4f3b29b9 100644 --- a/tests/V1/Standard/PaymentDetailsFieldTest.php +++ b/tests/V1/Standard/PaymentDetailsFieldTest.php @@ -1,5 +1,7 @@ "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 509a2a9f..85636246 100644 --- a/tests/V1/Standard/PositionFieldTest.php +++ b/tests/V1/Standard/PositionFieldTest.php @@ -1,5 +1,7 @@ [ [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 f60d38bc..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 3e30a21a..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 d6ed6a65..6113be2d 100644 --- a/tests/V1/Workflow/WorkflowTest.php +++ b/tests/V1/Workflow/WorkflowTest.php @@ -1,5 +1,7 @@ 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 9e99d3de..df4ad42d 100644 --- a/tests/V1/Workflow/WorkflowTestFunctional.php +++ b/tests/V1/Workflow/WorkflowTestFunctional.php @@ -1,5 +1,7 @@ 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 985f4430..7c49181e 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -1,5 +1,7 @@ getProperty('mindeeApi'); $property->setAccessible(true); $property->setValue($client, $mockedApi); @@ -29,24 +33,24 @@ private static function makeClientWithMockedApi(MindeeAPIV2 $mockedApi): Client public function testEnqueuePostAsync(): void { $predictable = $this->createMock(MindeeAPIV2::class); - $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); - $predictable->expects($this->once()) + $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); + $predictable->expects(self::once()) ->method('reqPostEnqueue') ->with( - $this->isInstanceOf(LocalInputSource::class), - $this->isInstanceOf(ExtractionParameters::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'); + $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 @@ -54,20 +58,20 @@ public function testDocumentGetJobAsync(): void /** @var MindeeAPIV2&MockObject $predictable */ $predictable = $this->createMock(MindeeAPIV2::class); - $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); + $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $processing = new JobResponse(json_decode($syntheticResponse, true)); - $predictable->expects($this->once()) + $predictable->expects(self::once()) ->method('reqGetJob') - ->with($this->equalTo('dummy-id')) + ->with(self::equalTo('dummy-id')) ->willReturn($processing); $mindeeClient = self::makeClientWithMockedApi($predictable); $response = $mindeeClient->getJob('dummy-id'); - $this->assertNotNull($response, 'must return a response'); - $this->assertNotNull($response->job, 'job must return a response'); + self::assertNotNull($response, 'must return a response'); + self::assertNotNull($response->job, 'job must return a response'); } public function testDocumentGetInferenceAsync(): void @@ -75,17 +79,17 @@ public function testDocumentGetInferenceAsync(): void /** @var MindeeAPIV2&MockObject $predictable */ $predictable = $this->createMock(MindeeAPIV2::class); - $jsonFile = \TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; - $this->assertFileExists($jsonFile, 'Test resource file must exist'); + $jsonFile = TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; + self::assertFileExists($jsonFile, 'Test resource file must exist'); $json = json_decode(file_get_contents($jsonFile), true); $processing = new ExtractionResponse($json); - $predictable->expects($this->once()) + $predictable->expects(self::once()) ->method('reqGetResult') ->with( - $this->equalTo(ExtractionResponse::class), - $this->equalTo('12345678-1234-1234-1234-123456789abc') + self::equalTo(ExtractionResponse::class), + self::equalTo('12345678-1234-1234-1234-123456789abc') ) ->willReturn($processing); @@ -93,18 +97,18 @@ public function testDocumentGetInferenceAsync(): void $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.' @@ -113,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(ExtractionResponse::class); - $this->assertNotNull($loaded, 'Loaded ExtractionResponse must not be null'); - $this->assertInstanceOf(ExtractionResponse::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' @@ -145,7 +149,7 @@ public function testInvalidBaseUrlRaisesMindeeException(): void try { $client = new Client('dummy-key'); - $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); + $input = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); $params = new ExtractionParameters('dummy-model-id'); $client->enqueueAndGetResult(ExtractionResponse::class, $input, $params); } finally { diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index e0a0d7e7..c532676b 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -1,5 +1,7 @@ modelId, rag: false, rawText: true); $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); - $this->assertNotNull($response); + 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); } /** @@ -68,26 +70,26 @@ public function testParseFileFilledSinglePageMustSucceed(): void $inferenceParams = new ExtractionParameters($this->modelId, rag: false, textContext: 'this is an invoice'); $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); - $this->assertNotNull($response); + 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 ); @@ -103,9 +105,9 @@ public function testInvalidUUIDMustThrowError(): void 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); } } @@ -118,9 +120,9 @@ public function testUnknownModelMustThrowError(): void 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); } } @@ -130,13 +132,13 @@ public function testInvalidJobMustThrowError(): void try { $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'); @@ -154,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); } } @@ -167,15 +169,15 @@ public function testUrlInputSourceMustNotRaiseErrors(): void $inferenceParams = new ExtractionParameters($this->modelId); $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $urlSource, $inferenceParams); - $this->assertNotNull($response); + 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 @@ -191,27 +193,27 @@ public function testDataSchemaMustSucceed(): void $inferenceParams = new ExtractionParameters($this->modelId, dataSchema: $dataSchemaReplace); $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); - $this->assertNotNull($response); + 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 ); @@ -223,11 +225,13 @@ public function testMultipleWebhooksMustSucceed(): void TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf' ); - $inferenceParams = new ExtractionParameters($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 6526ff1a..66de7fa7 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -1,5 +1,7 @@ outputDir = getcwd() . '/output'; if (!is_dir($this->outputDir)) { - mkdir($this->outputDir, 0777, true); + mkdir($this->outputDir, 0o777, true); } } @@ -46,29 +51,29 @@ protected function tearDown(): 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 ExtractionParameters($this->findocModelId); @@ -80,25 +85,25 @@ public function testExtractCropsFromImageCorrectly(): void $extractedImages->saveAllToDisk($this->outputDir, quality: 50); $file1Info = filesize($this->outputDir . '/crop_001.jpg'); - $this->assertGreaterThanOrEqual(97000, $file1Info); - $this->assertLessThanOrEqual(103000, $file1Info); + self::assertGreaterThanOrEqual(97000, $file1Info); + self::assertLessThanOrEqual(103000, $file1Info); $file2Info = filesize($this->outputDir . '/crop_002.jpg'); - $this->assertGreaterThanOrEqual(97000, $file2Info); - $this->assertLessThanOrEqual(103000, $file2Info); + self::assertGreaterThanOrEqual(97000, $file2Info); + self::assertLessThanOrEqual(103000, $file2Info); } public function testExtractCropsFromEachPDFPageCorrectly(): void { - $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); + $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); $cropParams = new CropParameters($this->cropModelId); $response = $this->client->enqueueAndGetResult(CropResponse::class, $inputSource, $cropParams); $cropOperation = new Crop($inputSource); $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); - $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 501cbffd..39314f38 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -1,5 +1,7 @@ outputDir = getcwd() . '/output'; if (!is_dir($this->outputDir)) { - mkdir($this->outputDir, 0777, true); + mkdir($this->outputDir, 0o777, true); } } @@ -46,31 +53,31 @@ protected function tearDown(): 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 { - $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 ExtractionParameters($this->findocModelId); @@ -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 2e32c100..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() { + public function testDataSchemaShouldntReplaceWhenUnset(): void + { $params = new ExtractionParameters('model_id', dataSchema: null); - $this->assertFalse(isset($params->dataSchema)); + self::assertFalse(isset($params->dataSchema)); } - public function testDataSchemaShouldEquateNoMatterTheType(){ + 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); - $this->assertEquals(strval($paramsDict->dataSchema), $this->expectedSchemaString); - $this->assertEquals(strval($paramsObject->dataSchema), $this->expectedSchemaString); - $this->assertEquals(strval($paramsString->dataSchema), $this->expectedSchemaString); + 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 5122fefa..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)); + 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); - $this->assertInstanceOf(ExtractionResponse::class, $response); - $this->assertNotNull($response->inference); - $this->assertNotNull($response->inference->result); - $this->assertNotNull($response->inference->result->fields); + 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 index a5d44c10..30cae739 100644 --- a/tests/V2/Parsing/ExtractionResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -1,5 +1,7 @@ assertFileExists($fullPath, "Resource file must exist: $resourcePath"); + self::assertFileExists($fullPath, "Resource file must exist: $resourcePath"); $localResponse = new LocalResponse($fullPath); return $localResponse->deserializeResponse(ExtractionResponse::class); @@ -33,414 +35,408 @@ private function loadFromResource(string $resourcePath): ExtractionResponse private function readFileAsString(string $path): string { - $this->assertFileExists($path, "Resource file must exist: $path"); + self::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'); + self::assertCount(21, $fields, 'Expected 21 fields'); - $this->assertInstanceOf( + self::assertInstanceOf( SimpleField::class, $fields['total_amount'], "Field 'total_amount' must be a SimpleField" ); $totalAmount = $fields->getSimpleField('total_amount'); - $this->assertEmpty($totalAmount->value); + self::assertEmpty($totalAmount->value); - $this->assertInstanceOf( + self::assertInstanceOf( ListField::class, $fields['taxes'], "Field 'taxes' must be a ListField" ); $taxes = $fields->getListField('taxes'); - $this->assertEmpty($taxes->items); + self::assertEmpty($taxes->items); - $this->assertInstanceOf( + self::assertInstanceOf( ObjectField::class, $fields['supplier_address'], "Field 'supplier_address' must be an ObjectField" ); $supplierAddress = $fields->getObjectField('supplier_address'); - $this->assertCount(9, $supplierAddress->fields); + self::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"); + self::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"); + self::assertEmpty($subField->value, "Field $fieldName.$subFieldName must be empty"); } } elseif ($field instanceof SimpleField) { - $this->assertIsNotObject($field->value, "Field $fieldName must be a scalar value"); + self::assertIsNotObject($field->value, "Field $fieldName must be a scalar value"); } else { - $this->fail("Unknown field type: $fieldName"); + self::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, 'ExtractionInference ID mismatch'); + self::assertNotNull($inference, 'Inference must not be null'); + self::assertSame('12345678-1234-1234-1234-123456789abc', $inference->id, 'ExtractionInference 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'); + self::assertNotNull($model, 'Model must not be null'); + self::assertSame('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'); + 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; - $this->assertCount(21, $fields, 'Expected 21 fields in the payload'); + self::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"); + self::assertInstanceOf(SimpleField::class, $date); + self::assertSame('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"); + 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]; - $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'); + 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'); - $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"); + 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'); - $this->assertNotNull($supplierAddress, "'supplier_address' field must exist"); - $this->assertInstanceOf(ObjectField::class, $supplierAddress, "'supplier_address' must be an ObjectField"); + self::assertNotNull($supplierAddress, "'supplier_address' field must exist"); + self::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"); + 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'); - $this->assertInstanceOf(ObjectField::class, $customerAddr); + self::assertInstanceOf(ObjectField::class, $customerAddr); $city = $customerAddr->fields->get('city'); - $this->assertInstanceOf(SimpleField::class, $city); - $this->assertEquals('New York', $city->value, 'City mismatch'); + self::assertInstanceOf(SimpleField::class, $city); + self::assertSame('New York', $city->value, 'City mismatch'); - $this->assertNull($inference->result->options ?? null, 'Options must be null'); + self::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); + self::assertNotNull($inference); $root = $inference->result->fields; - $this->assertInstanceOf(SimpleField::class, $root->get('field_simple')); - $this->assertInstanceOf(ObjectField::class, $root->get('field_object')); + self::assertInstanceOf(SimpleField::class, $root->get('field_simple')); + self::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())); + 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; - $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')); + 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'); - $this->assertInstanceOf(ObjectField::class, $subObjectObject); + self::assertInstanceOf(ObjectField::class, $subObjectObject); $lvl2 = $subObjectObject->fields; - $this->assertInstanceOf(ListField::class, $lvl2->get('sub_object_object_sub_object_list')); + self::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); + self::assertInstanceOf(ListField::class, $nestedList); $items = $nestedList->items; - $this->assertNotEmpty($items); - $this->assertInstanceOf(ObjectField::class, $items[0]); + self::assertNotEmpty($items); + self::assertInstanceOf(ObjectField::class, $items[0]); $firstItem = $items[0]; - $this->assertInstanceOf(ObjectField::class, $firstItem); + self::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); + self::assertInstanceOf(SimpleField::class, $deepSimple); + self::assertSame('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); + self::assertNotNull($inference); $fields = $inference->result->fields; $fieldSimpleString = $fields->get('field_simple_string'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleString); - $this->assertIsString($fieldSimpleString->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleString); + self::assertIsString($fieldSimpleString->value); $fieldSimpleFloat = $fields->get('field_simple_float'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleFloat); - $this->assertIsFloat($fieldSimpleFloat->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleFloat); + self::assertIsFloat($fieldSimpleFloat->value); $fieldSimpleInt = $fields->get('field_simple_int'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleInt); - $this->assertIsFloat($fieldSimpleInt->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleInt); + self::assertIsFloat($fieldSimpleInt->value); $fieldSimpleZero = $fields->get('field_simple_zero'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleZero); - $this->assertIsFloat($fieldSimpleZero->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleZero); + self::assertIsFloat($fieldSimpleZero->value); $fieldSimpleBool = $fields->get('field_simple_bool'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleBool); - $this->assertIsBool($fieldSimpleBool->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleBool); + self::assertIsBool($fieldSimpleBool->value); $fieldSimpleNull = $fields->get('field_simple_null'); - $this->assertInstanceOf(SimpleField::class, $fieldSimpleNull); - $this->assertNull($fieldSimpleNull->value); + self::assertInstanceOf(SimpleField::class, $fieldSimpleNull); + self::assertNull($fieldSimpleNull->value); $fieldSimpleList = $fields->get('field_simple_list'); - $this->assertInstanceOf(ListField::class, $fieldSimpleList); + self::assertInstanceOf(ListField::class, $fieldSimpleList); $simpleItems = $fieldSimpleList->items; - $this->assertCount(2, $simpleItems); + self::assertCount(2, $simpleItems); $firstSimpleItem = $simpleItems[0]; - $this->assertInstanceOf(SimpleField::class, $firstSimpleItem); - $this->assertIsString($firstSimpleItem->value); + self::assertInstanceOf(SimpleField::class, $firstSimpleItem); + self::assertIsString($firstSimpleItem->value); foreach ($fieldSimpleList->items as $item) { - $this->assertInstanceOf(SimpleField::class, $item); - $this->assertIsString($item->value); + self::assertInstanceOf(SimpleField::class, $item); + self::assertIsString($item->value); } $fieldObject = $fields->get('field_object'); - $this->assertInstanceOf(ObjectField::class, $fieldObject); + self::assertInstanceOf(ObjectField::class, $fieldObject); $fieldObjectFields = $fieldObject->fields; - $this->assertCount(2, $fieldObjectFields); + self::assertCount(2, $fieldObjectFields); foreach ($fieldObjectFields as $fieldName => $subField) { - $this->assertInstanceOf(SimpleField::class, $subField); + self::assertInstanceOf(SimpleField::class, $subField); } $subfield1 = $fieldObjectFields->getSimpleField('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $subfield1); - $this->assertIsString($subfield1->value); + self::assertInstanceOf(SimpleField::class, $subfield1); + self::assertIsString($subfield1->value); $fieldObjectList = $fields->get('field_object_list'); - $this->assertInstanceOf(ListField::class, $fieldObjectList); + self::assertInstanceOf(ListField::class, $fieldObjectList); $objectItems = $fieldObjectList->items; - $this->assertCount(2, $objectItems); + self::assertCount(2, $objectItems); $firstObjectItem = $objectItems[0]; - $this->assertInstanceOf(ObjectField::class, $firstObjectItem); + self::assertInstanceOf(ObjectField::class, $firstObjectItem); $firstObjectSubfield = $firstObjectItem->fields->get('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $firstObjectSubfield); - $this->assertIsString($firstObjectSubfield->value); + self::assertInstanceOf(SimpleField::class, $firstObjectSubfield); + self::assertIsString($firstObjectSubfield->value); foreach ($fieldObjectList->items as $item) { - $this->assertInstanceOf(ObjectField::class, $item); + self::assertInstanceOf(ObjectField::class, $item); $subfield = $item->fields->get('subfield_1'); - $this->assertInstanceOf(SimpleField::class, $subfield); - $this->assertIsString($subfield->value); + self::assertInstanceOf(SimpleField::class, $subfield); + self::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); + self::assertNotNull($inference); $activeOptions = $inference->activeOptions; - $this->assertTrue($activeOptions->rawText); - $this->assertFalse($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); + self::assertTrue($activeOptions->rawText); + self::assertFalse($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); $rawText = $inference->result->rawText; - $this->assertNotNull($rawText); - $this->assertCount(2, $rawText->pages); + self::assertNotNull($rawText); + self::assertCount(2, $rawText->pages); $first = $rawText->pages[0]; - $this->assertEquals('This is the raw text of the first page...', $first->content); + self::assertSame('This is the raw text of the first page...', $first->content); foreach ($rawText->pages as $page) { - $this->assertIsString($page->content); + self::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' + TestingUtilities::getV2ProductDir() . '/extraction/standard_field_types.rst' ); $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertEquals($expectedRst, strval($response->inference)); + self::assertNotNull($inference); + self::assertSame($expectedRst, (string) ($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); + self::assertNotNull($inference); $fields = $response->inference->result->fields; $dateField = $fields->getSimpleField('date'); - $this->assertCount(1, $dateField->locations); + self::assertCount(1, $dateField->locations); $location = $dateField->locations[0]; - $this->assertNotNull($location); - $this->assertEquals(0, $location->page); - $this->assertEquals( + self::assertNotNull($location); + self::assertSame(0, $location->page); + self::assertSame( 0.948979073166918, $location->polygon->coordinates[0]->getX() ); - $this->assertEquals( + self::assertSame( 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( + 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] ); - $this->assertEquals( + self::assertSame( 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( + 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() ); - $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); + 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; - $this->assertTrue($activeOptions->polygon); - $this->assertFalse($activeOptions->confidence); - $this->assertFalse($activeOptions->rag); - $this->assertFalse($activeOptions->rawText); - $this->assertFalse($activeOptions->textContext); + self::assertTrue($activeOptions->polygon); + self::assertFalse($activeOptions->confidence); + self::assertFalse($activeOptions->rag); + self::assertFalse($activeOptions->rawText); + self::assertFalse($activeOptions->textContext); } - public function testRagMetadataWhenMatched() + public function testRagMetadataWhenMatched(): void { $response = $this->loadFromResource('extraction/rag_matched.json'); $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertEquals('12345abc-1234-1234-1234-123456789abc', $inference->result->rag->retrievedDocumentId); + self::assertNotNull($inference); + self::assertSame('12345abc-1234-1234-1234-123456789abc', $inference->result->rag->retrievedDocumentId); } - public function testRagMetadataWhenNotMatched() + public function testRagMetadataWhenNotMatched(): void { $response = $this->loadFromResource('extraction/rag_not_matched.json'); $inference = $response->inference; - $this->assertNotNull($inference); - $this->assertNull($inference->result->rag->retrievedDocumentId); + self::assertNotNull($inference); + self::assertNull($inference->result->rag->retrievedDocumentId); } - public function testShouldLoadWith422Error() + public function testShouldLoadWith422Error(): void { $jsonResponse = json_decode( - file_get_contents(\TestingUtilities::getV2DataDir() . '/job/fail_422.json'), true + 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]); + 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; - $this->assertNotNull($inference); + self::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); + 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; - $this->assertNotNull($inference); + self::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); + 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/JobResponseTest.php b/tests/V2/Parsing/JobResponseTest.php index 6a805208..1bd8e662 100644 --- a/tests/V2/Parsing/JobResponseTest.php +++ b/tests/V2/Parsing/JobResponseTest.php @@ -1,5 +1,7 @@ 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 3227212d..641c971f 100644 --- a/tests/V2/Product/ClassificationFunctional.php +++ b/tests/V2/Product/ClassificationFunctional.php @@ -1,5 +1,6 @@ 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 9ba83619..e14e484f 100644 --- a/tests/V2/Product/CropFunctional.php +++ b/tests/V2/Product/CropFunctional.php @@ -1,5 +1,7 @@ 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 4d868040..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 { @@ -54,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 { @@ -65,34 +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()); - $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 { @@ -104,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 { @@ -153,11 +149,11 @@ public function testRstDisplayMustBeAccessible(): void $rstReference = file_get_contents($rstReferencePath); $inference = $response->inference; - $this->assertNotNull($inference); + self::assertNotNull($inference); - $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 b65af80f..974d29e7 100644 --- a/tests/V2/Product/OcrFunctional.php +++ b/tests/V2/Product/OcrFunctional.php @@ -1,5 +1,7 @@ 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 0d6b9808..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,32 +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); - $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 { @@ -89,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 aa89b158..24cfc73d 100644 --- a/tests/V2/Product/SplitFunctional.php +++ b/tests/V2/Product/SplitFunctional.php @@ -1,5 +1,7 @@ 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]); } }