From 740a819747bdb47de47a5ef839977bcee5931618 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 11 May 2026 15:00:10 +0200 Subject: [PATCH 01/11] :recycle: move all V1 and V2 logic to their own namespaces (#184) :recycle: move all V1 and V2 logic to their own namespaces (#184) --- CHANGELOG.md | 9 ++ bin/MindeeCLICommand.php | 11 +- bin/MindeeCLIDocuments.php | 52 +++--- docs/code_samples/bank_account_details_v1.txt | 4 +- docs/code_samples/bank_account_details_v2.txt | 4 +- docs/code_samples/bank_check_v1.txt | 4 +- docs/code_samples/barcode_reader_v1.txt | 4 +- docs/code_samples/bill_of_lading_v1_async.txt | 4 +- docs/code_samples/business_card_v1_async.txt | 4 +- docs/code_samples/carte_grise_v1.txt | 4 +- docs/code_samples/cropper_v1.txt | 4 +- docs/code_samples/custom_v1.txt | 6 +- docs/code_samples/default.txt | 6 +- docs/code_samples/default_async.txt | 6 +- docs/code_samples/delivery_notes_v1_async.txt | 4 +- docs/code_samples/driver_license_v1_async.txt | 4 +- .../code_samples/energy_bill_fra_v1_async.txt | 4 +- docs/code_samples/expense_receipts_v5.txt | 4 +- .../expense_receipts_v5_async.txt | 4 +- docs/code_samples/financial_document_v1.txt | 4 +- .../financial_document_v1_async.txt | 4 +- .../french_healthcard_v1_async.txt | 4 +- docs/code_samples/idcard_fr_v1.txt | 4 +- docs/code_samples/idcard_fr_v2.txt | 4 +- docs/code_samples/ind_passport_v1_async.txt | 4 +- .../international_id_v2_async.txt | 4 +- .../invoice_splitter_v1_async.txt | 4 +- docs/code_samples/invoices_v4.txt | 4 +- docs/code_samples/invoices_v4_async.txt | 4 +- .../multi_receipts_detector_v1.txt | 4 +- .../code_samples/nutrition_facts_v1_async.txt | 4 +- docs/code_samples/passport_v1.txt | 4 +- docs/code_samples/payslip_fra_v3_async.txt | 4 +- docs/code_samples/resume_v1_async.txt | 4 +- .../us_healthcare_cards_v1_async.txt | 4 +- docs/code_samples/us_mail_v3_async.txt | 4 +- docs/code_samples/v2_classification.txt | 4 +- docs/code_samples/v2_crop.txt | 4 +- docs/code_samples/v2_extraction_polling.txt | 8 +- docs/code_samples/v2_extraction_webhook.txt | 6 +- docs/code_samples/v2_ocr.txt | 4 +- docs/code_samples/v2_split.txt | 4 +- docs/code_samples/workflow_execution.txt | 4 +- docs/code_samples/workflow_polling.txt | 6 +- .../InvoiceSplitterAutoExtractionExample.php | 52 ------ .../MultiReceiptsAutoExtractionExample.php | 37 ----- .../PollingOptions.php | 2 +- .../DependencyChecker.php | 2 +- src/Error/MindeeV2HttpException.php | 2 +- src/Error/MindeeV2HttpUnknownException.php | 2 +- src/Extraction/ExtractedImage.php | 2 +- .../{ExtractedPdf.php => ExtractedPDF.php} | 6 +- src/Extraction/ImageExtractor.php | 4 +- .../{PdfExtractor.php => PDFExtractor.php} | 12 +- src/Image/ImageCompressor.php | 4 +- src/PDF/PDFCompressor.php | 10 +- src/PDF/PDFUtils.php | 2 +- src/Parsing/{Common => }/SummaryHelper.php | 19 +-- src/{ => V1}/Client.php | 31 ++-- .../ClientOptions}/CommonOptions.php | 2 +- .../ClientOptions}/PredictMethodOptions.php | 8 +- .../ClientOptions}/PredictOptions.php | 2 +- .../ClientOptions}/WorkflowOptions.php | 2 +- src/{Http/BaseApi.php => V1/HTTP/BaseAPI.php} | 6 +- src/{Http => V1/HTTP}/BaseEndpoint.php | 6 +- src/{Http => V1/HTTP}/Endpoint.php | 8 +- .../MindeeApi.php => V1/HTTP/MindeeAPI.php} | 6 +- .../HTTP/MindeeWorkflowAPI.php} | 4 +- src/{Http => V1/HTTP}/ResponseValidation.php | 2 +- src/{Http => V1/HTTP}/WorkflowEndpoint.php | 8 +- src/{ => V1}/Parsing/Common/ApiRequest.php | 2 +- src/{ => V1}/Parsing/Common/ApiResponse.php | 4 +- .../Parsing/Common/AsyncPredictResponse.php | 6 +- src/{ => V1}/Parsing/Common/Document.php | 16 +- src/{ => V1}/Parsing/Common/Execution.php | 4 +- src/{ => V1}/Parsing/Common/ExecutionFile.php | 2 +- .../Parsing/Common/Extras/CropperExtra.php | 4 +- src/{ => V1}/Parsing/Common/Extras/Extras.php | 2 +- .../Common/Extras/FullTextOcrExtra.php | 4 +- .../Parsing/Common/Extras/RAGExtra.php | 2 +- src/{ => V1}/Parsing/Common/Inference.php | 10 +- src/{ => V1}/Parsing/Common/Job.php | 2 +- .../Parsing/Common/OCR}/MVisionV1.php | 4 +- .../Ocr.php => V1/Parsing/Common/OCR/OCR.php} | 6 +- .../Parsing/Common/OCR/OCRLine.php} | 10 +- .../Parsing/Common/OCR/OCRPage.php} | 28 ++-- .../Parsing/Common/OCR/OCRWord.php} | 6 +- .../Parsing/Common/OrientationField.php | 4 +- src/{ => V1}/Parsing/Common/Page.php | 4 +- .../Parsing/Common/PredictResponse.php | 4 +- src/{ => V1}/Parsing/Common/Prediction.php | 2 +- src/{ => V1}/Parsing/Common/Product.php | 2 +- .../Parsing/Common/WorkflowResponse.php | 4 +- .../Parsing/Generated/GeneratedListField.php | 4 +- .../Generated/GeneratedObjectField.php | 4 +- .../Parsing/Standard/AddressField.php | 2 +- src/{ => V1}/Parsing/Standard/AmountField.php | 2 +- src/{ => V1}/Parsing/Standard/BaseField.php | 2 +- .../Parsing/Standard/BooleanField.php | 6 +- .../Parsing/Standard/ClassificationField.php | 2 +- .../Standard/CompanyRegistrationField.php | 8 +- src/{ => V1}/Parsing/Standard/DateField.php | 2 +- .../Parsing/Standard/FieldConfidenceMixin.php | 2 +- .../Parsing/Standard/FieldPositionMixin.php | 3 +- src/{ => V1}/Parsing/Standard/LocaleField.php | 2 +- .../Parsing/Standard/PaymentDetailsField.php | 2 +- .../Parsing/Standard/PositionField.php | 2 +- src/{ => V1}/Parsing/Standard/StringField.php | 2 +- src/{ => V1}/Parsing/Standard/TaxField.php | 2 +- src/{ => V1}/Parsing/Standard/Taxes.php | 2 +- src/V1/Parsing/SummaryHelperV1.php | 24 +++ .../Product/BarcodeReader/BarcodeReaderV1.php | 8 +- .../BarcodeReader/BarcodeReaderV1Document.php | 10 +- .../Product/BillOfLading/BillOfLadingV1.php | 8 +- .../BillOfLading/BillOfLadingV1Carrier.php | 22 +-- .../BillOfLadingV1CarrierItem.php | 48 +++--- .../BillOfLadingV1CarrierItems.php | 2 +- .../BillOfLading/BillOfLadingV1Consignee.php | 26 +-- .../BillOfLading/BillOfLadingV1Document.php | 12 +- .../BillOfLadingV1NotifyParty.php | 26 +-- .../BillOfLading/BillOfLadingV1Shipper.php | 26 +-- .../Product/BusinessCard/BusinessCardV1.php | 8 +- .../BusinessCard/BusinessCardV1Document.php | 10 +- src/{ => V1}/Product/Cropper/CropperV1.php | 8 +- .../Product/Cropper/CropperV1Document.php | 4 +- .../Product/Cropper/CropperV1Page.php | 8 +- .../Product/DeliveryNote/DeliveryNoteV1.php | 8 +- .../DeliveryNote/DeliveryNoteV1Document.php | 14 +- .../Product/DriverLicense/DriverLicenseV1.php | 8 +- .../DriverLicense/DriverLicenseV1Document.php | 12 +- .../FinancialDocument/FinancialDocumentV1.php | 8 +- .../FinancialDocumentV1Document.php | 26 +-- .../FinancialDocumentV1LineItem.php | 60 +++---- .../FinancialDocumentV1LineItems.php | 2 +- .../BankAccountDetailsV1.php | 8 +- .../BankAccountDetailsV1Document.php | 10 +- .../BankAccountDetailsV2.php | 8 +- .../BankAccountDetailsV2Bban.php | 26 +-- .../BankAccountDetailsV2Document.php | 10 +- .../Product/Fr/CarteGrise/CarteGriseV1.php | 8 +- .../Fr/CarteGrise/CarteGriseV1Document.php | 12 +- .../Product/Fr/EnergyBill/EnergyBillV1.php | 8 +- .../Fr/EnergyBill/EnergyBillV1Document.php | 14 +- .../EnergyBill/EnergyBillV1EnergyConsumer.php | 18 +-- .../EnergyBill/EnergyBillV1EnergySupplier.php | 18 +-- .../Fr/EnergyBill/EnergyBillV1EnergyUsage.php | 60 +++---- .../EnergyBill/EnergyBillV1EnergyUsages.php | 2 +- .../Fr/EnergyBill/EnergyBillV1MeterDetail.php | 22 +-- .../EnergyBill/EnergyBillV1Subscription.php | 48 +++--- .../EnergyBill/EnergyBillV1Subscriptions.php | 2 +- .../EnergyBillV1TaxesAndContribution.php | 48 +++--- .../EnergyBillV1TaxesAndContributions.php | 2 +- .../Product/Fr/HealthCard/HealthCardV1.php | 8 +- .../Fr/HealthCard/HealthCardV1Document.php | 12 +- src/{ => V1}/Product/Fr/IdCard/IdCardV1.php | 8 +- .../Product/Fr/IdCard/IdCardV1Document.php | 12 +- .../Product/Fr/IdCard/IdCardV1Page.php | 8 +- src/{ => V1}/Product/Fr/IdCard/IdCardV2.php | 8 +- .../Product/Fr/IdCard/IdCardV2Document.php | 12 +- .../Product/Fr/IdCard/IdCardV2Page.php | 8 +- src/{ => V1}/Product/Fr/Payslip/PayslipV3.php | 8 +- .../Fr/Payslip/PayslipV3BankAccountDetail.php | 22 +-- .../Product/Fr/Payslip/PayslipV3Document.php | 8 +- .../Product/Fr/Payslip/PayslipV3Employee.php | 38 ++--- .../Product/Fr/Payslip/PayslipV3Employer.php | 38 ++--- .../Fr/Payslip/PayslipV3Employment.php | 38 ++--- .../Fr/Payslip/PayslipV3PaidTimeOff.php | 42 ++--- .../Fr/Payslip/PayslipV3PaidTimeOffs.php | 2 +- .../Product/Fr/Payslip/PayslipV3PayDetail.php | 50 +++--- .../Product/Fr/Payslip/PayslipV3PayPeriod.php | 30 ++-- .../Fr/Payslip/PayslipV3SalaryDetail.php | 42 ++--- .../Fr/Payslip/PayslipV3SalaryDetails.php | 2 +- .../Product/Generated/GeneratedV1.php | 6 +- .../Product/Generated/GeneratedV1Document.php | 8 +- .../Product/Generated/GeneratedV1Page.php | 8 +- .../Generated/GeneratedV1Prediction.php | 14 +- .../Ind/IndianPassport/IndianPassportV1.php | 8 +- .../IndianPassportV1Document.php | 14 +- .../InternationalId/InternationalIdV2.php | 8 +- .../InternationalIdV2Document.php | 14 +- src/{ => V1}/Product/Invoice/InvoiceV4.php | 8 +- .../Product/Invoice/InvoiceV4Document.php | 26 +-- .../Product/Invoice/InvoiceV4LineItem.php | 60 +++---- .../Product/Invoice/InvoiceV4LineItems.php | 2 +- .../InvoiceSplitter/InvoiceSplitterV1.php | 8 +- .../InvoiceSplitterV1Document.php | 8 +- .../InvoiceSplitterV1InvoicePageGroup.php | 14 +- .../InvoiceSplitterV1InvoicePageGroups.php | 2 +- .../MultiReceiptsDetectorV1.php | 8 +- .../MultiReceiptsDetectorV1Document.php | 10 +- .../NutritionFactsLabelV1.php | 8 +- .../NutritionFactsLabelV1AddedSugar.php | 22 +-- .../NutritionFactsLabelV1Calorie.php | 22 +-- .../NutritionFactsLabelV1Cholesterol.php | 22 +-- .../NutritionFactsLabelV1DietaryFiber.php | 22 +-- .../NutritionFactsLabelV1Document.php | 10 +- .../NutritionFactsLabelV1Nutrient.php | 42 ++--- .../NutritionFactsLabelV1Nutrients.php | 2 +- .../NutritionFactsLabelV1Protein.php | 22 +-- .../NutritionFactsLabelV1SaturatedFat.php | 22 +-- .../NutritionFactsLabelV1ServingSize.php | 18 +-- .../NutritionFactsLabelV1Sodium.php | 26 +-- ...NutritionFactsLabelV1TotalCarbohydrate.php | 22 +-- .../NutritionFactsLabelV1TotalFat.php | 22 +-- .../NutritionFactsLabelV1TotalSugar.php | 22 +-- .../NutritionFactsLabelV1TransFat.php | 22 +-- src/{ => V1}/Product/Passport/PassportV1.php | 8 +- .../Product/Passport/PassportV1Document.php | 12 +- src/{ => V1}/Product/Receipt/ReceiptV5.php | 8 +- .../Product/Receipt/ReceiptV5Document.php | 22 +-- .../Product/Receipt/ReceiptV5LineItem.php | 36 ++--- .../Product/Receipt/ReceiptV5LineItems.php | 2 +- src/{ => V1}/Product/Resume/ResumeV1.php | 8 +- .../Product/Resume/ResumeV1Certificate.php | 36 ++--- .../Product/Resume/ResumeV1Certificates.php | 2 +- .../Product/Resume/ResumeV1Document.php | 12 +- .../Product/Resume/ResumeV1Education.php | 54 +++---- .../Product/Resume/ResumeV1Educations.php | 2 +- .../Product/Resume/ResumeV1Language.php | 24 +-- .../Product/Resume/ResumeV1Languages.php | 2 +- .../Resume/ResumeV1ProfessionalExperience.php | 66 ++++---- .../ResumeV1ProfessionalExperiences.php | 2 +- .../Resume/ResumeV1SocialNetworksUrl.php | 24 +-- .../Resume/ResumeV1SocialNetworksUrls.php | 2 +- .../Product/Us/BankCheck/BankCheckV1.php | 8 +- .../Us/BankCheck/BankCheckV1Document.php | 14 +- .../Product/Us/BankCheck/BankCheckV1Page.php | 8 +- .../Us/HealthcareCard/HealthcareCardV1.php | 8 +- .../HealthcareCard/HealthcareCardV1Copay.php | 24 +-- .../HealthcareCard/HealthcareCardV1Copays.php | 2 +- .../HealthcareCardV1Document.php | 12 +- src/{ => V1}/Product/Us/UsMail/UsMailV3.php | 8 +- .../Product/Us/UsMail/UsMailV3Document.php | 12 +- .../Us/UsMail/UsMailV3RecipientAddress.php | 60 +++---- .../Us/UsMail/UsMailV3RecipientAddresses.php | 2 +- .../Us/UsMail/UsMailV3SenderAddress.php | 30 ++-- src/{ClientV2.php => V2/Client.php} | 27 ++-- src/V2/ClientOptions/BaseParameters.php | 2 +- src/V2/FileOperations/Split.php | 10 +- src/V2/FileOperations/SplitFiles.php | 8 +- .../HTTP/MindeeAPIV2.php} | 24 ++- src/V2/Parsing/BaseInference.php | 8 +- src/{Error => V2/Parsing}/ErrorItem.php | 2 +- .../V2 => V2/Parsing}/ErrorResponse.php | 4 +- .../Parsing/Inference}/BaseResponse.php | 2 +- .../Parsing/Inference}/Field/BaseField.php | 2 +- .../Inference}/Field/FieldConfidence.php | 2 +- .../Inference}/Field/FieldLocation.php | 2 +- .../Inference}/Field/InferenceFields.php | 2 +- .../Parsing/Inference}/Field/ListField.php | 4 +- .../Parsing/Inference}/Field/ObjectField.php | 2 +- .../Parsing/Inference}/Field/SimpleField.php | 2 +- .../V2 => V2/Parsing/Inference}/Inference.php | 4 +- .../Inference}/InferenceActiveOptions.php | 5 +- .../Parsing/Inference}/InferenceFile.php | 2 +- .../Parsing/Inference}/InferenceJob.php | 2 +- .../Parsing/Inference}/InferenceModel.php | 2 +- .../Parsing/Inference}/InferenceResponse.php | 2 +- .../Parsing/Inference}/InferenceResult.php | 10 +- .../Parsing/Inference/RAGMetadata.php} | 4 +- .../V2 => V2/Parsing/Inference}/RawText.php | 2 +- .../Parsing/Inference}/RawTextPage.php | 2 +- src/{Parsing/V2 => V2/Parsing}/Job.php | 2 +- .../V2 => V2/Parsing}/JobResponse.php | 4 +- src/{Parsing/V2 => V2/Parsing}/JobWebhook.php | 2 +- .../ClassificationClassifier.php | 2 +- .../ClassificationInference.php | 2 +- .../Classification/ClassificationResponse.php | 2 +- .../Params/ClassificationParameters.php | 2 +- src/V2/Product/Crop/CropItem.php | 4 +- src/V2/Product/Crop/CropResponse.php | 2 +- src/V2/Product/Crop/Params/CropParameters.php | 2 +- .../Product/Extraction/Params}/DataSchema.php | 2 +- .../Params}/DataSchemaActiveOption.php | 2 +- .../Extraction/Params}/DataSchemaField.php | 2 +- .../Extraction/Params}/DataSchemaReplace.php | 2 +- .../Params}/InferenceParameters.php | 3 +- src/V2/Product/Ocr/OcrResponse.php | 2 +- src/V2/Product/Ocr/Params/OcrParameters.php | 2 +- .../Product/Split/Params/SplitParameters.php | 2 +- src/V2/Product/Split/SplitRange.php | 2 +- src/V2/Product/Split/SplitResponse.php | 2 +- src/version.php | 2 +- tests/ClientTest.php | 16 +- ...=> DependencyCheckerNoExtendedTestPDF.php} | 14 +- ...fTest.php => DependencyCheckerPDFTest.php} | 4 +- tests/Input/LocalInputSourceTest.php | 149 +++++++++--------- tests/Input/URLInputSourceTest.php | 5 +- tests/V1/Error/MindeeHttpExceptionTest.php | 4 +- tests/V1/Extraction/ImageExtractorTest.php | 10 +- ...ceSplitterAutoExtractionTestFunctional.php | 16 +- ...ExtractorTest.php => PDFExtractorTest.php} | 16 +- tests/V1/Http/MindeeApiTest.php | 14 +- .../V1/Input/URLInputSourceTestFunctional.php | 4 +- .../Common/AsyncPredictResponseTest.php | 6 +- .../Common/Extras/CropperExtraTest.php | 6 +- .../Extras/ExtrasIntegrationFunctional.php | 10 +- .../Common/Extras/FullTextOcrExtraTest.php | 4 +- .../{Ocr/OcrTest.php => OCR/OCRTest.php} | 10 +- .../V1/Parsing/Common/PredictResponseTest.php | 6 +- .../BarcodeReader/BarcodeReaderV1Test.php | 6 +- .../BillOfLading/BillOfLadingV1Test.php | 6 +- .../BusinessCard/BusinessCardV1Test.php | 6 +- tests/V1/Product/Cropper/CropperV1Test.php | 10 +- .../DeliveryNote/DeliveryNoteV1Test.php | 6 +- .../DriverLicense/DriverLicenseV1Test.php | 6 +- .../FinancialDocumentV1Test.php | 14 +- .../BankAccountDetailsV1Test.php | 6 +- .../BankAccountDetailsV2Test.php | 6 +- .../Fr/CarteGrise/CarteGriseV1Test.php | 6 +- .../Fr/EnergyBill/EnergyBillV1Test.php | 6 +- .../Fr/HealthCard/HealthCardV1Test.php | 6 +- tests/V1/Product/Fr/IdCard/IdCardV1Test.php | 10 +- tests/V1/Product/Fr/IdCard/IdCardV2Test.php | 10 +- tests/V1/Product/Fr/Payslip/PayslipV3Test.php | 6 +- .../V1/Product/Generated/GeneratedV1Test.php | 16 +- .../IndianPassport/IndianPassportV1Test.php | 6 +- .../InternationalId/InternationalIdV2Test.php | 6 +- tests/V1/Product/Invoice/InvoiceV4Test.php | 6 +- .../InvoiceSplitter/InvoiceSplitterV1Test.php | 6 +- .../MultiReceiptsDetectorV1Test.php | 6 +- .../NutritionFactsLabelV1Test.php | 6 +- tests/V1/Product/Passport/PassportV1Test.php | 6 +- tests/V1/Product/Receipt/ReceiptV5Test.php | 6 +- tests/V1/Product/Resume/ResumeV1Test.php | 6 +- .../Product/Us/BankCheck/BankCheckV1Test.php | 10 +- .../HealthcareCard/HealthcareCardV1Test.php | 6 +- tests/V1/Product/Us/UsMail/UsMailV3Test.php | 6 +- tests/V1/Standard/AmountFieldTest.php | 2 +- tests/V1/Standard/ClassificationFieldTest.php | 2 +- .../Standard/CompanyRegistrationFieldTest.php | 2 +- tests/V1/Standard/DateFieldTest.php | 2 +- tests/V1/Standard/LocaleFieldTest.php | 2 +- tests/V1/Standard/PaymentDetailsFieldTest.php | 2 +- tests/V1/Standard/PositionFieldTest.php | 2 +- tests/V1/Standard/StringFieldTest.php | 2 +- tests/V1/Standard/TaxesTest.php | 2 +- tests/V1/Workflow/WorkflowTest.php | 4 +- tests/V1/Workflow/WorkflowTestFunctional.php | 8 +- tests/V2/ClientV2Test.php | 26 +-- tests/V2/ClientV2TestFunctional.php | 8 +- tests/V2/FileOperations/CropFunctional.php | 16 +- tests/V2/FileOperations/SplitFunctional.php | 14 +- tests/V2/Input/InferenceParameterTest.php | 4 +- tests/V2/Input/LocalResponseV2Test.php | 2 +- tests/V2/Parsing/InferenceResponseTest.php | 16 +- tests/V2/Parsing/JobResponseTest.php | 6 +- tests/V2/Product/ClassificationFunctional.php | 6 +- tests/V2/Product/CropFunctional.php | 6 +- tests/V2/Product/OcrFunctional.php | 6 +- tests/V2/Product/SplitFunctional.php | 6 +- 351 files changed, 1799 insertions(+), 1870 deletions(-) delete mode 100644 examples/InvoiceSplitterAutoExtractionExample.php delete mode 100644 examples/MultiReceiptsAutoExtractionExample.php rename src/{Input => ClientOptions}/PollingOptions.php (98%) rename src/{Parsing => Dependency}/DependencyChecker.php (99%) rename src/Extraction/{ExtractedPdf.php => ExtractedPDF.php} (96%) rename src/Extraction/{PdfExtractor.php => PDFExtractor.php} (95%) rename src/Parsing/{Common => }/SummaryHelper.php (77%) rename src/{ => V1}/Client.php (96%) rename src/{Input => V1/ClientOptions}/CommonOptions.php (96%) rename src/{Input => V1/ClientOptions}/PredictMethodOptions.php (95%) rename src/{Input => V1/ClientOptions}/PredictOptions.php (98%) rename src/{Input => V1/ClientOptions}/WorkflowOptions.php (97%) rename src/{Http/BaseApi.php => V1/HTTP/BaseAPI.php} (96%) rename src/{Http => V1/HTTP}/BaseEndpoint.php (94%) rename src/{Http => V1/HTTP}/Endpoint.php (96%) rename src/{Http/MindeeApi.php => V1/HTTP/MindeeAPI.php} (95%) rename src/{Http/MindeeWorkflowApi.php => V1/HTTP/MindeeWorkflowAPI.php} (94%) rename src/{Http => V1/HTTP}/ResponseValidation.php (99%) rename src/{Http => V1/HTTP}/WorkflowEndpoint.php (93%) rename src/{ => V1}/Parsing/Common/ApiRequest.php (96%) rename src/{ => V1}/Parsing/Common/ApiResponse.php (85%) rename src/{ => V1}/Parsing/Common/AsyncPredictResponse.php (78%) rename src/{ => V1}/Parsing/Common/Document.php (85%) rename src/{ => V1}/Parsing/Common/Execution.php (97%) rename src/{ => V1}/Parsing/Common/ExecutionFile.php (93%) rename src/{ => V1}/Parsing/Common/Extras/CropperExtra.php (92%) rename src/{ => V1}/Parsing/Common/Extras/Extras.php (98%) rename src/{ => V1}/Parsing/Common/Extras/FullTextOcrExtra.php (90%) rename src/{ => V1}/Parsing/Common/Extras/RAGExtra.php (94%) rename src/{ => V1}/Parsing/Common/Inference.php (84%) rename src/{ => V1}/Parsing/Common/Job.php (98%) rename src/{Parsing/Common/Ocr => V1/Parsing/Common/OCR}/MVisionV1.php (86%) rename src/{Parsing/Common/Ocr/Ocr.php => V1/Parsing/Common/OCR/OCR.php} (90%) rename src/{Parsing/Common/Ocr/OcrLine.php => V1/Parsing/Common/OCR/OCRLine.php} (80%) rename src/{Parsing/Common/Ocr/OcrPage.php => V1/Parsing/Common/OCR/OCRPage.php} (82%) rename src/{Parsing/Common/Ocr/OcrWord.php => V1/Parsing/Common/OCR/OCRWord.php} (86%) rename src/{ => V1}/Parsing/Common/OrientationField.php (93%) rename src/{ => V1}/Parsing/Common/Page.php (96%) rename src/{ => V1}/Parsing/Common/PredictResponse.php (79%) rename src/{ => V1}/Parsing/Common/Prediction.php (85%) rename src/{ => V1}/Parsing/Common/Product.php (94%) rename src/{ => V1}/Parsing/Common/WorkflowResponse.php (90%) rename src/{ => V1}/Parsing/Generated/GeneratedListField.php (96%) rename src/{ => V1}/Parsing/Generated/GeneratedObjectField.php (97%) rename src/{ => V1}/Parsing/Standard/AddressField.php (98%) rename src/{ => V1}/Parsing/Standard/AmountField.php (96%) rename src/{ => V1}/Parsing/Standard/BaseField.php (98%) rename src/{ => V1}/Parsing/Standard/BooleanField.php (87%) rename src/{ => V1}/Parsing/Standard/ClassificationField.php (95%) rename src/{ => V1}/Parsing/Standard/CompanyRegistrationField.php (87%) rename src/{ => V1}/Parsing/Standard/DateField.php (98%) rename src/{ => V1}/Parsing/Standard/FieldConfidenceMixin.php (94%) rename src/{ => V1}/Parsing/Standard/FieldPositionMixin.php (94%) rename src/{ => V1}/Parsing/Standard/LocaleField.php (98%) rename src/{ => V1}/Parsing/Standard/PaymentDetailsField.php (98%) rename src/{ => V1}/Parsing/Standard/PositionField.php (98%) rename src/{ => V1}/Parsing/Standard/StringField.php (96%) rename src/{ => V1}/Parsing/Standard/TaxField.php (98%) rename src/{ => V1}/Parsing/Standard/Taxes.php (97%) create mode 100644 src/V1/Parsing/SummaryHelperV1.php rename src/{ => V1}/Product/BarcodeReader/BarcodeReaderV1.php (84%) rename src/{ => V1}/Product/BarcodeReader/BarcodeReaderV1Document.php (88%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1.php (84%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1Carrier.php (72%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1CarrierItem.php (57%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1CarrierItems.php (97%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1Consignee.php (71%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1Document.php (95%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1NotifyParty.php (71%) rename src/{ => V1}/Product/BillOfLading/BillOfLadingV1Shipper.php (71%) rename src/{ => V1}/Product/BusinessCard/BusinessCardV1.php (84%) rename src/{ => V1}/Product/BusinessCard/BusinessCardV1Document.php (95%) rename src/{ => V1}/Product/Cropper/CropperV1.php (84%) rename src/{ => V1}/Product/Cropper/CropperV1Document.php (75%) rename src/{ => V1}/Product/Cropper/CropperV1Page.php (84%) rename src/{ => V1}/Product/DeliveryNote/DeliveryNoteV1.php (84%) rename src/{ => V1}/Product/DeliveryNote/DeliveryNoteV1Document.php (91%) rename src/{ => V1}/Product/DriverLicense/DriverLicenseV1.php (84%) rename src/{ => V1}/Product/DriverLicense/DriverLicenseV1Document.php (95%) rename src/{ => V1}/Product/FinancialDocument/FinancialDocumentV1.php (84%) rename src/{ => V1}/Product/FinancialDocument/FinancialDocumentV1Document.php (96%) rename src/{ => V1}/Product/FinancialDocument/FinancialDocumentV1LineItem.php (55%) rename src/{ => V1}/Product/FinancialDocument/FinancialDocumentV1LineItems.php (97%) rename src/{ => V1}/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php (84%) rename src/{ => V1}/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php (88%) rename src/{ => V1}/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php (84%) rename src/{ => V1}/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php (70%) rename src/{ => V1}/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php (90%) rename src/{ => V1}/Product/Fr/CarteGrise/CarteGriseV1.php (84%) rename src/{ => V1}/Product/Fr/CarteGrise/CarteGriseV1Document.php (98%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1.php (84%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1Document.php (95%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php (75%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php (75%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php (56%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php (98%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php (72%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1Subscription.php (59%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php (97%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php (59%) rename src/{ => V1}/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php (97%) rename src/{ => V1}/Product/Fr/HealthCard/HealthCardV1.php (84%) rename src/{ => V1}/Product/Fr/HealthCard/HealthCardV1Document.php (89%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV1.php (84%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV1Document.php (94%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV1Page.php (83%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV2.php (84%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV2Document.php (96%) rename src/{ => V1}/Product/Fr/IdCard/IdCardV2Page.php (86%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3.php (84%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3BankAccountDetail.php (72%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3Document.php (96%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3Employee.php (66%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3Employer.php (67%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3Employment.php (66%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3PaidTimeOff.php (61%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php (97%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3PayDetail.php (69%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3PayPeriod.php (69%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3SalaryDetail.php (61%) rename src/{ => V1}/Product/Fr/Payslip/PayslipV3SalaryDetails.php (97%) rename src/{ => V1}/Product/Generated/GeneratedV1.php (88%) rename src/{ => V1}/Product/Generated/GeneratedV1Document.php (90%) rename src/{ => V1}/Product/Generated/GeneratedV1Page.php (91%) rename src/{ => V1}/Product/Generated/GeneratedV1Prediction.php (91%) rename src/{ => V1}/Product/Ind/IndianPassport/IndianPassportV1.php (84%) rename src/{ => V1}/Product/Ind/IndianPassport/IndianPassportV1Document.php (96%) rename src/{ => V1}/Product/InternationalId/InternationalIdV2.php (84%) rename src/{ => V1}/Product/InternationalId/InternationalIdV2Document.php (95%) rename src/{ => V1}/Product/Invoice/InvoiceV4.php (84%) rename src/{ => V1}/Product/Invoice/InvoiceV4Document.php (95%) rename src/{ => V1}/Product/Invoice/InvoiceV4LineItem.php (55%) rename src/{ => V1}/Product/Invoice/InvoiceV4LineItems.php (98%) rename src/{ => V1}/Product/InvoiceSplitter/InvoiceSplitterV1.php (84%) rename src/{ => V1}/Product/InvoiceSplitter/InvoiceSplitterV1Document.php (87%) rename src/{ => V1}/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php (80%) rename src/{ => V1}/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php (97%) rename src/{ => V1}/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php (84%) rename src/{ => V1}/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php (83%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1.php (84%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php (97%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php (61%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php (97%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php (76%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php (73%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php (75%) rename src/{ => V1}/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php (75%) rename src/{ => V1}/Product/Passport/PassportV1.php (84%) rename src/{ => V1}/Product/Passport/PassportV1Document.php (94%) rename src/{ => V1}/Product/Receipt/ReceiptV5.php (84%) rename src/{ => V1}/Product/Receipt/ReceiptV5Document.php (93%) rename src/{ => V1}/Product/Receipt/ReceiptV5LineItem.php (61%) rename src/{ => V1}/Product/Receipt/ReceiptV5LineItems.php (98%) rename src/{ => V1}/Product/Resume/ResumeV1.php (84%) rename src/{ => V1}/Product/Resume/ResumeV1Certificate.php (61%) rename src/{ => V1}/Product/Resume/ResumeV1Certificates.php (98%) rename src/{ => V1}/Product/Resume/ResumeV1Document.php (96%) rename src/{ => V1}/Product/Resume/ResumeV1Education.php (56%) rename src/{ => V1}/Product/Resume/ResumeV1Educations.php (98%) rename src/{ => V1}/Product/Resume/ResumeV1Language.php (67%) rename src/{ => V1}/Product/Resume/ResumeV1Languages.php (97%) rename src/{ => V1}/Product/Resume/ResumeV1ProfessionalExperience.php (54%) rename src/{ => V1}/Product/Resume/ResumeV1ProfessionalExperiences.php (98%) rename src/{ => V1}/Product/Resume/ResumeV1SocialNetworksUrl.php (67%) rename src/{ => V1}/Product/Resume/ResumeV1SocialNetworksUrls.php (98%) rename src/{ => V1}/Product/Us/BankCheck/BankCheckV1.php (84%) rename src/{ => V1}/Product/Us/BankCheck/BankCheckV1Document.php (90%) rename src/{ => V1}/Product/Us/BankCheck/BankCheckV1Page.php (88%) rename src/{ => V1}/Product/Us/HealthcareCard/HealthcareCardV1.php (84%) rename src/{ => V1}/Product/Us/HealthcareCard/HealthcareCardV1Copay.php (66%) rename src/{ => V1}/Product/Us/HealthcareCard/HealthcareCardV1Copays.php (97%) rename src/{ => V1}/Product/Us/HealthcareCard/HealthcareCardV1Document.php (95%) rename src/{ => V1}/Product/Us/UsMail/UsMailV3.php (84%) rename src/{ => V1}/Product/Us/UsMail/UsMailV3Document.php (92%) rename src/{ => V1}/Product/Us/UsMail/UsMailV3RecipientAddress.php (54%) rename src/{ => V1}/Product/Us/UsMail/UsMailV3RecipientAddresses.php (98%) rename src/{ => V1}/Product/Us/UsMail/UsMailV3SenderAddress.php (69%) rename src/{ClientV2.php => V2/Client.php} (91%) rename src/{Http/MindeeApiV2.php => V2/HTTP/MindeeAPIV2.php} (98%) rename src/{Error => V2/Parsing}/ErrorItem.php (94%) rename src/{Parsing/V2 => V2/Parsing}/ErrorResponse.php (95%) rename src/{Parsing/V2 => V2/Parsing/Inference}/BaseResponse.php (93%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/BaseField.php (97%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/FieldConfidence.php (97%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/FieldLocation.php (95%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/InferenceFields.php (98%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/ListField.php (94%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/ObjectField.php (98%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Field/SimpleField.php (95%) rename src/{Parsing/V2 => V2/Parsing/Inference}/Inference.php (93%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceActiveOptions.php (94%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceFile.php (96%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceJob.php (93%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceModel.php (93%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceResponse.php (93%) rename src/{Parsing/V2 => V2/Parsing/Inference}/InferenceResult.php (81%) rename src/{Parsing/V2/RagMetadata.php => V2/Parsing/Inference/RAGMetadata.php} (87%) rename src/{Parsing/V2 => V2/Parsing/Inference}/RawText.php (95%) rename src/{Parsing/V2 => V2/Parsing/Inference}/RawTextPage.php (93%) rename src/{Parsing/V2 => V2/Parsing}/Job.php (98%) rename src/{Parsing/V2 => V2/Parsing}/JobResponse.php (83%) rename src/{Parsing/V2 => V2/Parsing}/JobWebhook.php (98%) rename src/{Input => V2/Product/Extraction/Params}/DataSchema.php (98%) rename src/{Parsing/V2 => V2/Product/Extraction/Params}/DataSchemaActiveOption.php (92%) rename src/{Input => V2/Product/Extraction/Params}/DataSchemaField.php (98%) rename src/{Input => V2/Product/Extraction/Params}/DataSchemaReplace.php (96%) rename src/{Input => V2/Product/Extraction/Params}/InferenceParameters.php (97%) rename tests/Dependencies/{DependencyCheckerNoExtendedTestPdf.php => DependencyCheckerNoExtendedTestPDF.php} (78%) rename tests/Dependencies/{DependencyCheckerPdfTest.php => DependencyCheckerPDFTest.php} (85%) rename tests/V1/Extraction/{PdfExtractorTest.php => PDFExtractorTest.php} (89%) rename tests/V1/Parsing/Common/{Ocr/OcrTest.php => OCR/OCRTest.php} (88%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d9b1131..9003c542 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Mindee PHP API Library Changelog +## v3.0.0-alpha1 - 2026-05-11 +### ¡Breaking Changes! +* +### Changes +* :sparkles: add support for extraction in crop, split, and classification +### Fixes +* + + ## v2.9.0 - 2026-05-07 ### Changes * :sparkles: add support for extraction in crop, split, and classification diff --git a/bin/MindeeCLICommand.php b/bin/MindeeCLICommand.php index c7334193..0685284c 100644 --- a/bin/MindeeCLICommand.php +++ b/bin/MindeeCLICommand.php @@ -2,22 +2,21 @@ namespace Mindee\CLI; -use Mindee\Client; use Mindee\Error\MindeeHttpException; use Mindee\Input\InputSource; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; -use Mindee\Input\PredictMethodOptions; -use Mindee\Input\PredictOptions; use Mindee\Input\URLInputSource; -use Mindee\Parsing\Common\AsyncPredictResponse; -use Mindee\Parsing\Common\PredictResponse; +use Mindee\V1\Client; +use Mindee\V1\ClientOptions\PredictMethodOptions; +use Mindee\V1\ClientOptions\PredictOptions; +use Mindee\V1\Parsing\Common\AsyncPredictResponse; +use Mindee\V1\Parsing\Common\PredictResponse; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; - use const Mindee\Input\KEEP_ONLY; use const Mindee\Input\REMOVE; use const Mindee\VERSION; diff --git a/bin/MindeeCLIDocuments.php b/bin/MindeeCLIDocuments.php index 83411e52..21c34140 100644 --- a/bin/MindeeCLIDocuments.php +++ b/bin/MindeeCLIDocuments.php @@ -16,157 +16,157 @@ public static function getSpecs(): array return [ "generated" => new DocumentCommandConfig( "Custom document type from docTI", - \Mindee\Product\Generated\GeneratedV1::class, + \Mindee\V1\Product\Generated\GeneratedV1::class, false, true ), "barcode-reader" => new DocumentCommandConfig( "Barcode Reader", - \Mindee\Product\BarcodeReader\BarcodeReaderV1::class, + \Mindee\V1\Product\BarcodeReader\BarcodeReaderV1::class, true, false ), "bill-of-lading" => new DocumentCommandConfig( "Bill of Lading", - \Mindee\Product\BillOfLading\BillOfLadingV1::class, + \Mindee\V1\Product\BillOfLading\BillOfLadingV1::class, false, true ), "business-card" => new DocumentCommandConfig( "Business Card", - \Mindee\Product\BusinessCard\BusinessCardV1::class, + \Mindee\V1\Product\BusinessCard\BusinessCardV1::class, false, true ), "cropper" => new DocumentCommandConfig( "Cropper", - \Mindee\Product\Cropper\CropperV1::class, + \Mindee\V1\Product\Cropper\CropperV1::class, true, false ), "delivery-note" => new DocumentCommandConfig( "Delivery note", - \Mindee\Product\DeliveryNote\DeliveryNoteV1::class, + \Mindee\V1\Product\DeliveryNote\DeliveryNoteV1::class, false, true ), "driver-license" => new DocumentCommandConfig( "Driver License", - \Mindee\Product\DriverLicense\DriverLicenseV1::class, + \Mindee\V1\Product\DriverLicense\DriverLicenseV1::class, false, true ), "financial-document" => new DocumentCommandConfig( "Financial Document", - \Mindee\Product\FinancialDocument\FinancialDocumentV1::class, + \Mindee\V1\Product\FinancialDocument\FinancialDocumentV1::class, true, true ), "fr-bank-account-details" => new DocumentCommandConfig( "FR Bank Account Details", - \Mindee\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, + \Mindee\V1\Product\Fr\BankAccountDetails\BankAccountDetailsV2::class, true, false ), "fr-carte-grise" => new DocumentCommandConfig( "FR Carte Grise", - \Mindee\Product\Fr\CarteGrise\CarteGriseV1::class, + \Mindee\V1\Product\Fr\CarteGrise\CarteGriseV1::class, true, false ), "fr-energy-bill" => new DocumentCommandConfig( "FR Energy Bill", - \Mindee\Product\Fr\EnergyBill\EnergyBillV1::class, + \Mindee\V1\Product\Fr\EnergyBill\EnergyBillV1::class, false, true ), "fr-health-card" => new DocumentCommandConfig( "FR Health Card", - \Mindee\Product\Fr\HealthCard\HealthCardV1::class, + \Mindee\V1\Product\Fr\HealthCard\HealthCardV1::class, false, true ), "fr-carte-nationale-d-identite" => new DocumentCommandConfig( "FR Carte Nationale d'Identité", - \Mindee\Product\Fr\IdCard\IdCardV2::class, + \Mindee\V1\Product\Fr\IdCard\IdCardV2::class, true, false ), "fr-payslip" => new DocumentCommandConfig( "FR Payslip", - \Mindee\Product\Fr\Payslip\PayslipV3::class, + \Mindee\V1\Product\Fr\Payslip\PayslipV3::class, false, true ), "ind-passport-india" => new DocumentCommandConfig( "IND Passport - India", - \Mindee\Product\Ind\IndianPassport\IndianPassportV1::class, + \Mindee\V1\Product\Ind\IndianPassport\IndianPassportV1::class, false, true ), "international-id" => new DocumentCommandConfig( "International ID", - \Mindee\Product\InternationalId\InternationalIdV2::class, + \Mindee\V1\Product\InternationalId\InternationalIdV2::class, false, true ), "invoice" => new DocumentCommandConfig( "Invoice", - \Mindee\Product\Invoice\InvoiceV4::class, + \Mindee\V1\Product\Invoice\InvoiceV4::class, true, true ), "invoice-splitter" => new DocumentCommandConfig( "Invoice Splitter", - \Mindee\Product\InvoiceSplitter\InvoiceSplitterV1::class, + \Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1::class, false, true ), "multi-receipts-detector" => new DocumentCommandConfig( "Multi Receipts Detector", - \Mindee\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, + \Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, true, false ), "nutrition-facts-label" => new DocumentCommandConfig( "Nutrition Facts Label", - \Mindee\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, + \Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, false, true ), "passport" => new DocumentCommandConfig( "Passport", - \Mindee\Product\Passport\PassportV1::class, + \Mindee\V1\Product\Passport\PassportV1::class, true, false ), "receipt" => new DocumentCommandConfig( "Receipt", - \Mindee\Product\Receipt\ReceiptV5::class, + \Mindee\V1\Product\Receipt\ReceiptV5::class, true, true ), "resume" => new DocumentCommandConfig( "Resume", - \Mindee\Product\Resume\ResumeV1::class, + \Mindee\V1\Product\Resume\ResumeV1::class, false, true ), "us-bank-check" => new DocumentCommandConfig( "US Bank Check", - \Mindee\Product\Us\BankCheck\BankCheckV1::class, + \Mindee\V1\Product\Us\BankCheck\BankCheckV1::class, true, false ), "us-healthcare-card" => new DocumentCommandConfig( "US Healthcare Card", - \Mindee\Product\Us\HealthcareCard\HealthcareCardV1::class, + \Mindee\V1\Product\Us\HealthcareCard\HealthcareCardV1::class, false, true ), "us-us-mail" => new DocumentCommandConfig( "US US Mail", - \Mindee\Product\Us\UsMail\UsMailV3::class, + \Mindee\V1\Product\Us\UsMail\UsMailV3::class, false, true ), diff --git a/docs/code_samples/bank_account_details_v1.txt b/docs/code_samples/bank_account_details_v1.txt index dfd63f64..af944d38 100644 --- a/docs/code_samples/bank_account_details_v1.txt +++ b/docs/code_samples/bank_account_details_v1.txt @@ -1,7 +1,7 @@ isPdf() && $inputSource->getPageCount() > 1) { - parseMultiPage($inputSource, $mindeeClient); - } else { - parseSinglePage($inputSource, $mindeeClient); - } -} - -function parseSinglePage(PathInput $inputSource, Client $mindeeClient) -{ - $invoiceResult = $mindeeClient->parse(InvoiceV4::class, $inputSource); - echo $invoiceResult->document; -} - -function parseMultiPage(PathInput $inputSource, Client $mindeeClient) -{ - global $mindeeClient; - $pdfExtractor = new PdfExtractor($inputSource); - $invoiceSplitterResponse = $mindeeClient->enqueueAndParse( - InvoiceSplitterV1::class, - $inputSource - ); - $pageGroups = $invoiceSplitterResponse->document->inference->prediction->invoicePageGroups; - $extractedPdfs = $pdfExtractor->extractInvoices($pageGroups); - - foreach ($extractedPdfs as $extractedPdf) { - // Optional: Save the files locally - // $extractedPdf->writeToFile("output/path"); - - $invoiceResult = $mindeeClient->parse( - InvoiceV4::class, - $extractedPdf->asInputSource() - ); - echo $invoiceResult->document; - } -} - -$mindeeClient = new Client("my-api-key-here"); -// $mindeeClient = new Client(); // Optionally, use an environment variable. -$inputPath = "path/to/your/file.ext"; -parseInvoice($inputPath, $mindeeClient); diff --git a/examples/MultiReceiptsAutoExtractionExample.php b/examples/MultiReceiptsAutoExtractionExample.php deleted file mode 100644 index 05f07282..00000000 --- a/examples/MultiReceiptsAutoExtractionExample.php +++ /dev/null @@ -1,37 +0,0 @@ -parse(MultiReceiptsDetectorV1::class, $inputSource); - $pageCount = $inputSource->getPageCount(); - - $totalExtractedReceipts = []; - - for ($i = 0; $i < $pageCount; $i++) { - $receiptsPositions = $multiReceiptsResult->document->inference->pages[$i]->prediction->receipts; - $extractedReceipts = $imageExtractor->extractImagesFromPage($receiptsPositions, $i); - $totalExtractedReceipts = array_merge($totalExtractedReceipts, $extractedReceipts); - } - - foreach ($totalExtractedReceipts as $receipt) { - // Optional: save the extracted receipts to a file - // $receipt->writeToFile("output/path"); - - $result = $client->parse(ReceiptV5::class, $receipt->asInputSource()); - echo $result->document . "\n"; - } -} -processReceipts($mindeeClient, $inputPath); diff --git a/src/Input/PollingOptions.php b/src/ClientOptions/PollingOptions.php similarity index 98% rename from src/Input/PollingOptions.php rename to src/ClientOptions/PollingOptions.php index 60e2c3e3..99f4b5f1 100644 --- a/src/Input/PollingOptions.php +++ b/src/ClientOptions/PollingOptions.php @@ -1,6 +1,6 @@ pdfBytes; } diff --git a/src/Extraction/ImageExtractor.php b/src/Extraction/ImageExtractor.php index 16bc580a..c9519434 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Extraction/ImageExtractor.php @@ -2,6 +2,7 @@ namespace Mindee\Extraction; +use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeGeometryException; use Mindee\Error\MindeeImageException; @@ -10,8 +11,7 @@ use Mindee\Geometry\BBoxUtils; use Mindee\Geometry\Polygon; use Mindee\Input\LocalInputSource; -use Mindee\Parsing\DependencyChecker; -use Mindee\Parsing\Standard\BaseField; +use Mindee\V1\Parsing\Standard\BaseField; /** * Extract sub-images from an image. diff --git a/src/Extraction/PdfExtractor.php b/src/Extraction/PDFExtractor.php similarity index 95% rename from src/Extraction/PdfExtractor.php rename to src/Extraction/PDFExtractor.php index 36bac699..e6e6b39c 100644 --- a/src/Extraction/PdfExtractor.php +++ b/src/Extraction/PDFExtractor.php @@ -2,10 +2,10 @@ namespace Mindee\Extraction; +use Mindee\Dependency\DependencyChecker; use Mindee\Error\MindeePDFException; use Mindee\Input\LocalInputSource; -use Mindee\Parsing\DependencyChecker; -use Mindee\Product\InvoiceSplitter\InvoiceSplitterV1InvoicePageGroups; +use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1InvoicePageGroups; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; use setasign\Fpdi\PdfParser\Filter\FilterException; @@ -15,7 +15,7 @@ /** * PDF extraction class. */ -class PdfExtractor +class PDFExtractor { /** * @var string bytes representation of a file @@ -79,7 +79,7 @@ public function getPageCount(): int * * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * - * @return ExtractedPdf[] list of extracted documents + * @return ExtractedPDF[] list of extracted documents * * @throws MindeePDFException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. * @throws \InvalidArgumentException Throws if invalid indexes are provided. @@ -123,7 +123,7 @@ public function extractSubDocuments(mixed $pageIndexes): array ) { throw new MindeePDFException("PDF file couldn't be processed during extraction.", 0, $e); } - $extractedPdfs[] = new ExtractedPdf($mergedPdfBytes, $fieldFilename); + $extractedPdfs[] = new ExtractedPDF($mergedPdfBytes, $fieldFilename); } return $extractedPdfs; @@ -135,7 +135,7 @@ public function extractSubDocuments(mixed $pageIndexes): array * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * @param boolean $strict Whether to trust confidence scores or not. * - * @return ExtractedPdf[] a list of extracted invoices + * @return ExtractedPDF[] a list of extracted invoices */ public function extractInvoices(mixed $pageIndexes, bool $strict = false): array { diff --git a/src/Image/ImageCompressor.php b/src/Image/ImageCompressor.php index 0d339f2a..e88dedba 100644 --- a/src/Image/ImageCompressor.php +++ b/src/Image/ImageCompressor.php @@ -2,10 +2,10 @@ namespace Mindee\Image; +use Mindee\Dependency\DependencyChecker; +use Mindee\Error\ErrorCode; use Mindee\Error\MindeeImageException; use Mindee\Error\MindeeUnhandledException; -use Mindee\Parsing\DependencyChecker; -use Mindee\Error\ErrorCode; /** * Image compressor class to handle image compression. diff --git a/src/PDF/PDFCompressor.php b/src/PDF/PDFCompressor.php index 5906f6a3..5ec84f23 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/PDF/PDFCompressor.php @@ -2,10 +2,10 @@ namespace Mindee\PDF; +use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeePDFException; use Mindee\Error\MindeeUnhandledException; -use Mindee\Parsing\DependencyChecker; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; use Smalot\PdfParser\Config; @@ -65,10 +65,10 @@ public static function compress( try { $fpdi = new CustomFPDI(); $pageCount = $fpdi->setSourceFile($pdfPath); - } catch (CrossReferenceException $e) { + } catch (CrossReferenceException) { error_log("[WARNING] PDF format for '$pdfPath' is not directly supported." . " Output PDF will be rasterized and source text won't be available."); - $pdfPath = PDFUtils::downgradePdfVersion($pdfPath); + $pdfPath = PDFUtils::downgradePDFVersion($pdfPath); $fpdi = new CustomFPDI(); $pdf = $parser->parseFile($pdfPath); $pageCount = $fpdi->setSourceFile($pdfPath); @@ -76,7 +76,7 @@ public static function compress( $outPdf = new CustomFPDI(); for ($i = 1; $i <= $pageCount; $i++) { - list($tempJpegFile, $orientation) = static::processPdfPage($pdfPath, $i, $quality); + list($tempJpegFile, $orientation) = static::processPDFPage($pdfPath, $i, $quality); list($width, $height) = getimagesize($tempJpegFile); $outPdf->AddPage($orientation, [$width, $height]); $outPdf->Image($tempJpegFile, 0, 0, $width, $height); @@ -207,7 +207,7 @@ private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): v * @return array Path to the temporary JPEG file and orientation of the page. * @throws MindeePDFException If there's an error processing the page. */ - private static function processPdfPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array + private static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array { try { $singlePagePdf = new FPDI(); diff --git a/src/PDF/PDFUtils.php b/src/PDF/PDFUtils.php index 710cfccf..63047e35 100644 --- a/src/PDF/PDFUtils.php +++ b/src/PDF/PDFUtils.php @@ -111,7 +111,7 @@ public static function extractPagesTextElements(string $pdfPath): array * @throws MindeePDFException Throws if the file can't be handled through Imagick. * @throws Exception Will be thrown as MindeePDFException, this is just for PHPCS linting purposes. */ - public static function downgradePdfVersion(string $inputPath): string + public static function downgradePDFVersion(string $inputPath): string { try { $outputPath = tempnam(sys_get_temp_dir(), 'downgrade_pdf_') . '.pdf'; diff --git a/src/Parsing/Common/SummaryHelper.php b/src/Parsing/SummaryHelper.php similarity index 77% rename from src/Parsing/Common/SummaryHelper.php rename to src/Parsing/SummaryHelper.php index 9165acfc..c9c54381 100644 --- a/src/Parsing/Common/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -1,9 +1,9 @@ 0 ? $endpointVersion : '1'; - $endpointSettings = new MindeeApi($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); + $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); return new Endpoint($endpointName, $endpointOwner, $endpointVersion, $endpointSettings); } @@ -329,7 +330,7 @@ private function makeWorkflowExecutionRequest( string $workflowId, PredictMethodOptions $options ): WorkflowResponse { - $workflowRouterSettings = new MindeeWorkflowApi($this->apiKey, $workflowId); + $workflowRouterSettings = new MindeeWorkflowAPI($this->apiKey, $workflowId); $options->endpoint = new WorkflowEndpoint($workflowRouterSettings); if (!$options->pageOptions->isEmpty()) { if ($inputDoc instanceof LocalInputSource) { diff --git a/src/Input/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php similarity index 96% rename from src/Input/CommonOptions.php rename to src/V1/ClientOptions/CommonOptions.php index fca8df40..adeee460 100644 --- a/src/Input/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -1,6 +1,6 @@ urlName = $urlName; diff --git a/src/Http/MindeeApi.php b/src/V1/HTTP/MindeeAPI.php similarity index 95% rename from src/Http/MindeeApi.php rename to src/V1/HTTP/MindeeAPI.php index bf206b66..ccc7a5cf 100644 --- a/src/Http/MindeeApi.php +++ b/src/V1/HTTP/MindeeAPI.php @@ -4,16 +4,16 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\Http; +namespace Mindee\V1\HTTP; -use Mindee\Client; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; +use Mindee\V1\Client; /** * Data class containing settings for endpoints. */ -class MindeeApi extends BaseApi +class MindeeAPI extends BaseAPI { /** * @var string Name of the endpoint. diff --git a/src/Http/MindeeWorkflowApi.php b/src/V1/HTTP/MindeeWorkflowAPI.php similarity index 94% rename from src/Http/MindeeWorkflowApi.php rename to src/V1/HTTP/MindeeWorkflowAPI.php index 0e0a6f2d..38a57953 100644 --- a/src/Http/MindeeWorkflowApi.php +++ b/src/V1/HTTP/MindeeWorkflowAPI.php @@ -4,7 +4,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\Http; +namespace Mindee\V1\HTTP; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; @@ -12,7 +12,7 @@ /** * Data class containing settings for workflows. */ -class MindeeWorkflowApi extends BaseApi +class MindeeWorkflowAPI extends BaseAPI { /** * @var string ID of the workflow. diff --git a/src/Http/ResponseValidation.php b/src/V1/HTTP/ResponseValidation.php similarity index 99% rename from src/Http/ResponseValidation.php rename to src/V1/HTTP/ResponseValidation.php index 74d3518d..047ce24d 100644 --- a/src/Http/ResponseValidation.php +++ b/src/V1/HTTP/ResponseValidation.php @@ -4,7 +4,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\Http; +namespace Mindee\V1\HTTP; /** * Wrapper class for http requests/responses validation handling. diff --git a/src/Http/WorkflowEndpoint.php b/src/V1/HTTP/WorkflowEndpoint.php similarity index 93% rename from src/Http/WorkflowEndpoint.php rename to src/V1/HTTP/WorkflowEndpoint.php index 219a70e1..16932d5f 100644 --- a/src/Http/WorkflowEndpoint.php +++ b/src/V1/HTTP/WorkflowEndpoint.php @@ -1,11 +1,11 @@ ocr = new Ocr($rawResponse['ocr']); + $this->ocr = new OCR($rawResponse['ocr']); } if (array_key_exists("extras", $rawResponse['inference']) && $rawResponse['inference']['extras']) { $this->extras = new Extras($rawResponse['inference']['extras']); diff --git a/src/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php similarity index 97% rename from src/Parsing/Common/Execution.php rename to src/V1/Parsing/Common/Execution.php index 7fb83ab8..6d115454 100644 --- a/src/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -1,12 +1,12 @@ pages = []; foreach ($rawPrediction['pages'] as $pagePrediction) { - $this->pages[] = new OcrPage($pagePrediction); + $this->pages[] = new OCRPage($pagePrediction); } } diff --git a/src/Parsing/Common/Ocr/Ocr.php b/src/V1/Parsing/Common/OCR/OCR.php similarity index 90% rename from src/Parsing/Common/Ocr/Ocr.php rename to src/V1/Parsing/Common/OCR/OCR.php index 6cefb57d..1b2648ba 100644 --- a/src/Parsing/Common/Ocr/Ocr.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -1,14 +1,14 @@ words, "Mindee\\Parsing\\Common\\Ocr\\OcrPage::getMinMaxX"); + usort($this->words, "Mindee\\V1\\Parsing\\Common\\OCR\\OCRPage::getMinMaxX"); } /** * Appends a word to the line. * - * @param \Mindee\Parsing\Common\Ocr\OcrWord $word Word to add. + * @param OCRWord $word Word to add. * @return void */ - public function add(OcrWord $word) + public function add(OCRWord $word) { $this->words[] = $word; } diff --git a/src/Parsing/Common/Ocr/OcrPage.php b/src/V1/Parsing/Common/OCR/OCRPage.php similarity index 82% rename from src/Parsing/Common/Ocr/OcrPage.php rename to src/V1/Parsing/Common/OCR/OCRPage.php index 8cee1982..67e4b783 100644 --- a/src/Parsing/Common/Ocr/OcrPage.php +++ b/src/V1/Parsing/Common/OCR/OCRPage.php @@ -1,11 +1,11 @@ polygon->isPointInY($currentWord->polygon->getCentroid()); $nextInCurrent = $currentWord->polygon->isPointInY($nextWord->polygon->getCentroid()); @@ -33,11 +33,11 @@ private static function areWordsOnSameLine(OcrWord $currentWord, OcrWord $nextWo /** * Compares word positions on the X axis. Returns a sort-compliant result (0;-1;1). * - * @param OcrWord $word1 First word. - * @param OcrWord $word2 Second word. + * @param OCRWord $word1 First word. + * @param OCRWord $word2 Second word. * @return integer */ - public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int + public static function getMinMaxX(OCRWord $word1, OCRWord $word2): int { $word1X = $word1->polygon->getMinMaxX()->getMin(); $word2X = $word2->polygon->getMinMaxX()->getMin(); @@ -50,11 +50,11 @@ public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int /** * Compares word positions on the Y axis. Returns a sort-compliant result (0;-1;1). * - * @param OcrWord $word1 First word. - * @param OcrWord $word2 Second word. + * @param OCRWord $word1 First word. + * @param OCRWord $word2 Second word. * @return integer */ - public static function getMinMaxY(OcrWord $word1, OcrWord $word2): int + public static function getMinMaxY(OCRWord $word1, OCRWord $word2): int { $word1Y = $word1->polygon->getMinMaxY()->getMin(); $word2Y = $word2->polygon->getMinMaxY()->getMin(); @@ -75,14 +75,14 @@ private function toLines(): array $indexes = []; $lines = []; foreach ($this->allWords as $w) { - $line = new OcrLine(); + $line = new OCRLine(); for ($idx = 0; $idx < count($this->allWords); $idx++) { $word = $this->allWords[$idx]; if (!in_array($idx, $indexes)) { if ($current == null) { $current = $word; $indexes[] = $idx; - $line = new OcrLine(); + $line = new OCRLine(); $line->add($word); } else { if ($this->areWordsOnSameLine($current, $word)) { @@ -131,7 +131,7 @@ public function __construct(array $rawPrediction) { $this->allWords = []; foreach ($rawPrediction['all_words'] as $wordPrediction) { - $this->allWords[] = new OcrWord($wordPrediction); + $this->allWords[] = new OCRWord($wordPrediction); } usort($this->allWords, "self::getMinMaxY"); } diff --git a/src/Parsing/Common/Ocr/OcrWord.php b/src/V1/Parsing/Common/OCR/OCRWord.php similarity index 86% rename from src/Parsing/Common/Ocr/OcrWord.php rename to src/V1/Parsing/Common/OCR/OCRWord.php index 197862a1..1ac5d46c 100644 --- a/src/Parsing/Common/Ocr/OcrWord.php +++ b/src/V1/Parsing/Common/OCR/OCRWord.php @@ -1,13 +1,13 @@ value); + return SummaryHelperV1::formatForDisplay($this->value); } } diff --git a/src/Parsing/Standard/ClassificationField.php b/src/V1/Parsing/Standard/ClassificationField.php similarity index 95% rename from src/Parsing/Standard/ClassificationField.php rename to src/V1/Parsing/Standard/ClassificationField.php index d530f90d..9d31848f 100644 --- a/src/Parsing/Standard/ClassificationField.php +++ b/src/V1/Parsing/Standard/ClassificationField.php @@ -1,6 +1,6 @@ type); - $printable['value'] = SummaryHelper::formatForDisplay($this->value); + $printable['type'] = SummaryHelperV1::formatForDisplay($this->type); + $printable['value'] = SummaryHelperV1::formatForDisplay($this->value); return $printable; } } diff --git a/src/Parsing/Standard/DateField.php b/src/V1/Parsing/Standard/DateField.php similarity index 98% rename from src/Parsing/Standard/DateField.php rename to src/V1/Parsing/Standard/DateField.php index 356ae224..d9d2c551 100644 --- a/src/Parsing/Standard/DateField.php +++ b/src/V1/Parsing/Standard/DateField.php @@ -1,6 +1,6 @@ pages[] = new Page(BarcodeReaderV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BarcodeReader/BarcodeReaderV1Document.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php similarity index 88% rename from src/Product/BarcodeReader/BarcodeReaderV1Document.php rename to src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php index 82d9a6ef..b7ac70cf 100644 --- a/src/Product/BarcodeReader/BarcodeReaderV1Document.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php @@ -1,11 +1,11 @@ pages[] = new Page(BillOfLadingV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php similarity index 72% rename from src/Product/BillOfLading/BillOfLadingV1Carrier.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php index 55b196e9..cd091c18 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Carrier.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php @@ -1,10 +1,10 @@ name); - $outArr["professionalNumber"] = SummaryHelper::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelper::formatForDisplay($this->scac); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); + $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); return $outArr; } @@ -62,9 +62,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelper::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelper::formatForDisplay($this->scac); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); + $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); return $outArr; } /** @@ -87,6 +87,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php similarity index 57% rename from src/Product/BillOfLading/BillOfLadingV1CarrierItem.php rename to src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php index 9b5d68fe..7fa82fe6 100644 --- a/src/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php @@ -1,10 +1,10 @@ description, 36); - $outArr["grossWeight"] = SummaryHelper::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelper::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelper::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelper::formatForDisplay($this->weightUnit); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); + $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); + $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); return $outArr; } @@ -83,12 +83,12 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["grossWeight"] = SummaryHelper::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelper::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelper::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelper::formatForDisplay($this->weightUnit); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); + $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); + $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); return $outArr; } /** @@ -100,13 +100,13 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["grossWeight"], 12); - $outStr .= SummaryHelper::padString($printable["measurement"], 11); - $outStr .= SummaryHelper::padString($printable["measurementUnit"], 16); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["weightUnit"], 11); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["grossWeight"], 12); + $outStr .= SummaryHelperV1::padString($printable["measurement"], 11); + $outStr .= SummaryHelperV1::padString($printable["measurementUnit"], 16); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["weightUnit"], 11); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -114,6 +114,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php similarity index 97% rename from src/Product/BillOfLading/BillOfLadingV1CarrierItems.php rename to src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index b579173e..89b38c3c 100644 --- a/src/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -1,6 +1,6 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } @@ -68,10 +68,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** @@ -95,6 +95,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Document.php b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php similarity index 95% rename from src/Product/BillOfLading/BillOfLadingV1Document.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Document.php index 8e836c2e..1eeed163 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Document.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php @@ -1,12 +1,12 @@ dateOfIssue :Departure Date: $this->departureDate "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php similarity index 71% rename from src/Product/BillOfLading/BillOfLadingV1NotifyParty.php rename to src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index ec96befb..25376e97 100644 --- a/src/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -1,10 +1,10 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } @@ -68,10 +68,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** @@ -95,6 +95,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php similarity index 71% rename from src/Product/BillOfLading/BillOfLadingV1Shipper.php rename to src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php index bd3ae072..75ca19cb 100644 --- a/src/Product/BillOfLading/BillOfLadingV1Shipper.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php @@ -1,10 +1,10 @@ address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } @@ -68,10 +68,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["email"] = SummaryHelper::formatForDisplay($this->email); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelper::formatForDisplay($this->phone); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); return $outArr; } /** @@ -95,6 +95,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/BusinessCard/BusinessCardV1.php b/src/V1/Product/BusinessCard/BusinessCardV1.php similarity index 84% rename from src/Product/BusinessCard/BusinessCardV1.php rename to src/V1/Product/BusinessCard/BusinessCardV1.php index f5697c46..3c93c46f 100644 --- a/src/Product/BusinessCard/BusinessCardV1.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1.php @@ -2,11 +2,11 @@ /** Business Card V1. */ -namespace Mindee\Product\BusinessCard; +namespace Mindee\V1\Product\BusinessCard; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Business Card API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BusinessCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/BusinessCard/BusinessCardV1Document.php b/src/V1/Product/BusinessCard/BusinessCardV1Document.php similarity index 95% rename from src/Product/BusinessCard/BusinessCardV1Document.php rename to src/V1/Product/BusinessCard/BusinessCardV1Document.php index 711ea6f7..50621a3b 100644 --- a/src/Product/BusinessCard/BusinessCardV1Document.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1Document.php @@ -1,11 +1,11 @@ website :Social Media: $socialMedia "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Cropper/CropperV1.php b/src/V1/Product/Cropper/CropperV1.php similarity index 84% rename from src/Product/Cropper/CropperV1.php rename to src/V1/Product/Cropper/CropperV1.php index e3863ffa..51718551 100644 --- a/src/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -2,11 +2,11 @@ /** Cropper V1. */ -namespace Mindee\Product\Cropper; +namespace Mindee\V1\Product\Cropper; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Cropper API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(CropperV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Cropper/CropperV1Document.php b/src/V1/Product/Cropper/CropperV1Document.php similarity index 75% rename from src/Product/Cropper/CropperV1Document.php rename to src/V1/Product/Cropper/CropperV1Document.php index aecf0b65..2920532f 100644 --- a/src/Product/Cropper/CropperV1Document.php +++ b/src/V1/Product/Cropper/CropperV1Document.php @@ -1,8 +1,8 @@ pages[] = new Page(DeliveryNoteV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php similarity index 91% rename from src/Product/DeliveryNote/DeliveryNoteV1Document.php rename to src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php index 426646b5..598a3350 100644 --- a/src/Product/DeliveryNote/DeliveryNoteV1Document.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php @@ -1,13 +1,13 @@ customerAddress :Total Amount: $this->totalAmount "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/DriverLicense/DriverLicenseV1.php b/src/V1/Product/DriverLicense/DriverLicenseV1.php similarity index 84% rename from src/Product/DriverLicense/DriverLicenseV1.php rename to src/V1/Product/DriverLicense/DriverLicenseV1.php index 43c2468a..c791542b 100644 --- a/src/Product/DriverLicense/DriverLicenseV1.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1.php @@ -2,11 +2,11 @@ /** Driver License V1. */ -namespace Mindee\Product\DriverLicense; +namespace Mindee\V1\Product\DriverLicense; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Driver License API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(DriverLicenseV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/DriverLicense/DriverLicenseV1Document.php b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php similarity index 95% rename from src/Product/DriverLicense/DriverLicenseV1Document.php rename to src/V1/Product/DriverLicense/DriverLicenseV1Document.php index c3ddb431..e9851eda 100644 --- a/src/Product/DriverLicense/DriverLicenseV1Document.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php @@ -1,12 +1,12 @@ mrz :DD Number: $this->ddNumber "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php similarity index 84% rename from src/Product/FinancialDocument/FinancialDocumentV1.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1.php index 5c153e3e..2a86164c 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php @@ -2,11 +2,11 @@ /** Financial Document V1. */ -namespace Mindee\Product\FinancialDocument; +namespace Mindee\V1\Product\FinancialDocument; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Financial Document API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(FinancialDocumentV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1Document.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php similarity index 96% rename from src/Product/FinancialDocument/FinancialDocumentV1Document.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php index e070e7f6..560569bd 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1Document.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php @@ -1,19 +1,19 @@ time :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php similarity index 55% rename from src/Product/FinancialDocument/FinancialDocumentV1LineItem.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php index ed04696d..c1722c8f 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -1,10 +1,10 @@ description, 36); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -97,14 +97,14 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -116,15 +116,15 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["productCode"], 12); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["taxAmount"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 12); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitMeasure"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["productCode"], 12); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["taxAmount"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 12); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitMeasure"], 15); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -132,6 +132,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php similarity index 97% rename from src/Product/FinancialDocument/FinancialDocumentV1LineItems.php rename to src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index b9340c2c..ca69c2e1 100644 --- a/src/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -1,6 +1,6 @@ pages[] = new Page(BankAccountDetailsV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php similarity index 88% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php index ceb8cc30..1f90c28e 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php @@ -1,11 +1,11 @@ accountHolderName :SWIFT Code: $this->swift "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php similarity index 84% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php index 532eaf80..4d7f7917 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php @@ -2,11 +2,11 @@ /** Bank Account Details V2. */ -namespace Mindee\Product\Fr\BankAccountDetails; +namespace Mindee\V1\Product\Fr\BankAccountDetails; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Bank Account Details API version 2 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(BankAccountDetailsV2Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php similarity index 70% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index 94297e1b..5a04e1b8 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -1,10 +1,10 @@ bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelper::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelper::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelper::formatForDisplay($this->bbanNumber); + $outArr["bbanBankCode"] = SummaryHelperV1::formatForDisplay($this->bbanBankCode); + $outArr["bbanBranchCode"] = SummaryHelperV1::formatForDisplay($this->bbanBranchCode); + $outArr["bbanKey"] = SummaryHelperV1::formatForDisplay($this->bbanKey); + $outArr["bbanNumber"] = SummaryHelperV1::formatForDisplay($this->bbanNumber); return $outArr; } @@ -68,10 +68,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["bbanBankCode"] = SummaryHelper::formatForDisplay($this->bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelper::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelper::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelper::formatForDisplay($this->bbanNumber); + $outArr["bbanBankCode"] = SummaryHelperV1::formatForDisplay($this->bbanBankCode); + $outArr["bbanBranchCode"] = SummaryHelperV1::formatForDisplay($this->bbanBranchCode); + $outArr["bbanKey"] = SummaryHelperV1::formatForDisplay($this->bbanKey); + $outArr["bbanNumber"] = SummaryHelperV1::formatForDisplay($this->bbanNumber); return $outArr; } /** @@ -95,6 +95,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php similarity index 90% rename from src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php rename to src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php index dfc3043a..10b844f3 100644 --- a/src/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php @@ -1,11 +1,11 @@ iban :SWIFT Code: $this->swiftCode "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/CarteGrise/CarteGriseV1.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php similarity index 84% rename from src/Product/Fr/CarteGrise/CarteGriseV1.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index ede84373..d1557163 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -2,11 +2,11 @@ /** Carte Grise V1. */ -namespace Mindee\Product\Fr\CarteGrise; +namespace Mindee\V1\Product\Fr\CarteGrise; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Carte Grise API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(CarteGriseV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/CarteGrise/CarteGriseV1Document.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php similarity index 98% rename from src/Product/Fr/CarteGrise/CarteGriseV1Document.php rename to src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php index 9342649a..b3119b21 100644 --- a/src/Product/Fr/CarteGrise/CarteGriseV1Document.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php @@ -1,12 +1,12 @@ mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php similarity index 84% rename from src/Product/Fr/EnergyBill/EnergyBillV1.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1.php index d027d1be..c49192cd 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php @@ -2,11 +2,11 @@ /** Energy Bill V1. */ -namespace Mindee\Product\Fr\EnergyBill; +namespace Mindee\V1\Product\Fr\EnergyBill; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Energy Bill API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(EnergyBillV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php similarity index 95% rename from src/Product/Fr/EnergyBill/EnergyBillV1Document.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php index 9667b67b..d64b1ae1 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php @@ -1,13 +1,13 @@ address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } @@ -56,8 +56,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } /** @@ -79,6 +79,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php similarity index 75% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php index b95eafc3..d19538e9 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php @@ -1,10 +1,10 @@ address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } @@ -56,8 +56,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); return $outArr; } /** @@ -79,6 +79,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php similarity index 56% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php index 4e6767a6..77c772a6 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php @@ -1,10 +1,10 @@ consumption); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -96,14 +96,14 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["consumption"] = SummaryHelper::formatFloat($this->consumption); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -115,15 +115,15 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["consumption"], 11); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unit"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["consumption"], 11); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $outStr .= SummaryHelperV1::padString($printable["unit"], 15); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -131,6 +131,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php similarity index 98% rename from src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 39f0b4c7..8a100ab5 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -1,6 +1,6 @@ meterNumber); - $outArr["meterType"] = SummaryHelper::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); + $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } @@ -62,9 +62,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["meterNumber"] = SummaryHelper::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelper::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); + $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** @@ -87,6 +87,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php similarity index 59% rename from src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php index 04c81e3e..60eb45b9 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php @@ -1,10 +1,10 @@ description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -83,12 +83,12 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -100,13 +100,13 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -114,6 +114,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php similarity index 97% rename from src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index 78d4818f..91d16dde 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -1,6 +1,6 @@ description, 36); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -83,12 +83,12 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelper::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["total"] = SummaryHelperV1::formatFloat($this->total); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -100,13 +100,13 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["endDate"], 10); - $outStr .= SummaryHelper::padString($printable["startDate"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 8); - $outStr .= SummaryHelper::padString($printable["total"], 9); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); + $outStr .= SummaryHelperV1::padString($printable["total"], 9); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -114,6 +114,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php similarity index 97% rename from src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php rename to src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 477416e1..167d4354 100644 --- a/src/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php @@ -1,6 +1,6 @@ pages[] = new Page(HealthCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/HealthCard/HealthCardV1Document.php b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php similarity index 89% rename from src/Product/Fr/HealthCard/HealthCardV1Document.php rename to src/V1/Product/Fr/HealthCard/HealthCardV1Document.php index 94f2d774..60798be2 100644 --- a/src/Product/Fr/HealthCard/HealthCardV1Document.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php @@ -1,12 +1,12 @@ socialSecurity :Issuance Date: $this->issuanceDate "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV1.php b/src/V1/Product/Fr/IdCard/IdCardV1.php similarity index 84% rename from src/Product/Fr/IdCard/IdCardV1.php rename to src/V1/Product/Fr/IdCard/IdCardV1.php index 16af405a..15049893 100644 --- a/src/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -2,11 +2,11 @@ /** Carte Nationale d'Identité V1. */ -namespace Mindee\Product\Fr\IdCard; +namespace Mindee\V1\Product\Fr\IdCard; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Carte Nationale d'Identité API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(IdCardV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/IdCard/IdCardV1Document.php b/src/V1/Product/Fr/IdCard/IdCardV1Document.php similarity index 94% rename from src/Product/Fr/IdCard/IdCardV1Document.php rename to src/V1/Product/Fr/IdCard/IdCardV1Document.php index b47a4705..0c2decad 100644 --- a/src/Product/Fr/IdCard/IdCardV1Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Document.php @@ -1,12 +1,12 @@ mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV1Page.php b/src/V1/Product/Fr/IdCard/IdCardV1Page.php similarity index 83% rename from src/Product/Fr/IdCard/IdCardV1Page.php rename to src/V1/Product/Fr/IdCard/IdCardV1Page.php index 4239fca1..05c7cdd0 100644 --- a/src/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -1,9 +1,9 @@ documentSide "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV2.php b/src/V1/Product/Fr/IdCard/IdCardV2.php similarity index 84% rename from src/Product/Fr/IdCard/IdCardV2.php rename to src/V1/Product/Fr/IdCard/IdCardV2.php index a4455598..cc2397a0 100644 --- a/src/Product/Fr/IdCard/IdCardV2.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2.php @@ -2,11 +2,11 @@ /** Carte Nationale d'Identité V2. */ -namespace Mindee\Product\Fr\IdCard; +namespace Mindee\V1\Product\Fr\IdCard; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Carte Nationale d'Identité API version 2 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(IdCardV2Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/IdCard/IdCardV2Document.php b/src/V1/Product/Fr/IdCard/IdCardV2Document.php similarity index 96% rename from src/Product/Fr/IdCard/IdCardV2Document.php rename to src/V1/Product/Fr/IdCard/IdCardV2Document.php index 45b38d16..b85660cd 100644 --- a/src/Product/Fr/IdCard/IdCardV2Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Document.php @@ -1,12 +1,12 @@ issueDate :Issuing Authority: $this->authority "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/IdCard/IdCardV2Page.php b/src/V1/Product/Fr/IdCard/IdCardV2Page.php similarity index 86% rename from src/Product/Fr/IdCard/IdCardV2Page.php rename to src/V1/Product/Fr/IdCard/IdCardV2Page.php index e96774bf..d8bcea68 100644 --- a/src/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -1,9 +1,9 @@ documentSide "; $outStr .= parent::__toString(); - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Fr/Payslip/PayslipV3.php b/src/V1/Product/Fr/Payslip/PayslipV3.php similarity index 84% rename from src/Product/Fr/Payslip/PayslipV3.php rename to src/V1/Product/Fr/Payslip/PayslipV3.php index b58461ea..c132823a 100644 --- a/src/Product/Fr/Payslip/PayslipV3.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3.php @@ -2,11 +2,11 @@ /** Payslip V3. */ -namespace Mindee\Product\Fr\Payslip; +namespace Mindee\V1\Product\Fr\Payslip; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Payslip API version 3 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(PayslipV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php similarity index 72% rename from src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php rename to src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php index 7cdbb5a6..35e9af02 100644 --- a/src/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php @@ -1,10 +1,10 @@ bankName); - $outArr["iban"] = SummaryHelper::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelper::formatForDisplay($this->swift); + $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); + $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); + $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); return $outArr; } @@ -62,9 +62,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["bankName"] = SummaryHelper::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelper::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelper::formatForDisplay($this->swift); + $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); + $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); + $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); return $outArr; } /** @@ -87,6 +87,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3Document.php b/src/V1/Product/Fr/Payslip/PayslipV3Document.php similarity index 96% rename from src/Product/Fr/Payslip/PayslipV3Document.php rename to src/V1/Product/Fr/Payslip/PayslipV3Document.php index 012dcc82..9bbd4a31 100644 --- a/src/Product/Fr/Payslip/PayslipV3Document.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Document.php @@ -1,10 +1,10 @@ address); - $outArr["dateOfBirth"] = SummaryHelper::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelper::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelper::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelper::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelper::formatForDisplay($this->socialSecurityNumber); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); + $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); + $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); + $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); return $outArr; } @@ -86,13 +86,13 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelper::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelper::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelper::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelper::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelper::formatForDisplay($this->socialSecurityNumber); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); + $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); + $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); + $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); return $outArr; } /** @@ -119,6 +119,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php similarity index 67% rename from src/Product/Fr/Payslip/PayslipV3Employer.php rename to src/V1/Product/Fr/Payslip/PayslipV3Employer.php index a46a7689..dffb89d2 100644 --- a/src/Product/Fr/Payslip/PayslipV3Employer.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php @@ -1,10 +1,10 @@ address); - $outArr["companyId"] = SummaryHelper::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelper::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelper::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelper::formatForDisplay($this->urssafNumber); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); + $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); + $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); return $outArr; } @@ -86,13 +86,13 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["address"] = SummaryHelper::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelper::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelper::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelper::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelper::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelper::formatForDisplay($this->urssafNumber); + $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); + $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); + $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); + $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); + $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); return $outArr; } /** @@ -119,6 +119,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php similarity index 66% rename from src/Product/Fr/Payslip/PayslipV3Employment.php rename to src/V1/Product/Fr/Payslip/PayslipV3Employment.php index 2ab159f3..a8511fc2 100644 --- a/src/Product/Fr/Payslip/PayslipV3Employment.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php @@ -1,10 +1,10 @@ category); - $outArr["coefficient"] = SummaryHelper::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelper::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelper::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelper::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelper::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); + $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); + $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); + $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); + $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); + $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); + $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); return $outArr; } @@ -86,13 +86,13 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["category"] = SummaryHelper::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelper::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelper::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelper::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelper::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelper::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); + $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); + $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); + $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); + $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); + $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); + $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); return $outArr; } /** @@ -119,6 +119,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php similarity index 61% rename from src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php rename to src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php index 25a7fe9c..94782c43 100644 --- a/src/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php @@ -1,10 +1,10 @@ accrued); - $outArr["period"] = SummaryHelper::formatForDisplay($this->period, 6); - $outArr["ptoType"] = SummaryHelper::formatForDisplay($this->ptoType, 11); - $outArr["remaining"] = SummaryHelper::formatFloat($this->remaining); - $outArr["used"] = SummaryHelper::formatFloat($this->used); + $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); + $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period, 6); + $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType, 11); + $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); + $outArr["used"] = SummaryHelperV1::formatFloat($this->used); return $outArr; } @@ -77,11 +77,11 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["accrued"] = SummaryHelper::formatFloat($this->accrued); - $outArr["period"] = SummaryHelper::formatForDisplay($this->period); - $outArr["ptoType"] = SummaryHelper::formatForDisplay($this->ptoType); - $outArr["remaining"] = SummaryHelper::formatFloat($this->remaining); - $outArr["used"] = SummaryHelper::formatFloat($this->used); + $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); + $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period); + $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType); + $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); + $outArr["used"] = SummaryHelperV1::formatFloat($this->used); return $outArr; } /** @@ -93,12 +93,12 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["accrued"], 9); - $outStr .= SummaryHelper::padString($printable["period"], 6); - $outStr .= SummaryHelper::padString($printable["ptoType"], 11); - $outStr .= SummaryHelper::padString($printable["remaining"], 9); - $outStr .= SummaryHelper::padString($printable["used"], 9); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["accrued"], 9); + $outStr .= SummaryHelperV1::padString($printable["period"], 6); + $outStr .= SummaryHelperV1::padString($printable["ptoType"], 11); + $outStr .= SummaryHelperV1::padString($printable["remaining"], 9); + $outStr .= SummaryHelperV1::padString($printable["used"], 9); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -106,6 +106,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php similarity index 97% rename from src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php rename to src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index 464ca86d..49c44c9e 100644 --- a/src/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php @@ -1,6 +1,6 @@ grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelper::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelper::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelper::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelper::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelper::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelper::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelper::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelper::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelper::formatFloat($this->totalTaxesAndDeductions); + $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); + $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); + $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); + $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); + $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); + $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); + $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); + $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); + $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); + $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); return $outArr; } @@ -114,16 +114,16 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["grossSalary"] = SummaryHelper::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelper::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelper::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelper::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelper::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelper::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelper::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelper::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelper::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelper::formatFloat($this->totalTaxesAndDeductions); + $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); + $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); + $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); + $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); + $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); + $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); + $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); + $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); + $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); + $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); return $outArr; } /** @@ -153,6 +153,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php similarity index 69% rename from src/Product/Fr/Payslip/PayslipV3PayPeriod.php rename to src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index 19e9742d..6a2999cb 100644 --- a/src/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -1,10 +1,10 @@ endDate); - $outArr["month"] = SummaryHelper::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelper::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); + $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } @@ -74,11 +74,11 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["endDate"] = SummaryHelper::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelper::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelper::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelper::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); + $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); + $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); + $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); + $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } /** @@ -103,6 +103,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php similarity index 61% rename from src/Product/Fr/Payslip/PayslipV3SalaryDetail.php rename to src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php index 75c93f68..0995d0c3 100644 --- a/src/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php @@ -1,10 +1,10 @@ amount); - $outArr["base"] = SummaryHelper::formatFloat($this->base); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["number"] = SummaryHelper::formatFloat($this->number); - $outArr["rate"] = SummaryHelper::formatFloat($this->rate); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["base"] = SummaryHelperV1::formatFloat($this->base); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["number"] = SummaryHelperV1::formatFloat($this->number); + $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); return $outArr; } @@ -78,11 +78,11 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["base"] = SummaryHelper::formatFloat($this->base); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["number"] = SummaryHelper::formatFloat($this->number); - $outArr["rate"] = SummaryHelper::formatFloat($this->rate); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["base"] = SummaryHelperV1::formatFloat($this->base); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["number"] = SummaryHelperV1::formatFloat($this->number); + $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); return $outArr; } /** @@ -94,12 +94,12 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["amount"], 12); - $outStr .= SummaryHelper::padString($printable["base"], 9); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["number"], 6); - $outStr .= SummaryHelper::padString($printable["rate"], 9); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["amount"], 12); + $outStr .= SummaryHelperV1::padString($printable["base"], 9); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["number"], 6); + $outStr .= SummaryHelperV1::padString($printable["rate"], 9); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -107,6 +107,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php similarity index 97% rename from src/Product/Fr/Payslip/PayslipV3SalaryDetails.php rename to src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index 2a8dd8da..074332b3 100644 --- a/src/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php @@ -1,6 +1,6 @@ pages[] = new Page(IndianPassportV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php similarity index 96% rename from src/Product/Ind/IndianPassport/IndianPassportV1Document.php rename to src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php index 0de52578..fab217ec 100644 --- a/src/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php @@ -1,13 +1,13 @@ address3 :File Number: $this->fileNumber "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/InternationalId/InternationalIdV2.php b/src/V1/Product/InternationalId/InternationalIdV2.php similarity index 84% rename from src/Product/InternationalId/InternationalIdV2.php rename to src/V1/Product/InternationalId/InternationalIdV2.php index 361ee315..71628ffc 100644 --- a/src/Product/InternationalId/InternationalIdV2.php +++ b/src/V1/Product/InternationalId/InternationalIdV2.php @@ -2,11 +2,11 @@ /** International ID V2. */ -namespace Mindee\Product\InternationalId; +namespace Mindee\V1\Product\InternationalId; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * International ID API version 2 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(InternationalIdV2Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/InternationalId/InternationalIdV2Document.php b/src/V1/Product/InternationalId/InternationalIdV2Document.php similarity index 95% rename from src/Product/InternationalId/InternationalIdV2Document.php rename to src/V1/Product/InternationalId/InternationalIdV2Document.php index 238f52df..da89c7b3 100644 --- a/src/Product/InternationalId/InternationalIdV2Document.php +++ b/src/V1/Product/InternationalId/InternationalIdV2Document.php @@ -1,13 +1,13 @@ mrzLine2 :MRZ Line 3: $this->mrzLine3 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Invoice/InvoiceV4.php b/src/V1/Product/Invoice/InvoiceV4.php similarity index 84% rename from src/Product/Invoice/InvoiceV4.php rename to src/V1/Product/Invoice/InvoiceV4.php index dcdb975d..6a71817d 100644 --- a/src/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -2,11 +2,11 @@ /** Invoice V4. */ -namespace Mindee\Product\Invoice; +namespace Mindee\V1\Product\Invoice; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Invoice API version 4 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(InvoiceV4Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Invoice/InvoiceV4Document.php b/src/V1/Product/Invoice/InvoiceV4Document.php similarity index 95% rename from src/Product/Invoice/InvoiceV4Document.php rename to src/V1/Product/Invoice/InvoiceV4Document.php index c485aa61..624d26fb 100644 --- a/src/Product/Invoice/InvoiceV4Document.php +++ b/src/V1/Product/Invoice/InvoiceV4Document.php @@ -1,19 +1,19 @@ category :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php similarity index 55% rename from src/Product/Invoice/InvoiceV4LineItem.php rename to src/V1/Product/Invoice/InvoiceV4LineItem.php index 461fe49e..1fc175e9 100644 --- a/src/Product/Invoice/InvoiceV4LineItem.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -1,10 +1,10 @@ description, 36); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -97,14 +97,14 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelper::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelper::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelper::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelper::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); + $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -116,15 +116,15 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["productCode"], 12); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["taxAmount"], 10); - $outStr .= SummaryHelper::padString($printable["taxRate"], 12); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitMeasure"], 15); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["productCode"], 12); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["taxAmount"], 10); + $outStr .= SummaryHelperV1::padString($printable["taxRate"], 12); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitMeasure"], 15); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -132,6 +132,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php similarity index 98% rename from src/Product/Invoice/InvoiceV4LineItems.php rename to src/V1/Product/Invoice/InvoiceV4LineItems.php index e3e399bc..fe934b74 100644 --- a/src/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -1,6 +1,6 @@ pages[] = new Page(InvoiceSplitterV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php similarity index 87% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php index dccce3ad..99d65d33 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1Document.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php @@ -1,10 +1,10 @@ tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["pageIndexes"], 72); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["pageIndexes"], 72); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -71,6 +71,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php similarity index 97% rename from src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php rename to src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index ea90083b..98c19a51 100644 --- a/src/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -1,6 +1,6 @@ pages[] = new Page(MultiReceiptsDetectorV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php similarity index 83% rename from src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php rename to src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php index 9df25cd1..1ed17ed3 100644 --- a/src/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php @@ -1,11 +1,11 @@ pages[] = new Page(NutritionFactsLabelV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php index d8b0a3d2..b10b434c 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index 48dc38b3..ae7801a1 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 593ef85f..1666d7d4 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index bcba21c4..1bc987f2 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php similarity index 97% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php index 4059714e..ae63f951 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php @@ -1,11 +1,11 @@ dailyValue); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 20); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } @@ -77,11 +77,11 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** @@ -93,12 +93,12 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["dailyValue"], 11); - $outStr .= SummaryHelper::padString($printable["name"], 20); - $outStr .= SummaryHelper::padString($printable["per100G"], 8); - $outStr .= SummaryHelper::padString($printable["perServing"], 11); - $outStr .= SummaryHelper::padString($printable["unit"], 4); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["dailyValue"], 11); + $outStr .= SummaryHelperV1::padString($printable["name"], 20); + $outStr .= SummaryHelperV1::padString($printable["per100G"], 8); + $outStr .= SummaryHelperV1::padString($printable["perServing"], 11); + $outStr .= SummaryHelperV1::padString($printable["unit"], 4); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -106,6 +106,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php similarity index 97% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 17ae8072..657adba0 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php @@ -1,6 +1,6 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index 25517a74..21512f28 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php similarity index 76% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index 901d9fe5..7513fb0d 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -1,10 +1,10 @@ amount); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } @@ -57,8 +57,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["amount"] = SummaryHelper::formatFloat($this->amount); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** @@ -80,6 +80,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php similarity index 73% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index f7d897d2..4c8a4064 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } @@ -71,10 +71,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** @@ -98,6 +98,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index 51de30f7..f5c3f2db 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index af421e6c..7915d6c1 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index cd122c34..c2ee82ac 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php similarity index 75% rename from src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php rename to src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index e3aded8f..a5c973f8 100644 --- a/src/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -1,10 +1,10 @@ dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } @@ -65,9 +65,9 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["dailyValue"] = SummaryHelper::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelper::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelper::formatFloat($this->perServing); + $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); + $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); + $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } /** @@ -90,6 +90,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php similarity index 84% rename from src/Product/Passport/PassportV1.php rename to src/V1/Product/Passport/PassportV1.php index 1a45b867..ef460a7b 100644 --- a/src/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -2,11 +2,11 @@ /** Passport V1. */ -namespace Mindee\Product\Passport; +namespace Mindee\V1\Product\Passport; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Passport API version 1 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(PassportV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Passport/PassportV1Document.php b/src/V1/Product/Passport/PassportV1Document.php similarity index 94% rename from src/Product/Passport/PassportV1Document.php rename to src/V1/Product/Passport/PassportV1Document.php index ed39a67e..c1885c09 100644 --- a/src/Product/Passport/PassportV1Document.php +++ b/src/V1/Product/Passport/PassportV1Document.php @@ -1,12 +1,12 @@ mrz1 :MRZ Line 2: $this->mrz2 "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Receipt/ReceiptV5.php b/src/V1/Product/Receipt/ReceiptV5.php similarity index 84% rename from src/Product/Receipt/ReceiptV5.php rename to src/V1/Product/Receipt/ReceiptV5.php index 681a87f4..d6e29029 100644 --- a/src/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -2,11 +2,11 @@ /** Receipt V5. */ -namespace Mindee\Product\Receipt; +namespace Mindee\V1\Product\Receipt; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * Receipt API version 5 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(ReceiptV5Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Receipt/ReceiptV5Document.php b/src/V1/Product/Receipt/ReceiptV5Document.php similarity index 93% rename from src/Product/Receipt/ReceiptV5Document.php rename to src/V1/Product/Receipt/ReceiptV5Document.php index fca27398..23cf840c 100644 --- a/src/Product/Receipt/ReceiptV5Document.php +++ b/src/V1/Product/Receipt/ReceiptV5Document.php @@ -1,17 +1,17 @@ receiptNumber :Line Items: $lineItemsSummary "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php similarity index 61% rename from src/Product/Receipt/ReceiptV5LineItem.php rename to src/V1/Product/Receipt/ReceiptV5LineItem.php index 4d184697..01d62900 100644 --- a/src/Product/Receipt/ReceiptV5LineItem.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -1,10 +1,10 @@ description, 36); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } @@ -71,10 +71,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["quantity"] = SummaryHelper::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelper::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelper::formatFloat($this->unitPrice); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); + $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); + $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); return $outArr; } /** @@ -86,11 +86,11 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["quantity"], 8); - $outStr .= SummaryHelper::padString($printable["totalAmount"], 12); - $outStr .= SummaryHelper::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); + $outStr .= SummaryHelperV1::padString($printable["totalAmount"], 12); + $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -98,6 +98,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php similarity index 98% rename from src/Product/Receipt/ReceiptV5LineItems.php rename to src/V1/Product/Receipt/ReceiptV5LineItems.php index f684ff43..a6ac2077 100644 --- a/src/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -1,6 +1,6 @@ pages[] = new Page(ResumeV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php similarity index 61% rename from src/Product/Resume/ResumeV1Certificate.php rename to src/V1/Product/Resume/ResumeV1Certificate.php index 48e12144..419ab7a3 100644 --- a/src/Product/Resume/ResumeV1Certificate.php +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -1,10 +1,10 @@ grade, 10); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name, 30); - $outArr["provider"] = SummaryHelper::formatForDisplay($this->provider, 25); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); + $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade, 10); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 30); + $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider, 25); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } @@ -68,10 +68,10 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["grade"] = SummaryHelper::formatForDisplay($this->grade); - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["provider"] = SummaryHelper::formatForDisplay($this->provider); - $outArr["year"] = SummaryHelper::formatForDisplay($this->year); + $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider); + $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); return $outArr; } /** @@ -83,11 +83,11 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["grade"], 10); - $outStr .= SummaryHelper::padString($printable["name"], 30); - $outStr .= SummaryHelper::padString($printable["provider"], 25); - $outStr .= SummaryHelper::padString($printable["year"], 4); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["grade"], 10); + $outStr .= SummaryHelperV1::padString($printable["name"], 30); + $outStr .= SummaryHelperV1::padString($printable["provider"], 25); + $outStr .= SummaryHelperV1::padString($printable["year"], 4); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -95,6 +95,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php similarity index 98% rename from src/Product/Resume/ResumeV1Certificates.php rename to src/V1/Product/Resume/ResumeV1Certificates.php index c13366f1..1313135d 100644 --- a/src/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -1,6 +1,6 @@ degreeDomain, 15); - $outArr["degreeType"] = SummaryHelper::formatForDisplay($this->degreeType, 25); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelper::formatForDisplay($this->school, 25); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); + $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain, 15); + $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType, 25); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school, 25); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } @@ -86,13 +86,13 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["degreeDomain"] = SummaryHelper::formatForDisplay($this->degreeDomain); - $outArr["degreeType"] = SummaryHelper::formatForDisplay($this->degreeType); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelper::formatForDisplay($this->school); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); + $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain); + $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } /** @@ -104,14 +104,14 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["degreeDomain"], 15); - $outStr .= SummaryHelper::padString($printable["degreeType"], 25); - $outStr .= SummaryHelper::padString($printable["endMonth"], 9); - $outStr .= SummaryHelper::padString($printable["endYear"], 8); - $outStr .= SummaryHelper::padString($printable["school"], 25); - $outStr .= SummaryHelper::padString($printable["startMonth"], 11); - $outStr .= SummaryHelper::padString($printable["startYear"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["degreeDomain"], 15); + $outStr .= SummaryHelperV1::padString($printable["degreeType"], 25); + $outStr .= SummaryHelperV1::padString($printable["endMonth"], 9); + $outStr .= SummaryHelperV1::padString($printable["endYear"], 8); + $outStr .= SummaryHelperV1::padString($printable["school"], 25); + $outStr .= SummaryHelperV1::padString($printable["startMonth"], 11); + $outStr .= SummaryHelperV1::padString($printable["startYear"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -119,6 +119,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php similarity index 98% rename from src/Product/Resume/ResumeV1Educations.php rename to src/V1/Product/Resume/ResumeV1Educations.php index 6549826c..22517e93 100644 --- a/src/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -1,6 +1,6 @@ language); - $outArr["level"] = SummaryHelper::formatForDisplay($this->level, 20); + $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); + $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level, 20); return $outArr; } @@ -56,8 +56,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["language"] = SummaryHelper::formatForDisplay($this->language); - $outArr["level"] = SummaryHelper::formatForDisplay($this->level); + $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); + $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level); return $outArr; } /** @@ -69,9 +69,9 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["language"], 8); - $outStr .= SummaryHelper::padString($printable["level"], 20); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["language"], 8); + $outStr .= SummaryHelperV1::padString($printable["level"], 20); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -79,6 +79,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php similarity index 97% rename from src/Product/Resume/ResumeV1Languages.php rename to src/V1/Product/Resume/ResumeV1Languages.php index 612a5ad7..dcdfba37 100644 --- a/src/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -1,6 +1,6 @@ contractType, 15); - $outArr["department"] = SummaryHelper::formatForDisplay($this->department, 10); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description, 36); - $outArr["employer"] = SummaryHelper::formatForDisplay($this->employer, 25); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelper::formatForDisplay($this->role, 20); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); + $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType, 15); + $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department, 10); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); + $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer, 25); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role, 20); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } @@ -98,15 +98,15 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["contractType"] = SummaryHelper::formatForDisplay($this->contractType); - $outArr["department"] = SummaryHelper::formatForDisplay($this->department); - $outArr["description"] = SummaryHelper::formatForDisplay($this->description); - $outArr["employer"] = SummaryHelper::formatForDisplay($this->employer); - $outArr["endMonth"] = SummaryHelper::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelper::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelper::formatForDisplay($this->role); - $outArr["startMonth"] = SummaryHelper::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelper::formatForDisplay($this->startYear); + $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType); + $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department); + $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); + $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer); + $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); + $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); + $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role); + $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); + $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); return $outArr; } /** @@ -118,16 +118,16 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["contractType"], 15); - $outStr .= SummaryHelper::padString($printable["department"], 10); - $outStr .= SummaryHelper::padString($printable["description"], 36); - $outStr .= SummaryHelper::padString($printable["employer"], 25); - $outStr .= SummaryHelper::padString($printable["endMonth"], 9); - $outStr .= SummaryHelper::padString($printable["endYear"], 8); - $outStr .= SummaryHelper::padString($printable["role"], 20); - $outStr .= SummaryHelper::padString($printable["startMonth"], 11); - $outStr .= SummaryHelper::padString($printable["startYear"], 10); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["contractType"], 15); + $outStr .= SummaryHelperV1::padString($printable["department"], 10); + $outStr .= SummaryHelperV1::padString($printable["description"], 36); + $outStr .= SummaryHelperV1::padString($printable["employer"], 25); + $outStr .= SummaryHelperV1::padString($printable["endMonth"], 9); + $outStr .= SummaryHelperV1::padString($printable["endYear"], 8); + $outStr .= SummaryHelperV1::padString($printable["role"], 20); + $outStr .= SummaryHelperV1::padString($printable["startMonth"], 11); + $outStr .= SummaryHelperV1::padString($printable["startYear"], 10); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -135,6 +135,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php similarity index 98% rename from src/Product/Resume/ResumeV1ProfessionalExperiences.php rename to src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index 84cfecca..31ff483b 100644 --- a/src/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -1,6 +1,6 @@ name, 20); - $outArr["url"] = SummaryHelper::formatForDisplay($this->url, 50); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); + $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url, 50); return $outArr; } @@ -56,8 +56,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["name"] = SummaryHelper::formatForDisplay($this->name); - $outArr["url"] = SummaryHelper::formatForDisplay($this->url); + $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); + $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url); return $outArr; } /** @@ -69,9 +69,9 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["name"], 20); - $outStr .= SummaryHelper::padString($printable["url"], 50); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["name"], 20); + $outStr .= SummaryHelperV1::padString($printable["url"], 50); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -79,6 +79,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php similarity index 98% rename from src/Product/Resume/ResumeV1SocialNetworksUrls.php rename to src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index 9b9b0a13..29f484c9 100644 --- a/src/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -1,6 +1,6 @@ pages[] = new Page(BankCheckV1Page::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/BankCheck/BankCheckV1Document.php b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php similarity index 90% rename from src/Product/Us/BankCheck/BankCheckV1Document.php rename to src/V1/Product/Us/BankCheck/BankCheckV1Document.php index 9bfe9113..3791e3dd 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Document.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php @@ -1,13 +1,13 @@ accountNumber :Check Number: $this->checkNumber "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/BankCheck/BankCheckV1Page.php b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php similarity index 88% rename from src/Product/Us/BankCheck/BankCheckV1Page.php rename to src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 8642f35c..9b204900 100644 --- a/src/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -1,9 +1,9 @@ pages[] = new Page(HealthcareCardV1Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php similarity index 66% rename from src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php rename to src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php index 8fc4287a..cdbfccdd 100644 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php @@ -1,10 +1,10 @@ serviceFees); - $outArr["serviceName"] = SummaryHelper::formatForDisplay($this->serviceName, 20); + $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); + $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName, 20); return $outArr; } @@ -57,8 +57,8 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["serviceFees"] = SummaryHelper::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelper::formatForDisplay($this->serviceName); + $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); + $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName); return $outArr; } /** @@ -70,9 +70,9 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["serviceFees"], 12); - $outStr .= SummaryHelper::padString($printable["serviceName"], 20); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["serviceFees"], 12); + $outStr .= SummaryHelperV1::padString($printable["serviceName"], 20); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -80,6 +80,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php similarity index 97% rename from src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php rename to src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index 0722d305..29bfbe0c 100644 --- a/src/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php @@ -1,6 +1,6 @@ enrollmentDate "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php similarity index 84% rename from src/Product/Us/UsMail/UsMailV3.php rename to src/V1/Product/Us/UsMail/UsMailV3.php index eee81dd3..0dd5ed7b 100644 --- a/src/Product/Us/UsMail/UsMailV3.php +++ b/src/V1/Product/Us/UsMail/UsMailV3.php @@ -2,11 +2,11 @@ /** US Mail V3. */ -namespace Mindee\Product\Us\UsMail; +namespace Mindee\V1\Product\Us\UsMail; -use Mindee\Parsing\Common\Inference; -use Mindee\Parsing\Common\Page; use Mindee\Error\MindeeUnsetException; +use Mindee\V1\Parsing\Common\Inference; +use Mindee\V1\Parsing\Common\Page; /** * US Mail API version 3 inference prediction. @@ -33,7 +33,7 @@ public function __construct(array $rawPrediction) foreach ($rawPrediction['pages'] as $page) { try { $this->pages[] = new Page(UsMailV3Document::class, $page); - } catch (MindeeUnsetException $ignored) { + } catch (MindeeUnsetException) { } } } diff --git a/src/Product/Us/UsMail/UsMailV3Document.php b/src/V1/Product/Us/UsMail/UsMailV3Document.php similarity index 92% rename from src/Product/Us/UsMail/UsMailV3Document.php rename to src/V1/Product/Us/UsMail/UsMailV3Document.php index c83f9bcb..53473639 100644 --- a/src/Product/Us/UsMail/UsMailV3Document.php +++ b/src/V1/Product/Us/UsMail/UsMailV3Document.php @@ -1,12 +1,12 @@ isReturnToSender "; - return SummaryHelper::cleanOutString($outStr); + return SummaryHelperV1::cleanOutString($outStr); } } diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php similarity index 54% rename from src/Product/Us/UsMail/UsMailV3RecipientAddress.php rename to src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index 472de2ef..ebcdd5df 100644 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -1,10 +1,10 @@ city, 15); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete, 35); - $outArr["isAddressChange"] = SummaryHelper::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelper::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street, 25); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit, 15); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); + $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit, 15); return $outArr; } @@ -92,14 +92,14 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete); - $outArr["isAddressChange"] = SummaryHelper::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelper::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street); - $outArr["unit"] = SummaryHelper::formatForDisplay($this->unit); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); + $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); + $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); return $outArr; } /** @@ -111,15 +111,15 @@ public function toTableLine(): string { $printable = $this->tablePrintableValues(); $outStr = "| "; - $outStr .= SummaryHelper::padString($printable["city"], 15); - $outStr .= SummaryHelper::padString($printable["complete"], 35); - $outStr .= SummaryHelper::padString($printable["isAddressChange"], 17); - $outStr .= SummaryHelper::padString($printable["postalCode"], 11); - $outStr .= SummaryHelper::padString($printable["privateMailboxNumber"], 22); - $outStr .= SummaryHelper::padString($printable["state"], 5); - $outStr .= SummaryHelper::padString($printable["street"], 25); - $outStr .= SummaryHelper::padString($printable["unit"], 15); - return rtrim(SummaryHelper::cleanOutString($outStr)); + $outStr .= SummaryHelperV1::padString($printable["city"], 15); + $outStr .= SummaryHelperV1::padString($printable["complete"], 35); + $outStr .= SummaryHelperV1::padString($printable["isAddressChange"], 17); + $outStr .= SummaryHelperV1::padString($printable["postalCode"], 11); + $outStr .= SummaryHelperV1::padString($printable["privateMailboxNumber"], 22); + $outStr .= SummaryHelperV1::padString($printable["state"], 5); + $outStr .= SummaryHelperV1::padString($printable["street"], 25); + $outStr .= SummaryHelperV1::padString($printable["unit"], 15); + return rtrim(SummaryHelperV1::cleanOutString($outStr)); } /** @@ -127,6 +127,6 @@ public function toTableLine(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toTableLine()); + return SummaryHelperV1::cleanOutString($this->toTableLine()); } } diff --git a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php similarity index 98% rename from src/Product/Us/UsMail/UsMailV3RecipientAddresses.php rename to src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php index 42e4c573..378a30ce 100644 --- a/src/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php @@ -1,6 +1,6 @@ city, 15); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete, 35); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street, 25); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); return $outArr; } @@ -74,11 +74,11 @@ private function tablePrintableValues(): array private function printableValues(): array { $outArr = []; - $outArr["city"] = SummaryHelper::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelper::formatForDisplay($this->complete); - $outArr["postalCode"] = SummaryHelper::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelper::formatForDisplay($this->state); - $outArr["street"] = SummaryHelper::formatForDisplay($this->street); + $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); + $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); + $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); + $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); + $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); return $outArr; } /** @@ -103,6 +103,6 @@ public function toFieldList(): string */ public function __toString(): string { - return SummaryHelper::cleanOutString($this->toFieldList()); + return SummaryHelperV1::cleanOutString($this->toFieldList()); } } diff --git a/src/ClientV2.php b/src/V2/Client.php similarity index 91% rename from src/ClientV2.php rename to src/V2/Client.php index fc0ab147..857e3470 100644 --- a/src/ClientV2.php +++ b/src/V2/Client.php @@ -1,27 +1,28 @@ mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); + $this->mindeeApi = new MindeeAPIV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); } /** @@ -81,7 +82,7 @@ public function getInference(string $inferenceId): InferenceResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass * @param string $resultUrl URL of the result. - * @return T A response containing parsing results. + * @return BaseResponse A response containing parsing results. */ public function getResultFromUrl( string $responseClass, @@ -95,7 +96,7 @@ public function getResultFromUrl( * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass * @param string $resultId ID of the result. - * @return T A response containing parsing results. + * @return BaseResponse A response containing parsing results. */ public function getResult( string $responseClass, @@ -142,7 +143,7 @@ public function enqueueAndGetInference( * @phpstan-param class-string $responseClass * @param InputSource $inputDoc Input document to parse. * @param BaseParameters $params Parameters relating to prediction options. - * @return T A response containing parsing results. + * @return BaseResponse A response containing parsing results. * @throws MindeeException Throws if enqueueing fails, job fails, or times out. */ public function enqueueAndGetResult( diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index a156fb3e..03cbd36b 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -2,7 +2,7 @@ namespace Mindee\V2\ClientOptions; -use Mindee\Input\PollingOptions; +use Mindee\ClientOptions\PollingOptions; /** * Base parameters for running an inference. diff --git a/src/V2/FileOperations/Split.php b/src/V2/FileOperations/Split.php index 43a076e2..2d0371c1 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -3,8 +3,8 @@ namespace Mindee\V2\FileOperations; use Mindee\Error\MindeeInputException; -use Mindee\Extraction\ExtractedPdf; -use Mindee\Extraction\PdfExtractor; +use Mindee\Extraction\ExtractedPDF; +use Mindee\Extraction\PDFExtractor; use Mindee\Input\LocalInputSource; /** @@ -49,9 +49,9 @@ public static function expandRange(int $start, int $end): array * * @param int[] $split Split range to extract. * - * @return ExtractedPdf 2D array of extracted pages + * @return ExtractedPDF 2D array of extracted pages */ - public function extractSingleSplit(array $split): ExtractedPdf + public function extractSingleSplit(array $split): ExtractedPDF { return $this->extractSplits([$split])[0]; } @@ -65,7 +65,7 @@ public function extractSingleSplit(array $split): ExtractedPdf */ public function extractSplits(array $splits): SplitFiles { - $pdfExtractor = new PdfExtractor($this->localInput); + $pdfExtractor = new PDFExtractor($this->localInput); $expandedPageIndexes = array_map(fn (array $split) => self::expandRange($split[0], $split[1]), $splits); return new SplitFiles(...$pdfExtractor->extractSubDocuments($expandedPageIndexes)); diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index b9fefd66..fe2935ce 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -3,21 +3,21 @@ namespace Mindee\V2\FileOperations; use Mindee\Error\MindeeException; -use Mindee\Extraction\ExtractedPdf; +use Mindee\Extraction\ExtractedPDF; /** * Split files collection wrapper. * - * * @extends \ArrayObject + * * @extends \ArrayObject */ class SplitFiles extends \ArrayObject { /** * Builds a new SplitFiles collection. * - * @param ExtractedPdf ...$items Items. + * @param ExtractedPDF ...$items Items. */ - public function __construct(ExtractedPdf ...$items) + public function __construct(ExtractedPDF ...$items) { parent::__construct($items); } diff --git a/src/Http/MindeeApiV2.php b/src/V2/HTTP/MindeeAPIV2.php similarity index 98% rename from src/Http/MindeeApiV2.php rename to src/V2/HTTP/MindeeAPIV2.php index 38c9957f..90aa7cd5 100644 --- a/src/Http/MindeeApiV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -4,36 +4,34 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\Http; +namespace Mindee\V2\HTTP; use CurlHandle; use Exception; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeException; - -// phpcs:disable -include_once(dirname(__DIR__) . '/version.php'); - -// phpcs:enable - use Mindee\Error\MindeeV2HttpException; use Mindee\Error\MindeeV2HttpUnknownException; -use Mindee\Input\InferenceParameters; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\URLInputSource; -use Mindee\Parsing\V2\BaseResponse; -use Mindee\Parsing\V2\ErrorResponse; -use Mindee\Parsing\V2\InferenceResponse; -use Mindee\Parsing\V2\JobResponse; use Mindee\V2\ClientOptions\BaseParameters; +use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\Inference\BaseResponse; +use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Parsing\JobResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; use const Mindee\VERSION; +// phpcs:disable +include_once(dirname(__DIR__, 2) . '/version.php'); + +// phpcs:enable + /** * Default key name for the API key entry in environment variables. */ @@ -61,7 +59,7 @@ /** * Data class containing settings for endpoints. */ -class MindeeApiV2 +class MindeeAPIV2 { /** * Get the User Agent to send for API calls. diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/BaseInference.php index 27dcb0f9..3195b931 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -2,10 +2,10 @@ namespace Mindee\V2\Parsing; -use Mindee\Parsing\Common\SummaryHelper; -use Mindee\Parsing\V2\InferenceFile; -use Mindee\Parsing\V2\InferenceJob; -use Mindee\Parsing\V2\InferenceModel; +use Mindee\Parsing\SummaryHelper; +use Mindee\V2\Parsing\Inference\InferenceFile; +use Mindee\V2\Parsing\Inference\InferenceJob; +use Mindee\V2\Parsing\Inference\InferenceModel; /** * Base for all inference-based V2 products. diff --git a/src/Error/ErrorItem.php b/src/V2/Parsing/ErrorItem.php similarity index 94% rename from src/Error/ErrorItem.php rename to src/V2/Parsing/ErrorItem.php index fc2e96d8..1d5304b3 100644 --- a/src/Error/ErrorItem.php +++ b/src/V2/Parsing/ErrorItem.php @@ -1,6 +1,6 @@ + * @var ObjectField */ public array $items; diff --git a/src/Parsing/V2/Field/ObjectField.php b/src/V2/Parsing/Inference/Field/ObjectField.php similarity index 98% rename from src/Parsing/V2/Field/ObjectField.php rename to src/V2/Parsing/Inference/Field/ObjectField.php index cfd440d0..0a3227ec 100644 --- a/src/Parsing/V2/Field/ObjectField.php +++ b/src/V2/Parsing/Inference/Field/ObjectField.php @@ -1,6 +1,6 @@ rag = isset( $serverResponse['rag'] - ) ? new RagMetadata($serverResponse['rag']) : null; + ) ? new RAGMetadata($serverResponse['rag']) : null; } /** diff --git a/src/Parsing/V2/RagMetadata.php b/src/V2/Parsing/Inference/RAGMetadata.php similarity index 87% rename from src/Parsing/V2/RagMetadata.php rename to src/V2/Parsing/Inference/RAGMetadata.php index a2dec186..56b56a13 100644 --- a/src/Parsing/V2/RagMetadata.php +++ b/src/V2/Parsing/Inference/RAGMetadata.php @@ -1,11 +1,11 @@ expectException(MindeeUnhandledException::class); $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); - new PdfExtractor($inputObj); + new PDFExtractor($inputObj); } public function testNoExtractedImage() { @@ -34,11 +34,11 @@ public function testNoExtractedImage() $saveFormat = "pdf"; new ExtractedImage($inputImage, $filename, $saveFormat, 0, 0); } - public function testNoExtractedPdf() + public function testNoExtractedPDF() { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; $filename = "dummy"; - new ExtractedPdf($inputImage, $filename); + new ExtractedPDF($inputImage, $filename); } } diff --git a/tests/Dependencies/DependencyCheckerPdfTest.php b/tests/Dependencies/DependencyCheckerPDFTest.php similarity index 85% rename from tests/Dependencies/DependencyCheckerPdfTest.php rename to tests/Dependencies/DependencyCheckerPDFTest.php index ff3f59b3..4fa6b1d0 100644 --- a/tests/Dependencies/DependencyCheckerPdfTest.php +++ b/tests/Dependencies/DependencyCheckerPDFTest.php @@ -2,10 +2,10 @@ namespace Dependencies; -use Mindee\Parsing\DependencyChecker; +use Mindee\Dependency\DependencyChecker; use PHPUnit\Framework\TestCase; -class DependencyCheckerPdfTest extends TestCase { +class DependencyCheckerPDFTest extends TestCase { public function testGhostScriptDependency() { $this->expectNotToPerformAssertions(); DependencyChecker::isGhostscriptAvailable(); diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 45130ca9..c2648307 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -2,24 +2,25 @@ namespace Input; -use Mindee\Client; use Mindee\Error\ErrorCode; use Mindee\Error\MindeePDFException; use Mindee\Error\MindeeSourceException; use Mindee\Image\ImageCompressor; +use Mindee\Input\Base64Input; +use Mindee\Input\BytesInput; +use Mindee\Input\FileInput; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; -use Mindee\Input\FileInput; -use Mindee\Input\BytesInput; -use Mindee\Input\Base64Input; use Mindee\PDF\PDFCompressor; use Mindee\PDF\PDFUtils; +use Mindee\V1\Client; use PHPUnit\Framework\TestCase; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\PdfParserException; use setasign\Fpdi\PdfReader\PdfReaderException; -use const Mindee\Http\API_KEY_ENV_NAME; +use TestingUtilities; +use const Mindee\V1\HTTP\API_KEY_ENV_NAME; use const Mindee\Input\KEEP_ONLY; use const Mindee\Input\REMOVE; @@ -40,20 +41,20 @@ protected function tearDown(): void putenv(API_KEY_ENV_NAME . '=' . $this->oldKey); $filesToDelete = [ - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress100.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress85.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress50.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress10.jpg", - \TestingUtilities::getRootDataDir() . "/output/compress1.jpg", - \TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", - \TestingUtilities::getRootDataDir() . "/output/not_compressed_multipage.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", - \TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", - \TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf" + TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", + TestingUtilities::getRootDataDir() . "/output/compress100.jpg", + TestingUtilities::getRootDataDir() . "/output/compress85.jpg", + TestingUtilities::getRootDataDir() . "/output/compress50.jpg", + TestingUtilities::getRootDataDir() . "/output/compress10.jpg", + TestingUtilities::getRootDataDir() . "/output/compress1.jpg", + TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", + TestingUtilities::getRootDataDir() . "/output/not_compressed_multipage.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", + TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf" ]; foreach ($filesToDelete as $file) { @@ -66,20 +67,20 @@ protected function tearDown(): void public function testPDFCountPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->assertEquals(12, $inputObj->getPageCount()); } public function testPDFReconstructOK() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); $this->assertEquals(5, $inputObj->getPageCount()); } public function testPDFReadContents() { - $inputDoc = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $contents = $inputDoc->readContents(); $this->assertEquals("multipage.pdf", $contents[0]); } @@ -89,13 +90,13 @@ public function testPDFReadContents() */ public function testPDFCutNPages(array $indexes) { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions($indexes, KEEP_ONLY, 2)); try { $basePdf = new FPDI(); $cutPdf = new FPDI(); $pageCountCutPdf = $cutPdf->setSourceFile( - \TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf" + TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf" ); $pageCountBasePdf = $basePdf->setSourceFile($inputObj->fileObject->getFilename()); $basePdf->Close(); @@ -106,7 +107,7 @@ public function testPDFCutNPages(array $indexes) $basePdf = new FPDI(); $cutPdf = new FPDI(); for ($pageNumber = 0; $pageNumber < $pageCountBasePdf; $pageNumber++) { - $cutPdf->setSourceFile(\TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf"); + $cutPdf->setSourceFile(TestingUtilities::getFileTypesDir() . "/pdf/multipage_cut-" . count($indexes) . ".pdf"); $basePdf->setSourceFile($inputObj->fileObject->getFilename()); $cutPdf->AddPage(); $cutPdf->useTemplate($cutPdf->importPage($pageNumber + 1)); @@ -134,14 +135,14 @@ public function pageIndexesProvider() public function testPDFKeep5FirstPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); $this->assertEquals(5, $inputObj->getPageCount()); } public function testPDFKeepInvalidPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 17], KEEP_ONLY, 2)); $this->assertEquals(2, $inputObj->getPageCount()); } @@ -149,35 +150,35 @@ public function testPDFKeepInvalidPages() public function testPDFRemove5LastPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([-5, -4, -3, -2, -1], REMOVE, 2)); $this->assertEquals(7, $inputObj->getPageCount()); } public function testPDFRemove5FirstPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], REMOVE, 2)); $this->assertEquals(7, $inputObj->getPageCount()); } public function testPDFRemoveInvalidPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([16], REMOVE, 2)); $this->assertEquals(12, $inputObj->getPageCount()); } public function testPDFKeepNoPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->expectException(MindeePDFException::class); $inputObj->applyPageOptions(new PageOptions([], KEEP_ONLY, 2)); } public function testPDFRemoveAllPages() { - $inputObj = new PathInput(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $this->expectException(MindeePDFException::class); $pageOptions = new PageOptions(range(0, $inputObj->getPageCount() - 1), REMOVE, 2); $inputObj->applyPageOptions(pageOptions: $pageOptions); @@ -185,8 +186,8 @@ public function testPDFRemoveAllPages() public function testPDFInputFromFile() { - $fileContents = file_get_contents(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $fileRef = fopen(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf", "r"); + $fileContents = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $fileRef = fopen(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf", "r"); $inputDoc = new FileInput($fileRef); $contents = $inputDoc->readContents(); $this->assertEquals("multipage.pdf", $contents[0]); @@ -195,7 +196,7 @@ public function testPDFInputFromFile() public function testPDFInputFromBytes() { - $pdfBytes = file_get_contents(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $pdfBytes = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputDoc = new BytesInput($pdfBytes, "dummy.pdf"); $contents = $inputDoc->readContents(); $this->assertEquals("dummy.pdf", $contents[0]); @@ -204,54 +205,54 @@ public function testPDFInputFromBytes() public function testInputFromRawb64String() { - $pdfBytes = file_get_contents(\TestingUtilities::getFileTypesDir() . "/receipt.txt"); + $pdfBytes = file_get_contents(TestingUtilities::getFileTypesDir() . "/receipt.txt"); $inputDoc = new Base64Input($pdfBytes, "dummy.pdf"); $contents = $inputDoc->readContents(); $this->assertEquals("dummy.pdf", $contents[0]); $this->assertEquals(str_replace("\n", "", $pdfBytes), str_replace("\n", "", base64_encode($contents[1]))); } - public function testShouldNotRaiseMimeErrorForBrokenFixablePdf() + public function testShouldNotRaiseMimeErrorForBrokenFixablePDF() { $this->expectNotToPerformAssertions(); - $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); + $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); } - public function testShouldRaiseErrorForBrokenUnfixablePdf() + public function testShouldRaiseErrorForBrokenUnfixablePDF() { $this->expectException(MindeeSourceException::class); - $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); + $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); } - public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf() + public function testShouldSendCorrectResultsForBrokenFixableInvoicePDF() { $sourceDocOriginal = $this->dummyClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' + TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' ); - $sourceDocFixed = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); + $sourceDocFixed = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); $this->assertEquals($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); } public function testImageQualityCompressionFromInputSource() { - $receiptInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $receiptInput->compress(80); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", file_get_contents($receiptInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); - $sizeCompressed = filesize(\TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg"); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg"); $this->assertGreaterThan($sizeCompressed, $sizeOriginal); } public function testDirectImageQualityCompression() { - $receiptInput = $this->dummyClient->sourceFromPath(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $compresses = [ 100 => ImageCompressor::compress($receiptInput->fileObject, 100), 85 => ImageCompressor::compress($receiptInput->fileObject), @@ -261,11 +262,11 @@ public function testDirectImageQualityCompression() ]; $outputFiles = [ - 100 => \TestingUtilities::getRootDataDir() . "/output/compress100.jpg", - 85 => \TestingUtilities::getRootDataDir() . "/output/compress85.jpg", - 50 => \TestingUtilities::getRootDataDir() . "/output/compress50.jpg", - 10 => \TestingUtilities::getRootDataDir() . "/output/compress10.jpg", - 1 => \TestingUtilities::getRootDataDir() . "/output/compress1.jpg", + 100 => TestingUtilities::getRootDataDir() . "/output/compress100.jpg", + 85 => TestingUtilities::getRootDataDir() . "/output/compress85.jpg", + 50 => TestingUtilities::getRootDataDir() . "/output/compress50.jpg", + 10 => TestingUtilities::getRootDataDir() . "/output/compress10.jpg", + 1 => TestingUtilities::getRootDataDir() . "/output/compress1.jpg", ]; $compressSize = []; @@ -285,9 +286,9 @@ public function testDirectImageQualityCompression() public function testPDFSourceText() { - $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'); + $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."); @@ -296,33 +297,33 @@ public function testPDFSourceText() public function testCompressPDFFromInputSource() { $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" + TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" ); $this->assertFalse($pdfInput->hasSourceText()); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", + TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . '/pdf/not_blank_image_only.pdf'); - $sizeIgnored = filesize(\TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf"); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/pdf/not_blank_image_only.pdf'); + $sizeIgnored = filesize(TestingUtilities::getRootDataDir() . "/output/not_compressed.pdf"); $this->assertEquals($sizeIgnored, $sizeOriginal); $pdfInput->compress(90, null, null, true, false); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", + TestingUtilities::getRootDataDir() . "/output/compress_indirect.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeCompressed = filesize(\TestingUtilities::getRootDataDir() . '/output/compress_indirect.pdf'); + $sizeCompressed = filesize(TestingUtilities::getRootDataDir() . '/output/compress_indirect.pdf'); $this->assertLessThan($sizeOriginal, $sizeCompressed); } public function testCompressPDFFromCompressor() { $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' + TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' ); - $sizeOriginal = filesize(\TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf'); + $sizeOriginal = filesize(TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf'); $this->assertFalse($pdfInput->hasSourceText()); $pdfCompresses = [ @@ -332,10 +333,10 @@ public function testCompressPDFFromCompressor() 10 => PDFCompressor::compress($pdfInput->fileObject, 10), ]; $outputFiles = [ - 85 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", - 75 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", - 50 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", - 10 => \TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", + 85 => TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", + 75 => TestingUtilities::getRootDataDir() . "/output/compress_direct_75.pdf", + 50 => TestingUtilities::getRootDataDir() . "/output/compress_direct_50.pdf", + 10 => TestingUtilities::getRootDataDir() . "/output/compress_direct_10.pdf", ]; $compressSize = []; @@ -356,25 +357,25 @@ public function testSourceTextPDFCompression() { $pdfInput = $this->dummyClient->sourceFromPath( - \TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf" + TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf" ); $this->assertTrue($pdfInput->hasSourceText()); $pdfInput->compress(5, null, null, true, false); file_put_contents( - \TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf", + TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf", file_get_contents($pdfInput->fileObject->getFilename()) ); - $sizeOriginal = filesize(\TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $sizeTextCompressed = filesize(\TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); + $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $sizeTextCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); $this->assertEquals($sizeTextCompressed, $sizeOriginal); // Note: Greater size when compressed is expected due to original not having any images, so the operation will // be aborted. $this->assertEquals( str_repeat('*', 650), - implode('', str_replace(" ", "", PDFUtils::extractPagesTextElements(\TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) + implode('', str_replace(" ", "", PDFUtils::extractPagesTextElements(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) ); } } diff --git a/tests/Input/URLInputSourceTest.php b/tests/Input/URLInputSourceTest.php index bb43f4ae..a3c05e99 100644 --- a/tests/Input/URLInputSourceTest.php +++ b/tests/Input/URLInputSourceTest.php @@ -2,12 +2,11 @@ namespace Input; -use Mindee\Client; use Mindee\Error\MindeeSourceException; use Mindee\Input\URLInputSource; +use Mindee\V1\Client; use PHPUnit\Framework\TestCase; - -use const Mindee\Http\API_KEY_ENV_NAME; +use const Mindee\V1\HTTP\API_KEY_ENV_NAME; class URLInputSourceTest extends TestCase { diff --git a/tests/V1/Error/MindeeHttpExceptionTest.php b/tests/V1/Error/MindeeHttpExceptionTest.php index be2e0e31..1a248b0e 100644 --- a/tests/V1/Error/MindeeHttpExceptionTest.php +++ b/tests/V1/Error/MindeeHttpExceptionTest.php @@ -2,11 +2,11 @@ namespace V1\Error; -use Mindee\Client; use Mindee\Error\MindeeHttpClientException; use Mindee\Error\MindeeHttpException; use Mindee\Input\PathInput; -use Mindee\Product\Invoice\InvoiceV4; +use Mindee\V1\Client; +use Mindee\V1\Product\Invoice\InvoiceV4; use PHPUnit\Framework\TestCase; class MindeeHttpExceptionTest extends TestCase diff --git a/tests/V1/Extraction/ImageExtractorTest.php b/tests/V1/Extraction/ImageExtractorTest.php index 15c25af3..d38c2451 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Extraction/ImageExtractorTest.php @@ -2,12 +2,12 @@ namespace V1\Extraction; -use Mindee\Client; -use Mindee\V1\Image\ImageExtractor; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; -use Mindee\Product\BarcodeReader\BarcodeReaderV1; -use Mindee\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1; +use Mindee\V1\Client; +use Mindee\V1\Image\ImageExtractor; +use Mindee\V1\Product\BarcodeReader\BarcodeReaderV1; +use Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1; use PHPUnit\Framework\TestCase; class ImageExtractorTest extends TestCase @@ -82,7 +82,7 @@ public function testGivenAnImageShouldExtractValueFields() } } - public function testGivenAPdfShouldExtractPositionFields() + public function testGivenAPDFShouldExtractPositionFields() { $imageInput = new PathInput( \TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/multipage_sample.pdf" diff --git a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php index 064752dd..ea698572 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php @@ -2,18 +2,18 @@ namespace V1\Extraction; -use Mindee\Client; -use Mindee\Extraction\PdfExtractor; +use Mindee\Extraction\PDFExtractor; use Mindee\Input\PathInput; -use Mindee\Parsing\Common\Document; -use Mindee\Product\Invoice\InvoiceV4; -use Mindee\Product\InvoiceSplitter\InvoiceSplitterV1; +use Mindee\V1\Client; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Product\Invoice\InvoiceV4; +use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; use TestingUtilities; require_once(__DIR__ . "/../../TestingUtilities.php"); -class PdfExtractorTest extends TestCase +class PDFExtractorTest extends TestCase { private const PRODUCT_DATA_DIR = '/tests/resources/products'; @@ -30,7 +30,7 @@ private function prepareInvoiceReturn(string $rstFilePath, Document $invoicePred * @test * @group functional */ - public function testPdfShouldExtractInvoicesStrict() + public function testPDFShouldExtractInvoicesStrict() { $client = new Client(); $invoiceSplitterInput = new PathInput( @@ -38,7 +38,7 @@ public function testPdfShouldExtractInvoicesStrict() ); $response = $client->enqueueAndParse(InvoiceSplitterV1::class, $invoiceSplitterInput); $inference = $response->document->inference; - $pdfExtractor = new PdfExtractor($invoiceSplitterInput); + $pdfExtractor = new PDFExtractor($invoiceSplitterInput); $this->assertEquals(2, $pdfExtractor->getPageCount()); $extractedPdfsStrict = $pdfExtractor->extractInvoices($inference->prediction->invoicePageGroups); diff --git a/tests/V1/Extraction/PdfExtractorTest.php b/tests/V1/Extraction/PDFExtractorTest.php similarity index 89% rename from tests/V1/Extraction/PdfExtractorTest.php rename to tests/V1/Extraction/PDFExtractorTest.php index caca0452..4a16da31 100644 --- a/tests/V1/Extraction/PdfExtractorTest.php +++ b/tests/V1/Extraction/PDFExtractorTest.php @@ -3,14 +3,14 @@ namespace V1\Extraction; -use Mindee\Client; -use Mindee\Extraction\PdfExtractor; +use Mindee\Extraction\PDFExtractor; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; -use Mindee\Product\InvoiceSplitter\InvoiceSplitterV1; +use Mindee\V1\Client; +use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; -class PdfExtractorTest extends TestCase +class PDFExtractorTest extends TestCase { private Client $dummyClient; @@ -23,8 +23,8 @@ public function testGivenAnImageShouldExtractAPDF() { $jpg = \TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; $localInput = new PathInput($jpg); - $this->assertFalse($localInput->isPdf()); - $extractor = new PdfExtractor($localInput); + $this->assertFalse($localInput->isPDF()); + $extractor = new PDFExtractor($localInput); $this->assertEquals(1, $extractor->getPageCount()); } @@ -37,7 +37,7 @@ public function testGivenAPDFShouldExtractInvoicesNoStrict() $response = $this->getPrediction(); $this->assertNotNull($response); $inference = $response->document->inference; - $extractor = new PdfExtractor($pdf); + $extractor = new PDFExtractor($pdf); $this->assertEquals(5, $extractor->getPageCount()); $extractedPDFSNoStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups); @@ -60,7 +60,7 @@ public function testGivenAPDFShouldExtractInvoicesStrict() $this->assertNotNull($response); $inference = $response->document->inference; - $extractor = new PdfExtractor($pdf); + $extractor = new PDFExtractor($pdf); $this->assertEquals(5, $extractor->getPageCount()); $extractedPDFStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups, true); diff --git a/tests/V1/Http/MindeeApiTest.php b/tests/V1/Http/MindeeApiTest.php index bc355a4f..5776a4a8 100644 --- a/tests/V1/Http/MindeeApiTest.php +++ b/tests/V1/Http/MindeeApiTest.php @@ -3,10 +3,10 @@ namespace V1\Http; use Mindee\Error\MindeeException; -use Mindee\Http\MindeeApi; -use Mindee\Product\InvoiceSplitter\InvoiceSplitterV1; +use Mindee\V1\HTTP\MindeeAPI; +use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; -use const Mindee\Http\API_KEY_ENV_NAME; +use const Mindee\V1\HTTP\API_KEY_ENV_NAME; class MindeeApiTest extends TestCase { @@ -23,16 +23,16 @@ protected function tearDown(): void public function testGivenOTSParametersAProperMindeeApiObjectShouldBeCreated() { - $settings = new MindeeApi("my-api-key", InvoiceSplitterV1::$endpointName); + $settings = new MindeeAPI("my-api-key", InvoiceSplitterV1::$endpointName); $this->assertEquals("my-api-key", $settings->apiKey); $this->assertEquals(InvoiceSplitterV1::$endpointName, $settings->endpointName); - $this->assertEquals(\Mindee\Client::DEFAULT_OWNER, $settings->accountName); + $this->assertEquals(\Mindee\V1\Client::DEFAULT_OWNER, $settings->accountName); $this->assertEquals("1", $settings->version); } public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated() { - $settings = new MindeeApi("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); + $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); @@ -43,6 +43,6 @@ public function testGivenInvalidApiKeyAnExceptionShouldBeThrown() { $this->expectException(MindeeException::class); putenv(API_KEY_ENV_NAME . '='); - new MindeeApi(null, InvoiceSplitterV1::$endpointName); + new MindeeAPI(null, InvoiceSplitterV1::$endpointName); } } diff --git a/tests/V1/Input/URLInputSourceTestFunctional.php b/tests/V1/Input/URLInputSourceTestFunctional.php index 432de859..20800724 100644 --- a/tests/V1/Input/URLInputSourceTestFunctional.php +++ b/tests/V1/Input/URLInputSourceTestFunctional.php @@ -2,8 +2,8 @@ namespace V1\Input; -use Mindee\Client; -use Mindee\Product\Invoice\InvoiceV4; +use Mindee\V1\Client; +use Mindee\V1\Product\Invoice\InvoiceV4; use PHPUnit\Framework\TestCase; class URLInputSourceTestFunctional extends TestCase diff --git a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php index f48e153f..4911915c 100644 --- a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php +++ b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php @@ -2,9 +2,9 @@ namespace V1\Parsing\Common; -use Mindee\Http\ResponseValidation; -use Mindee\Parsing\Common\AsyncPredictResponse; -use Mindee\Product\InvoiceSplitter\InvoiceSplitterV1; +use Mindee\V1\HTTP\ResponseValidation; +use Mindee\V1\Parsing\Common\AsyncPredictResponse; +use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; class AsyncPredictResponseTest extends TestCase diff --git a/tests/V1/Parsing/Common/Extras/CropperExtraTest.php b/tests/V1/Parsing/Common/Extras/CropperExtraTest.php index 62ce9757..7805073a 100644 --- a/tests/V1/Parsing/Common/Extras/CropperExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/CropperExtraTest.php @@ -2,9 +2,9 @@ namespace V1\Parsing\Common\Extras; -use Mindee\Input\PredictOptions; -use Mindee\Parsing\Common\Document; -use Mindee\Product\Receipt\ReceiptV5; +use Mindee\V1\ClientOptions\PredictOptions; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Product\Receipt\ReceiptV5; use PHPUnit\Framework\TestCase; class CropperExtraTest extends TestCase diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 65e84521..35486c32 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -2,11 +2,11 @@ namespace V1\Parsing\Common\Extras; -use Mindee\Client; -use Mindee\Input\PredictMethodOptions; -use Mindee\Input\PredictOptions; -use Mindee\Product\InternationalId\InternationalIdV2; -use Mindee\Product\Invoice\InvoiceV4; +use Mindee\V1\Client; +use Mindee\V1\ClientOptions\PredictMethodOptions; +use Mindee\V1\ClientOptions\PredictOptions; +use Mindee\V1\Product\InternationalId\InternationalIdV2; +use Mindee\V1\Product\Invoice\InvoiceV4; use PHPUnit\Framework\TestCase; class ExtrasIntegrationFunctional extends TestCase diff --git a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php index 48896e73..efeeece1 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php @@ -2,7 +2,7 @@ namespace V1\Parsing\Common\Extras; -use Mindee\Product\InternationalId\InternationalIdV2; +use Mindee\V1\Product\InternationalId\InternationalIdV2; use PHPUnit\Framework\TestCase; class FullTextOCRTest extends TestCase @@ -16,7 +16,7 @@ protected function setUp(): void private function loadDocument() { - $dummyClient = new \Mindee\Client("dummy-key"); + $dummyClient = new \Mindee\V1\Client("dummy-key"); $localResponse = new \Mindee\Input\LocalResponse($this->extrasDir . '/full_text_ocr/complete.json'); $response = $dummyClient->loadPrediction(InternationalIdV2::class, $localResponse); return $response->document; diff --git a/tests/V1/Parsing/Common/Ocr/OcrTest.php b/tests/V1/Parsing/Common/OCR/OCRTest.php similarity index 88% rename from tests/V1/Parsing/Common/Ocr/OcrTest.php rename to tests/V1/Parsing/Common/OCR/OCRTest.php index 0fd958d3..334bd12f 100644 --- a/tests/V1/Parsing/Common/Ocr/OcrTest.php +++ b/tests/V1/Parsing/Common/OCR/OCRTest.php @@ -1,19 +1,19 @@ ocrObject = new Ocr($jsonData["document"]["ocr"]); + $this->ocrObject = new OCR($jsonData["document"]["ocr"]); } public function testResponse() { diff --git a/tests/V1/Parsing/Common/PredictResponseTest.php b/tests/V1/Parsing/Common/PredictResponseTest.php index ebcd8359..aa2bd5db 100644 --- a/tests/V1/Parsing/Common/PredictResponseTest.php +++ b/tests/V1/Parsing/Common/PredictResponseTest.php @@ -2,9 +2,9 @@ namespace V1\Parsing\Common; -use Mindee\Parsing\Common\PredictResponse; -use Mindee\Product\Invoice\InvoiceV4; -use Mindee\Product\Invoice\InvoiceV4Document; +use Mindee\V1\Parsing\Common\PredictResponse; +use Mindee\V1\Product\Invoice\InvoiceV4; +use Mindee\V1\Product\Invoice\InvoiceV4Document; use PHPUnit\Framework\TestCase; class PredictResponseTest extends TestCase diff --git a/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php b/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php index a3302b99..6ee6fc17 100644 --- a/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php +++ b/tests/V1/Product/BarcodeReader/BarcodeReaderV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\BarcodeReader; -use Mindee\Parsing\Common\Document; use Mindee\Product\BarcodeReader; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class BarcodeReaderV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BarcodeReader\BarcodeReaderV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BarcodeReader\BarcodeReaderV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\BarcodeReader\BarcodeReaderV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\BarcodeReader\BarcodeReaderV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php index 9970cdc8..1eb0e60b 100644 --- a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php +++ b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\BillOfLading; -use Mindee\Parsing\Common\Document; use Mindee\Product\BillOfLading; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class BillOfLadingV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BillOfLading\BillOfLadingV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BillOfLading\BillOfLadingV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\BillOfLading\BillOfLadingV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\BillOfLading\BillOfLadingV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/BusinessCard/BusinessCardV1Test.php b/tests/V1/Product/BusinessCard/BusinessCardV1Test.php index cbfcf915..9096142b 100644 --- a/tests/V1/Product/BusinessCard/BusinessCardV1Test.php +++ b/tests/V1/Product/BusinessCard/BusinessCardV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\BusinessCard; -use Mindee\Parsing\Common\Document; use Mindee\Product\BusinessCard; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class BusinessCardV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BusinessCard\BusinessCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BusinessCard\BusinessCardV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\BusinessCard\BusinessCardV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\BusinessCard\BusinessCardV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Cropper/CropperV1Test.php b/tests/V1/Product/Cropper/CropperV1Test.php index 2807bd2d..cb081218 100644 --- a/tests/V1/Product/Cropper/CropperV1Test.php +++ b/tests/V1/Product/Cropper/CropperV1Test.php @@ -2,9 +2,9 @@ namespace V1\Product\Cropper; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; use Mindee\Product\Cropper; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; use PHPUnit\Framework\TestCase; class CropperV1Test extends TestCase @@ -22,9 +22,9 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Cropper\CropperV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Cropper\CropperV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(Cropper\CropperV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(\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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } diff --git a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php index 2ff3f366..083b6c47 100644 --- a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php +++ b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\DeliveryNote; -use Mindee\Parsing\Common\Document; use Mindee\Product\DeliveryNote; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class DeliveryNoteV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(DeliveryNote\DeliveryNoteV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\DeliveryNote\DeliveryNoteV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\DeliveryNote\DeliveryNoteV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php b/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php index 729fb748..18722d57 100644 --- a/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php +++ b/tests/V1/Product/DriverLicense/DriverLicenseV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\DriverLicense; -use Mindee\Parsing\Common\Document; use Mindee\Product\DriverLicense; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class DriverLicenseV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(DriverLicense\DriverLicenseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(DriverLicense\DriverLicenseV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\DriverLicense\DriverLicenseV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\DriverLicense\DriverLicenseV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php b/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php index 6182e57b..c26adc17 100644 --- a/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php +++ b/tests/V1/Product/FinancialDocument/FinancialDocumentV1Test.php @@ -2,9 +2,9 @@ namespace V1\Product\FinancialDocument; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; use Mindee\Product\FinancialDocument; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; use PHPUnit\Framework\TestCase; class FinancialDocumentV1Test extends TestCase @@ -28,11 +28,11 @@ protected function setUp(): void $completeDocJSONInvoice = json_decode($completeDocFileInvoice, true); $completeDocJSONReceipt = json_decode($completeDocFileReceipt, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDocInvoice = new Document(FinancialDocument\FinancialDocumentV1::class, $completeDocJSONInvoice["document"]); - $this->completeDocReceipt = new Document(FinancialDocument\FinancialDocumentV1::class, $completeDocJSONReceipt["document"]); - $this->emptyDoc = new Document(FinancialDocument\FinancialDocumentV1::class, $emptyDocJSON["document"]); - $this->completePage0Invoice = new Page(FinancialDocument\FinancialDocumentV1Document::class, $completeDocJSONInvoice["document"]["inference"]["pages"][0]); - $this->completePage0Receipt = new Page(FinancialDocument\FinancialDocumentV1Document::class, $completeDocJSONReceipt["document"]["inference"]["pages"][0]); + $this->completeDocInvoice = new Document(\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->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"); diff --git a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php index 0a06bfd2..0afebde3 100644 --- a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php +++ b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\BankAccountDetails; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\BankAccountDetails; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class BankAccountDetailsV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BankAccountDetails\BankAccountDetailsV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankAccountDetails\BankAccountDetailsV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php index 3e6d129e..7b92f2ca 100644 --- a/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php +++ b/tests/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\BankAccountDetails; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\BankAccountDetails; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class BankAccountDetailsV2Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BankAccountDetails\BankAccountDetailsV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankAccountDetails\BankAccountDetailsV2::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php b/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php index ce17ea28..57d859ad 100644 --- a/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php +++ b/tests/V1/Product/Fr/CarteGrise/CarteGriseV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\CarteGrise; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\CarteGrise; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class CarteGriseV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(CarteGrise\CarteGriseV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(CarteGrise\CarteGriseV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php b/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php index 20c64e57..1d8166e0 100644 --- a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php +++ b/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\EnergyBill; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\EnergyBill; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class EnergyBillV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(EnergyBill\EnergyBillV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(EnergyBill\EnergyBillV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php b/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php index b9e53ab8..802e6d2c 100644 --- a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php +++ b/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\HealthCard; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\HealthCard; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class HealthCardV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(HealthCard\HealthCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthCard\HealthCardV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Fr/IdCard/IdCardV1Test.php b/tests/V1/Product/Fr/IdCard/IdCardV1Test.php index 41e5060f..0fecdcb8 100644 --- a/tests/V1/Product/Fr/IdCard/IdCardV1Test.php +++ b/tests/V1/Product/Fr/IdCard/IdCardV1Test.php @@ -2,9 +2,9 @@ namespace V1\Product\Fr\IdCard; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; use Mindee\Product\Fr\IdCard; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; use PHPUnit\Framework\TestCase; class IdCardV1Test extends TestCase @@ -22,9 +22,9 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(IdCard\IdCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IdCard\IdCardV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(IdCard\IdCardV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(\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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } diff --git a/tests/V1/Product/Fr/IdCard/IdCardV2Test.php b/tests/V1/Product/Fr/IdCard/IdCardV2Test.php index 74bdf21b..13716008 100644 --- a/tests/V1/Product/Fr/IdCard/IdCardV2Test.php +++ b/tests/V1/Product/Fr/IdCard/IdCardV2Test.php @@ -2,9 +2,9 @@ namespace V1\Product\Fr\IdCard; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; use Mindee\Product\Fr\IdCard; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; use PHPUnit\Framework\TestCase; class IdCardV2Test extends TestCase @@ -22,9 +22,9 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(IdCard\IdCardV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IdCard\IdCardV2::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(IdCard\IdCardV2Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(\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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } diff --git a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php b/tests/V1/Product/Fr/Payslip/PayslipV3Test.php index 1dd77e2d..0fb56070 100644 --- a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php +++ b/tests/V1/Product/Fr/Payslip/PayslipV3Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Fr\Payslip; -use Mindee\Parsing\Common\Document; use Mindee\Product\Fr\Payslip; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class PayslipV3Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Payslip\PayslipV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Payslip\PayslipV3::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Generated/GeneratedV1Test.php b/tests/V1/Product/Generated/GeneratedV1Test.php index 3b812293..25dac487 100644 --- a/tests/V1/Product/Generated/GeneratedV1Test.php +++ b/tests/V1/Product/Generated/GeneratedV1Test.php @@ -2,14 +2,14 @@ namespace V1\Product\Generated; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; -use Mindee\Parsing\Generated\GeneratedListField; -use Mindee\Parsing\Generated\GeneratedObjectField; -use Mindee\Parsing\Standard\PositionField; -use Mindee\Parsing\Standard\StringField; -use Mindee\Product\Generated\GeneratedV1; -use Mindee\Product\Generated\GeneratedV1Page; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; +use Mindee\V1\Parsing\Generated\GeneratedListField; +use Mindee\V1\Parsing\Generated\GeneratedObjectField; +use Mindee\V1\Parsing\Standard\PositionField; +use Mindee\V1\Parsing\Standard\StringField; +use Mindee\V1\Product\Generated\GeneratedV1; +use Mindee\V1\Product\Generated\GeneratedV1Page; use PHPUnit\Framework\TestCase; diff --git a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php b/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php index 09e8735e..ffa89d39 100644 --- a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php +++ b/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Ind\IndianPassport; -use Mindee\Parsing\Common\Document; use Mindee\Product\Ind\IndianPassport; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class IndianPassportV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(IndianPassport\IndianPassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(IndianPassport\IndianPassportV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/InternationalId/InternationalIdV2Test.php b/tests/V1/Product/InternationalId/InternationalIdV2Test.php index 82aeb855..f83381f9 100644 --- a/tests/V1/Product/InternationalId/InternationalIdV2Test.php +++ b/tests/V1/Product/InternationalId/InternationalIdV2Test.php @@ -2,8 +2,8 @@ namespace V1\Product\InternationalId; -use Mindee\Parsing\Common\Document; use Mindee\Product\InternationalId; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class InternationalIdV2Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(InternationalId\InternationalIdV2::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(InternationalId\InternationalIdV2::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\InternationalId\InternationalIdV2::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\InternationalId\InternationalIdV2::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Invoice/InvoiceV4Test.php b/tests/V1/Product/Invoice/InvoiceV4Test.php index 5595e6c4..c81b7367 100644 --- a/tests/V1/Product/Invoice/InvoiceV4Test.php +++ b/tests/V1/Product/Invoice/InvoiceV4Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Invoice; -use Mindee\Parsing\Common\Document; use Mindee\Product\Invoice; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class InvoiceV4Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Invoice\InvoiceV4::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Invoice\InvoiceV4::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\Invoice\InvoiceV4::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\Invoice\InvoiceV4::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php b/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php index 81d953cd..f931b1c7 100644 --- a/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php +++ b/tests/V1/Product/InvoiceSplitter/InvoiceSplitterV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\InvoiceSplitter; -use Mindee\Parsing\Common\Document; use Mindee\Product\InvoiceSplitter; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class InvoiceSplitterV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(InvoiceSplitter\InvoiceSplitterV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(InvoiceSplitter\InvoiceSplitterV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php b/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php index d16f66f6..fa738fc4 100644 --- a/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php +++ b/tests/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\MultiReceiptsDetector; -use Mindee\Parsing\Common\Document; use Mindee\Product\MultiReceiptsDetector; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class MultiReceiptsDetectorV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php index ead37651..b5593e22 100644 --- a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php +++ b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\NutritionFactsLabel; -use Mindee\Parsing\Common\Document; use Mindee\Product\NutritionFactsLabel; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class NutritionFactsLabelV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(NutritionFactsLabel\NutritionFactsLabelV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Passport/PassportV1Test.php b/tests/V1/Product/Passport/PassportV1Test.php index 7408188c..d3748026 100644 --- a/tests/V1/Product/Passport/PassportV1Test.php +++ b/tests/V1/Product/Passport/PassportV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Passport; -use Mindee\Parsing\Common\Document; use Mindee\Product\Passport; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class PassportV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Passport\PassportV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Passport\PassportV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\Passport\PassportV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\Passport\PassportV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Receipt/ReceiptV5Test.php b/tests/V1/Product/Receipt/ReceiptV5Test.php index 7e282df1..d92c110e 100644 --- a/tests/V1/Product/Receipt/ReceiptV5Test.php +++ b/tests/V1/Product/Receipt/ReceiptV5Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Receipt; -use Mindee\Parsing\Common\Document; use Mindee\Product\Receipt; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class ReceiptV5Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Receipt\ReceiptV5::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Receipt\ReceiptV5::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\Receipt\ReceiptV5::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\Receipt\ReceiptV5::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Resume/ResumeV1Test.php b/tests/V1/Product/Resume/ResumeV1Test.php index 876d4551..39ff71de 100644 --- a/tests/V1/Product/Resume/ResumeV1Test.php +++ b/tests/V1/Product/Resume/ResumeV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Resume; -use Mindee\Parsing\Common\Document; use Mindee\Product\Resume; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class ResumeV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(Resume\ResumeV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(Resume\ResumeV1::class, $emptyDocJSON["document"]); + $this->completeDoc = new Document(\Mindee\V1\Product\Resume\ResumeV1::class, $completeDocJSON["document"]); + $this->emptyDoc = new Document(\Mindee\V1\Product\Resume\ResumeV1::class, $emptyDocJSON["document"]); $this->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php b/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php index 50b7162f..e20c40cf 100644 --- a/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php +++ b/tests/V1/Product/Us/BankCheck/BankCheckV1Test.php @@ -2,9 +2,9 @@ namespace V1\Product\Us\BankCheck; -use Mindee\Parsing\Common\Document; -use Mindee\Parsing\Common\Page; use Mindee\Product\Us\BankCheck; +use Mindee\V1\Parsing\Common\Document; +use Mindee\V1\Parsing\Common\Page; use PHPUnit\Framework\TestCase; class BankCheckV1Test extends TestCase @@ -22,9 +22,9 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(BankCheck\BankCheckV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(BankCheck\BankCheckV1::class, $emptyDocJSON["document"]); - $this->completePage0 = new Page(BankCheck\BankCheckV1Page::class, $completeDocJSON["document"]["inference"]["pages"][0]); + $this->completeDoc = new Document(\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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); $this->completePage0Reference = file_get_contents($productDir . "summary_page0.rst"); } diff --git a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php b/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php index 48d3fe02..3f09a552 100644 --- a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php +++ b/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Us\HealthcareCard; -use Mindee\Parsing\Common\Document; use Mindee\Product\Us\HealthcareCard; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class HealthcareCardV1Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(HealthcareCard\HealthcareCardV1::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(HealthcareCard\HealthcareCardV1::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Product/Us/UsMail/UsMailV3Test.php b/tests/V1/Product/Us/UsMail/UsMailV3Test.php index 38172d24..e3a70c24 100644 --- a/tests/V1/Product/Us/UsMail/UsMailV3Test.php +++ b/tests/V1/Product/Us/UsMail/UsMailV3Test.php @@ -2,8 +2,8 @@ namespace V1\Product\Us\UsMail; -use Mindee\Parsing\Common\Document; use Mindee\Product\Us\UsMail; +use Mindee\V1\Parsing\Common\Document; use PHPUnit\Framework\TestCase; class UsMailV3Test extends TestCase @@ -19,8 +19,8 @@ protected function setUp(): void $emptyDocFile = file_get_contents($productDir . "empty.json"); $completeDocJSON = json_decode($completeDocFile, true); $emptyDocJSON = json_decode($emptyDocFile, true); - $this->completeDoc = new Document(UsMail\UsMailV3::class, $completeDocJSON["document"]); - $this->emptyDoc = new Document(UsMail\UsMailV3::class, $emptyDocJSON["document"]); + $this->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->completeDocReference = file_get_contents($productDir . "summary_full.rst"); } diff --git a/tests/V1/Standard/AmountFieldTest.php b/tests/V1/Standard/AmountFieldTest.php index 314c19ae..cf3f654b 100644 --- a/tests/V1/Standard/AmountFieldTest.php +++ b/tests/V1/Standard/AmountFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\AmountField; +use Mindee\V1\Parsing\Standard\AmountField; use PHPUnit\Framework\TestCase; class AmountFieldTest extends TestCase diff --git a/tests/V1/Standard/ClassificationFieldTest.php b/tests/V1/Standard/ClassificationFieldTest.php index 9f4d1846..78f11227 100644 --- a/tests/V1/Standard/ClassificationFieldTest.php +++ b/tests/V1/Standard/ClassificationFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\ClassificationField; +use Mindee\V1\Parsing\Standard\ClassificationField; use PHPUnit\Framework\TestCase; class ClassificationFieldTest extends TestCase diff --git a/tests/V1/Standard/CompanyRegistrationFieldTest.php b/tests/V1/Standard/CompanyRegistrationFieldTest.php index 2d0445b9..15b7e5d5 100644 --- a/tests/V1/Standard/CompanyRegistrationFieldTest.php +++ b/tests/V1/Standard/CompanyRegistrationFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\CompanyRegistrationField; +use Mindee\V1\Parsing\Standard\CompanyRegistrationField; use PHPUnit\Framework\TestCase; class CompanyRegistrationFieldTest extends TestCase diff --git a/tests/V1/Standard/DateFieldTest.php b/tests/V1/Standard/DateFieldTest.php index bd76e60b..3f55410a 100644 --- a/tests/V1/Standard/DateFieldTest.php +++ b/tests/V1/Standard/DateFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\DateField; +use Mindee\V1\Parsing\Standard\DateField; use PHPUnit\Framework\TestCase; class DateFieldTest extends TestCase diff --git a/tests/V1/Standard/LocaleFieldTest.php b/tests/V1/Standard/LocaleFieldTest.php index e162309a..48805178 100644 --- a/tests/V1/Standard/LocaleFieldTest.php +++ b/tests/V1/Standard/LocaleFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\LocaleField; +use Mindee\V1\Parsing\Standard\LocaleField; use PHPUnit\Framework\TestCase; class LocaleFieldTest extends TestCase diff --git a/tests/V1/Standard/PaymentDetailsFieldTest.php b/tests/V1/Standard/PaymentDetailsFieldTest.php index edc14dc8..785e7468 100644 --- a/tests/V1/Standard/PaymentDetailsFieldTest.php +++ b/tests/V1/Standard/PaymentDetailsFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\PaymentDetailsField; +use Mindee\V1\Parsing\Standard\PaymentDetailsField; use PHPUnit\Framework\TestCase; class PaymentDetailsFieldTest extends TestCase diff --git a/tests/V1/Standard/PositionFieldTest.php b/tests/V1/Standard/PositionFieldTest.php index 009e60e6..509a2a9f 100644 --- a/tests/V1/Standard/PositionFieldTest.php +++ b/tests/V1/Standard/PositionFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\PositionField; +use Mindee\V1\Parsing\Standard\PositionField; use PHPUnit\Framework\TestCase; class PositionFieldTest extends TestCase diff --git a/tests/V1/Standard/StringFieldTest.php b/tests/V1/Standard/StringFieldTest.php index c3fe246c..f60d38bc 100644 --- a/tests/V1/Standard/StringFieldTest.php +++ b/tests/V1/Standard/StringFieldTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\StringField; +use Mindee\V1\Parsing\Standard\StringField; use PHPUnit\Framework\TestCase; class StringFieldTest extends TestCase diff --git a/tests/V1/Standard/TaxesTest.php b/tests/V1/Standard/TaxesTest.php index 7afed0aa..3e30a21a 100644 --- a/tests/V1/Standard/TaxesTest.php +++ b/tests/V1/Standard/TaxesTest.php @@ -2,7 +2,7 @@ namespace V1\Standard; -use Mindee\Parsing\Standard\TaxField; +use Mindee\V1\Parsing\Standard\TaxField; use PHPUnit\Framework\TestCase; class TaxesTest extends TestCase diff --git a/tests/V1/Workflow/WorkflowTest.php b/tests/V1/Workflow/WorkflowTest.php index ab9dd5bd..d6ed6a65 100644 --- a/tests/V1/Workflow/WorkflowTest.php +++ b/tests/V1/Workflow/WorkflowTest.php @@ -2,8 +2,8 @@ namespace V1\Workflow; -use Mindee\Parsing\Common\WorkflowResponse; -use Mindee\Product\Generated\GeneratedV1; +use Mindee\V1\Parsing\Common\WorkflowResponse; +use Mindee\V1\Product\Generated\GeneratedV1; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/V1/Workflow/WorkflowTestFunctional.php b/tests/V1/Workflow/WorkflowTestFunctional.php index 1144e612..9e99d3de 100644 --- a/tests/V1/Workflow/WorkflowTestFunctional.php +++ b/tests/V1/Workflow/WorkflowTestFunctional.php @@ -2,10 +2,10 @@ namespace V1\Workflow; -use Mindee\Client; -use Mindee\Input\PredictMethodOptions; -use Mindee\Input\WorkflowOptions; -use Mindee\Product\FinancialDocument\FinancialDocumentV1; +use Mindee\V1\Client; +use Mindee\V1\ClientOptions\PredictMethodOptions; +use Mindee\V1\ClientOptions\WorkflowOptions; +use Mindee\V1\Product\FinancialDocument\FinancialDocumentV1; use PHPUnit\Framework\TestCase; require_once(__DIR__ . "/../../TestingUtilities.php"); diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 3de066ed..91360e5e 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -2,23 +2,23 @@ namespace V2; -use Mindee\ClientV2; use Mindee\Error\MindeeException; -use Mindee\Http\MindeeApiV2; -use Mindee\Input\InferenceParameters; use Mindee\Input\LocalInputSource; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; -use Mindee\Parsing\V2\InferenceResponse; -use Mindee\Parsing\V2\JobResponse; +use Mindee\V2\Client; +use Mindee\V2\HTTP\MindeeAPIV2; +use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Product\Extraction\Params\InferenceParameters; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ClientV2Test extends TestCase { - private static function makeClientWithMockedApi(MindeeApiV2 $mockedApi): ClientV2 + private static function makeClientWithMockedApi(MindeeAPIV2 $mockedApi): Client { - $client = new ClientV2("dummy"); + $client = new Client("dummy"); $reflection = new \ReflectionClass($client); $property = $reflection->getProperty('mindeeApi'); $property->setAccessible(true); @@ -28,7 +28,7 @@ private static function makeClientWithMockedApi(MindeeApiV2 $mockedApi): ClientV public function testEnqueuePostAsync(): void { - $predictable = $this->createMock(MindeeApiV2::class); + $predictable = $this->createMock(MindeeAPIV2::class); $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $predictable->expects($this->once()) ->method('reqPostEnqueue') @@ -51,8 +51,8 @@ public function testEnqueuePostAsync(): void public function testDocumentGetJobAsync(): void { - /** @var MindeeApiV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeApiV2::class); + /** @var MindeeAPIV2&MockObject $predictable */ + $predictable = $this->createMock(MindeeAPIV2::class); $syntheticResponse = file_get_contents(\TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $processing = new JobResponse(json_decode($syntheticResponse, true)); @@ -72,8 +72,8 @@ public function testDocumentGetJobAsync(): void public function testDocumentGetInferenceAsync(): void { - /** @var MindeeApiV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeApiV2::class); + /** @var MindeeAPIV2&MockObject $predictable */ + $predictable = $this->createMock(MindeeAPIV2::class); $jsonFile = \TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; $this->assertFileExists($jsonFile, 'Test resource file must exist'); @@ -141,7 +141,7 @@ public function testInvalidBaseUrlRaisesMindeeException(): void putenv('MINDEE_V2_BASE_URL=https://invalid-v2.mindee.net'); try { - $client = new ClientV2('dummy-key'); + $client = new Client('dummy-key'); $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); $params = new InferenceParameters('dummy-model-id'); $client->enqueueAndGetInference($input, $params); diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index e2e70991..de2d0fa9 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -2,17 +2,17 @@ namespace V2; -use Mindee\ClientV2; use Mindee\Error\MindeeV2HttpException; -use Mindee\Input\InferenceParameters; use Mindee\Input\PathInput; use Mindee\Input\URLInputSource; +use Mindee\V2\Client; +use Mindee\V2\Product\Extraction\Params\InferenceParameters; use PHPUnit\Framework\TestCase; use TestingUtilities; class ClientV2TestFunctional extends TestCase { - private ClientV2 $mindeeClient; + private Client $mindeeClient; private string $modelId; protected function setUp(): void @@ -20,7 +20,7 @@ protected function setUp(): void $apiKey = getenv('MINDEE_V2_API_KEY'); $this->modelId = getenv('MINDEE_V2_FINDOC_MODEL_ID'); - $this->mindeeClient = new ClientV2($apiKey); + $this->mindeeClient = new Client($apiKey); } public function testParseFileEmptyMultiPageMustSucceed(): void diff --git a/tests/V2/FileOperations/CropFunctional.php b/tests/V2/FileOperations/CropFunctional.php index c7de38b2..cc1ea6c6 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -2,18 +2,18 @@ namespace V2\FileOperations; -use Mindee\ClientV2; -use Mindee\Input\InferenceParameters; use Mindee\Input\PathInput; -use Mindee\Parsing\V2\InferenceResponse; +use Mindee\V2\Client; use Mindee\V2\FileOperations\Crop; +use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Product\Crop\CropResponse; use Mindee\V2\Product\Crop\Params\CropParameters; +use Mindee\V2\Product\Extraction\Params\InferenceParameters; use PHPUnit\Framework\TestCase; class CropFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $cropModelId; private string $findocModelId; private string $outputDir; @@ -21,7 +21,7 @@ class CropFunctional extends TestCase protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY') ?: ''; - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->cropModelId = getenv('MINDEE_V2_CROP_MODEL_ID') ?: ''; $this->findocModelId = getenv('MINDEE_V2_FINDOC_MODEL_ID') ?: ''; @@ -81,14 +81,14 @@ public function testExtractCropsFromImageCorrectly(): void $file1Info = filesize($this->outputDir . '/crop_001.jpg'); $this->assertGreaterThanOrEqual(97000, $file1Info); - $this->assertLessThanOrEqual(100000, $file1Info); + $this->assertLessThanOrEqual(103000, $file1Info); $file2Info = filesize($this->outputDir . '/crop_002.jpg'); $this->assertGreaterThanOrEqual(97000, $file2Info); - $this->assertLessThanOrEqual(100000, $file2Info); + $this->assertLessThanOrEqual(103000, $file2Info); } - public function testExtractCropsFromEachPdfPageCorrectly(): void + public function testExtractCropsFromEachPDFPageCorrectly(): void { $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); $cropParams = new CropParameters($this->cropModelId); diff --git a/tests/V2/FileOperations/SplitFunctional.php b/tests/V2/FileOperations/SplitFunctional.php index dd12191d..83119fbf 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -2,18 +2,18 @@ namespace V2\FileOperations; -use Mindee\ClientV2; -use Mindee\Input\InferenceParameters; use Mindee\Input\PathInput; -use Mindee\Parsing\V2\InferenceResponse; +use Mindee\V2\Client; use Mindee\V2\FileOperations\Split; -use Mindee\V2\Product\Split\SplitResponse; +use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Product\Extraction\Params\InferenceParameters; use Mindee\V2\Product\Split\Params\SplitParameters; +use Mindee\V2\Product\Split\SplitResponse; use PHPUnit\Framework\TestCase; class SplitFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $splitModelId; private string $findocModelId; private string $outputDir; @@ -21,7 +21,7 @@ class SplitFunctional extends TestCase protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY') ?: ''; - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->splitModelId = getenv('MINDEE_V2_SPLIT_MODEL_ID') ?: ''; $this->findocModelId = getenv('MINDEE_V2_FINDOC_MODEL_ID') ?: ''; @@ -53,7 +53,7 @@ private function checkFindocReturn(InferenceResponse $findocResponse): void $this->assertGreaterThan(0, $totalAmount->value); } - public function testExtractSplitsFromPdfCorrectly(): void + public function testExtractSplitsFromPDFCorrectly(): void { $inputSource = new PathInput(\TestingUtilities::getV2ProductDir() . '/split/default_sample.pdf'); $splitParams = new SplitParameters($this->splitModelId); diff --git a/tests/V2/Input/InferenceParameterTest.php b/tests/V2/Input/InferenceParameterTest.php index c449e46e..4d623d5d 100644 --- a/tests/V2/Input/InferenceParameterTest.php +++ b/tests/V2/Input/InferenceParameterTest.php @@ -3,8 +3,8 @@ namespace V2\Input; -use Mindee\Input\DataSchema; -use Mindee\Input\InferenceParameters; +use Mindee\V2\Product\Extraction\Params\DataSchema; +use Mindee\V2\Product\Extraction\Params\InferenceParameters; use PHPUnit\Framework\TestCase; class InferenceParameterTest extends TestCase diff --git a/tests/V2/Input/LocalResponseV2Test.php b/tests/V2/Input/LocalResponseV2Test.php index 0b1b761e..46026a58 100644 --- a/tests/V2/Input/LocalResponseV2Test.php +++ b/tests/V2/Input/LocalResponseV2Test.php @@ -3,7 +3,7 @@ namespace V2\Input; use Mindee\Input\LocalResponse; -use Mindee\Parsing\V2\InferenceResponse; +use Mindee\V2\Parsing\Inference\InferenceResponse; use PHPUnit\Framework\TestCase; class LocalResponseV2Test extends TestCase diff --git a/tests/V2/Parsing/InferenceResponseTest.php b/tests/V2/Parsing/InferenceResponseTest.php index 89b9b1c6..caca52de 100644 --- a/tests/V2/Parsing/InferenceResponseTest.php +++ b/tests/V2/Parsing/InferenceResponseTest.php @@ -2,16 +2,16 @@ namespace V2\Parsing; -use Mindee\Error\ErrorItem; use Mindee\Geometry\Point; use Mindee\Input\LocalResponse; -use Mindee\Parsing\V2\ErrorResponse; -use Mindee\Parsing\V2\Field\FieldConfidence; -use Mindee\Parsing\V2\Field\ListField; -use Mindee\Parsing\V2\Field\ObjectField; -use Mindee\Parsing\V2\Field\SimpleField; -use Mindee\Parsing\V2\InferenceResponse; -use Mindee\Parsing\V2\JobResponse; +use Mindee\V2\Parsing\ErrorItem; +use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\Inference\Field\FieldConfidence; +use Mindee\V2\Parsing\Inference\Field\ListField; +use Mindee\V2\Parsing\Inference\Field\ObjectField; +use Mindee\V2\Parsing\Inference\Field\SimpleField; +use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Parsing\JobResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/V2/Parsing/JobResponseTest.php b/tests/V2/Parsing/JobResponseTest.php index 0a09d4d5..6a805208 100644 --- a/tests/V2/Parsing/JobResponseTest.php +++ b/tests/V2/Parsing/JobResponseTest.php @@ -3,9 +3,9 @@ namespace V2\Parsing; use DateTime; -use Mindee\Error\ErrorItem; -use Mindee\Parsing\V2\ErrorResponse; -use Mindee\Parsing\V2\JobResponse; +use Mindee\V2\Parsing\ErrorItem; +use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\JobResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/V2/Product/ClassificationFunctional.php b/tests/V2/Product/ClassificationFunctional.php index 5d91bce7..3227212d 100644 --- a/tests/V2/Product/ClassificationFunctional.php +++ b/tests/V2/Product/ClassificationFunctional.php @@ -3,8 +3,8 @@ namespace V2\Product; -use Mindee\ClientV2; use Mindee\Input\PathInput; +use Mindee\V2\Client; use Mindee\V2\Product\Classification\ClassificationResponse; use Mindee\V2\Product\Classification\Params\ClassificationParameters; use PHPUnit\Framework\TestCase; @@ -14,13 +14,13 @@ class ClassificationFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $classificationModelId; protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY'); - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->classificationModelId = getenv('MINDEE_V2_CLASSIFICATION_MODEL_ID') ?: ''; } diff --git a/tests/V2/Product/CropFunctional.php b/tests/V2/Product/CropFunctional.php index d509cb37..9ba83619 100644 --- a/tests/V2/Product/CropFunctional.php +++ b/tests/V2/Product/CropFunctional.php @@ -2,8 +2,8 @@ namespace V2\Product; -use Mindee\ClientV2; use Mindee\Input\PathInput; +use Mindee\V2\Client; use Mindee\V2\Product\Crop\CropResponse; use Mindee\V2\Product\Crop\Params\CropParameters; use PHPUnit\Framework\TestCase; @@ -13,14 +13,14 @@ class CropFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $cropModelId; private string $cropExtractionModelId; protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY'); - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->cropModelId = getenv('MINDEE_V2_CROP_MODEL_ID') ?: ''; $this->cropExtractionModelId = getenv('MINDEE_V2_SE_TESTS_CROP_EXTRACTION_MODEL_ID') ?: ''; diff --git a/tests/V2/Product/OcrFunctional.php b/tests/V2/Product/OcrFunctional.php index 70d1eb1d..b65af80f 100644 --- a/tests/V2/Product/OcrFunctional.php +++ b/tests/V2/Product/OcrFunctional.php @@ -2,8 +2,8 @@ namespace V2\Product; -use Mindee\ClientV2; use Mindee\Input\PathInput; +use Mindee\V2\Client; use Mindee\V2\Product\Ocr\OcrResponse; use Mindee\V2\Product\Ocr\Params\OcrParameters; use PHPUnit\Framework\TestCase; @@ -13,13 +13,13 @@ class OcrFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $ocrModelId; protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY'); - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->ocrModelId = getenv('MINDEE_V2_OCR_MODEL_ID') ?: ''; } diff --git a/tests/V2/Product/SplitFunctional.php b/tests/V2/Product/SplitFunctional.php index 92d2cbc8..aa89b158 100644 --- a/tests/V2/Product/SplitFunctional.php +++ b/tests/V2/Product/SplitFunctional.php @@ -2,8 +2,8 @@ namespace V2\Product; -use Mindee\ClientV2; use Mindee\Input\PathInput; +use Mindee\V2\Client; use Mindee\V2\Product\Split\Params\SplitParameters; use Mindee\V2\Product\Split\SplitResponse; use PHPUnit\Framework\TestCase; @@ -13,13 +13,13 @@ class SplitFunctional extends TestCase { - private ClientV2 $client; + private Client $client; private string $splitModelId; protected function setUp(): void { $apiKey = getenv('MINDEE_V2_API_KEY'); - $this->client = new ClientV2($apiKey); + $this->client = new Client($apiKey); $this->splitModelId = getenv('MINDEE_V2_SPLIT_MODEL_ID') ?: ''; } From d980a46ca91ad6cc25d4384912e2fee7ce2f2cef Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Tue, 12 May 2026 12:09:05 +0200 Subject: [PATCH 02/11] :recycle: :boom: fully remove v2 Inference in favor of Extraction (#186) --- docs/code_samples/v2_extraction_polling.txt | 8 +-- docs/code_samples/v2_extraction_webhook.txt | 4 +- src/V1/Parsing/Common/ApiResponse.php | 2 +- .../Parsing/Common/AsyncPredictResponse.php | 4 +- src/V1/Parsing/Common/Document.php | 14 ++--- src/V1/Parsing/Common/Inference.php | 6 +-- src/V1/Parsing/Common/OCR/OCR.php | 2 +- src/V1/Parsing/Standard/PositionField.php | 14 ++--- src/V2/Client.php | 51 +++++-------------- src/V2/ClientOptions/BaseParameters.php | 20 ++------ src/V2/HTTP/MindeeAPIV2.php | 21 ++------ .../ClassificationClassifier.php | 8 +-- .../Params/ClassificationParameters.php | 12 ++--- src/V2/Product/Crop/CropItem.php | 8 +-- src/V2/Product/Crop/Params/CropParameters.php | 12 ++--- .../Extraction/ExtractionInference.php} | 13 ++--- .../Extraction/ExtractionResponse.php} | 12 +++-- .../Extraction/ExtractionResult.php} | 6 ++- ...arameters.php => ExtractionParameters.php} | 25 ++++----- src/V2/Product/Ocr/Params/OcrParameters.php | 12 ++--- .../Product/Split/Params/SplitParameters.php | 12 ++--- src/V2/Product/Split/SplitRange.php | 8 +-- tests/Input/LocalInputSourceTest.php | 5 -- tests/V1/CLI/MindeeCLICommandTest.php | 2 - tests/V1/Input/LocalResponseV1Test.php | 4 +- .../Common/Extras/FullTextOcrExtraTest.php | 23 +-------- tests/V2/ClientV2Test.php | 29 ++++++----- tests/V2/ClientV2TestFunctional.php | 29 ++++++----- tests/V2/FileOperations/CropFunctional.php | 10 ++-- tests/V2/FileOperations/SplitFunctional.php | 10 ++-- tests/V2/Input/InferenceParameterTest.php | 10 ++-- tests/V2/Input/LocalResponseV2Test.php | 6 +-- ...nseTest.php => ExtractionResponseTest.php} | 10 ++-- tests/V2/Product/CropTest.php | 5 -- tests/V2/Product/OcrTest.php | 1 - 35 files changed, 166 insertions(+), 252 deletions(-) rename src/V2/{Parsing/Inference/Inference.php => Product/Extraction/ExtractionInference.php} (71%) rename src/V2/{Parsing/Inference/InferenceResponse.php => Product/Extraction/ExtractionResponse.php} (54%) rename src/V2/{Parsing/Inference/InferenceResult.php => Product/Extraction/ExtractionResult.php} (88%) rename src/V2/Product/Extraction/Params/{InferenceParameters.php => ExtractionParameters.php} (70%) rename tests/V2/Parsing/{InferenceResponseTest.php => ExtractionResponseTest.php} (98%) diff --git a/docs/code_samples/v2_extraction_polling.txt b/docs/code_samples/v2_extraction_polling.txt index bdb7fecf..c4696e52 100644 --- a/docs/code_samples/v2_extraction_polling.txt +++ b/docs/code_samples/v2_extraction_polling.txt @@ -1,9 +1,9 @@ enqueueAndGetResult( - InferenceResponse::class, + ExtractionResponse::class, $inputSource, $inferenceParams ); diff --git a/docs/code_samples/v2_extraction_webhook.txt b/docs/code_samples/v2_extraction_webhook.txt index 51213116..63fe599e 100644 --- a/docs/code_samples/v2_extraction_webhook.txt +++ b/docs/code_samples/v2_extraction_webhook.txt @@ -1,7 +1,7 @@ nPages = $rawResponse['n_pages']; $this->filename = $rawResponse['name']; try { - $reflection = new \ReflectionClass($predictionType); + $reflection = new ReflectionClass($predictionType); $this->inference = $reflection->newInstance($rawResponse['inference']); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new MindeeApiException( "Unable to create custom product " . $predictionType, ErrorCode::INTERNAL_LIBRARY_ERROR, diff --git a/src/V1/Parsing/Common/Inference.php b/src/V1/Parsing/Common/Inference.php index ba8fcb5e..7b618946 100644 --- a/src/V1/Parsing/Common/Inference.php +++ b/src/V1/Parsing/Common/Inference.php @@ -10,7 +10,7 @@ abstract class Inference { /** - * @var \Mindee\V1\Parsing\Common\Product Name and version of a given product, as sent back by the API. + * @var Product Name and version of a given product, as sent back by the API. */ public Product $product; /** @@ -22,7 +22,7 @@ abstract class Inference */ public static string $endpointVersion; /** - * @var \Mindee\V1\Parsing\Common\Prediction A document's top-level Prediction. + * @var Prediction A document's top-level Prediction. */ public Prediction $prediction; /** @@ -38,7 +38,7 @@ abstract class Inference */ public ?int $pageId; /** - * @var \Mindee\V1\Parsing\Common\Extras\Extras|null Potential Extras fields sent back along with the prediction. + * @var Extras|null Potential Extras fields sent back along with the prediction. */ public ?Extras $extras; diff --git a/src/V1/Parsing/Common/OCR/OCR.php b/src/V1/Parsing/Common/OCR/OCR.php index 1b2648ba..9b610afb 100644 --- a/src/V1/Parsing/Common/OCR/OCR.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -8,7 +8,7 @@ class OCR { /** - * @var \Mindee\V1\Parsing\Common\OCR\MVisionV1 Mindee Vision v1 results. + * @var MVisionV1 Mindee Vision v1 results. */ public MVisionV1 $mvisionV1; diff --git a/src/V1/Parsing/Standard/PositionField.php b/src/V1/Parsing/Standard/PositionField.php index a85a5913..aa8f6d9d 100644 --- a/src/V1/Parsing/Standard/PositionField.php +++ b/src/V1/Parsing/Standard/PositionField.php @@ -11,23 +11,23 @@ class PositionField extends BaseField { /** - * @var \Mindee\Geometry\Polygon|null Polygon of cropped area, identical to the `polygon` property. + * @var Polygon|null Polygon of cropped area, identical to the `polygon` property. */ public $value; /** - * @var \Mindee\Geometry\Polygon|null Polygon of cropped area. + * @var Polygon|null Polygon of cropped area. */ public ?Polygon $polygon; /** - * @var \Mindee\Geometry\Polygon|null Quadrangle of cropped area (does not exceed the canvas). + * @var Polygon|null Quadrangle of cropped area (does not exceed the canvas). */ public ?Polygon $quadrangle; /** - * @var \Mindee\Geometry\Polygon|null Oriented rectangle of cropped area (may exceed the canvas). + * @var Polygon|null Oriented rectangle of cropped area (may exceed the canvas). */ public ?Polygon $rectangle; /** - * @var \Mindee\Geometry\Polygon|null Straight rectangle of cropped area (does not exceed the canvas). + * @var Polygon|null Straight rectangle of cropped area (does not exceed the canvas). */ public ?Polygon $boundingBox; @@ -36,7 +36,7 @@ class PositionField extends BaseField * * @param array $rawPrediction Raw prediction array. * @param string $key Key to use for the value. - * @return \Mindee\Geometry\Polygon|null + * @return Polygon|null */ private static function getQuadrilateral(array $rawPrediction, string $key): ?Polygon { @@ -52,7 +52,7 @@ private static function getQuadrilateral(array $rawPrediction, string $key): ?Po * * @param array $rawPrediction Raw prediction array. * @param string $key Key to use for the value. - * @return \Mindee\Geometry\Polygon|null + * @return Polygon|null */ private static function getPolygon(array $rawPrediction, string $key): ?Polygon { diff --git a/src/V2/Client.php b/src/V2/Client.php index 857e3470..a6b828e0 100644 --- a/src/V2/Client.php +++ b/src/V2/Client.php @@ -2,15 +2,15 @@ namespace Mindee\V2; +use Mindee\ClientOptions\PollingOptions; use Mindee\CustomSleepMixin; use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\V2\ClientOptions\BaseParameters; use Mindee\V2\HTTP\MindeeAPIV2; use Mindee\V2\Parsing\Inference\BaseResponse; -use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Parsing\JobResponse; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; /** * Mindee Client V2. @@ -37,15 +37,15 @@ public function __construct(?string $apiKey = null) /** * Send the document to an asynchronous endpoint and return its ID in the queue. * - * @param InputSource $inputSource File to parse. - * @param InferenceParameters $params Parameters relating to prediction options. + * @param InputSource $inputSource File to parse. + * @param ExtractionParameters $params Parameters relating to prediction options. * @return JobResponse A JobResponse containing the job (queue) corresponding to a document. * @throws MindeeException Throws if the input document is not provided. * @category Asynchronous */ public function enqueueInference( InputSource $inputSource, - InferenceParameters $params + ExtractionParameters $params ): JobResponse { return $this->enqueue($inputSource, $params); } @@ -65,17 +65,6 @@ public function enqueue( return $this->mindeeApi->reqPostEnqueue($inputSource, $params); } - /** - * Retrieves an inference. - * - * @param string $inferenceId ID of the queue to poll. - * @return InferenceResponse An InferenceResponse containing a Job. - * @category Asynchronous - */ - public function getInference(string $inferenceId): InferenceResponse - { - return $this->mindeeApi->reqGetInference($inferenceId); - } /** * @template T of BaseResponse @@ -118,40 +107,28 @@ public function getJob(string $jobId): JobResponse return $this->mindeeApi->reqGetJob($jobId); } - /** - * Send a document to an endpoint and poll the server until the result is sent or - * until the maximum number of tries is reached. - * - * @param InputSource $inputDoc Input document to parse. - * @param InferenceParameters $params Parameters relating to prediction options. - * @return InferenceResponse A response containing parsing results. - * @throws MindeeException Throws if enqueueing fails, job fails, or times out. - */ - public function enqueueAndGetInference( - InputSource $inputDoc, - InferenceParameters $params - ): InferenceResponse { - return $this->enqueueAndGetResult(InferenceResponse::class, $inputDoc, $params); - } - /** * Send a document to an endpoint and poll the server until the result is sent or * until the maximum number of tries is reached. * * @template T of BaseResponse - * @param string $responseClass The response class to construct. + * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param InputSource $inputDoc Input document to parse. - * @param BaseParameters $params Parameters relating to prediction options. + * @param InputSource $inputDoc Input document to parse. + * @param BaseParameters $params Parameters relating to prediction options. + * @param PollingOptions|null $pollingOptions Options to apply to the polling. * @return BaseResponse A response containing parsing results. * @throws MindeeException Throws if enqueueing fails, job fails, or times out. */ public function enqueueAndGetResult( string $responseClass, InputSource $inputDoc, - BaseParameters $params + BaseParameters $params, + ?PollingOptions $pollingOptions = null ): BaseResponse { - $pollingOptions = $params->pollingOptions; + if (!$pollingOptions) { + $pollingOptions = new PollingOptions(); + } $enqueueResponse = $this->enqueue($inputDoc, $params); diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index 03cbd36b..f175d564 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -2,8 +2,6 @@ namespace Mindee\V2\ClientOptions; -use Mindee\ClientOptions\PollingOptions; - /** * Base parameters for running an inference. */ @@ -25,17 +23,11 @@ abstract class BaseParameters public array $webhooksIds; /** - * @var PollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. */ - public PollingOptions $pollingOptions; - - /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. - */ - public function __construct(string $modelId, ?string $alias, ?array $webhooksIds, ?PollingOptions $pollingOptions) + public function __construct(string $modelId, ?string $alias, ?array $webhooksIds) { $this->modelId = $modelId; @@ -47,10 +39,6 @@ public function __construct(string $modelId, ?string $alias, ?array $webhooksIds } else { $this->webhooksIds = []; } - if (!$pollingOptions) { - $pollingOptions = new PollingOptions(); - } - $this->pollingOptions = $pollingOptions; } /** diff --git a/src/V2/HTTP/MindeeAPIV2.php b/src/V2/HTTP/MindeeAPIV2.php index 90aa7cd5..0a68fb24 100644 --- a/src/V2/HTTP/MindeeAPIV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -19,12 +19,13 @@ use Mindee\V2\ClientOptions\BaseParameters; use Mindee\V2\Parsing\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; -use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; +use const Mindee\V1\HTTP\API_KEY_ENV_NAME; use const Mindee\VERSION; // phpcs:disable @@ -230,22 +231,6 @@ private function processJobResponse(array $result): JobResponse } } - /** - * Requests the job of a queued document from the API. - * Throws an error if the server's response contains one. - * @param string $inferenceId ID of the inference. - * @return InferenceResponse - * @throws MindeeException Throws if the server's response contains an error. - * @throws MindeeException Throws if the inference ID is not provided. - */ - public function reqGetInference(string $inferenceId): InferenceResponse - { - if (!isset($inferenceId)) { - throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } - return $this->reqGetResult(InferenceResponse::class, $inferenceId); - } - /** * Requests the job of a queued document from the API. * Throws an error if the server's response contains one. @@ -360,7 +345,7 @@ private function sendGetRequest(string $url): array * Starts a CURL session using POST. * * @param InputSource $inputSource File to upload. - * @param BaseParameters $params Inference parameters. + * @param BaseParameters $params Parameters. * @return array * @throws MindeeException Throws if the cURL operation doesn't go succeed. */ diff --git a/src/V2/Product/Classification/ClassificationClassifier.php b/src/V2/Product/Classification/ClassificationClassifier.php index c5570cd8..4adecf7d 100644 --- a/src/V2/Product/Classification/ClassificationClassifier.php +++ b/src/V2/Product/Classification/ClassificationClassifier.php @@ -2,7 +2,7 @@ namespace Mindee\V2\Product\Classification; -use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; /** * Classification of document type from the source file. @@ -15,9 +15,9 @@ class ClassificationClassifier public string $documentType; /** - * @var InferenceResponse|null $extractionResponse The extraction response associated with the classification. + * @var ExtractionResponse|null $extractionResponse The extraction response associated with the classification. */ - public ?InferenceResponse $extractionResponse; + public ?ExtractionResponse $extractionResponse; /** * @param array $rawPrediction Raw prediction array. @@ -26,7 +26,7 @@ public function __construct(array $rawPrediction) { $this->documentType = $rawPrediction['document_type']; $this->extractionResponse = isset($rawPrediction['extraction_response']) ? - new InferenceResponse($rawPrediction['extraction_response']) : null; + new ExtractionResponse($rawPrediction['extraction_response']) : null; } /** diff --git a/src/V2/Product/Classification/Params/ClassificationParameters.php b/src/V2/Product/Classification/Params/ClassificationParameters.php index 56f0702d..3d22d2cb 100644 --- a/src/V2/Product/Classification/Params/ClassificationParameters.php +++ b/src/V2/Product/Classification/Params/ClassificationParameters.php @@ -16,17 +16,15 @@ class ClassificationParameters extends BaseParameters public static string $slug = "classification"; /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Crop/CropItem.php b/src/V2/Product/Crop/CropItem.php index 826d0d4f..4cb78886 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -3,7 +3,7 @@ namespace Mindee\V2\Product\Crop; use Mindee\V2\Parsing\Inference\Field\FieldLocation; -use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; /** * Result of a cropped document region. @@ -21,9 +21,9 @@ class CropItem public string $objectType; /** - * @var InferenceResponse|null $extractionResponse The extraction response associated with the crop. + * @var ExtractionResponse|null $extractionResponse The extraction response associated with the crop. */ - public ?InferenceResponse $extractionResponse; + public ?ExtractionResponse $extractionResponse; /** * @param array $rawResponse Raw server response array. */ @@ -32,7 +32,7 @@ public function __construct(array $rawResponse) $this->location = new FieldLocation($rawResponse['location']); $this->objectType = $rawResponse['object_type']; $this->extractionResponse = isset($rawResponse['extraction_response']) ? - new InferenceResponse($rawResponse['extraction_response']) : null; + new ExtractionResponse($rawResponse['extraction_response']) : null; } /** diff --git a/src/V2/Product/Crop/Params/CropParameters.php b/src/V2/Product/Crop/Params/CropParameters.php index 7b7f6758..077836e1 100644 --- a/src/V2/Product/Crop/Params/CropParameters.php +++ b/src/V2/Product/Crop/Params/CropParameters.php @@ -16,17 +16,15 @@ class CropParameters extends BaseParameters public static string $slug = "crop"; /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Parsing/Inference/Inference.php b/src/V2/Product/Extraction/ExtractionInference.php similarity index 71% rename from src/V2/Parsing/Inference/Inference.php rename to src/V2/Product/Extraction/ExtractionInference.php index 2bcbf0e8..b46f7587 100644 --- a/src/V2/Parsing/Inference/Inference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -1,14 +1,15 @@ activeOptions = new InferenceActiveOptions($rawResponse['active_options']); - $this->result = new InferenceResult($rawResponse['result']); + $this->result = new ExtractionResult($rawResponse['result']); } /** diff --git a/src/V2/Parsing/Inference/InferenceResponse.php b/src/V2/Product/Extraction/ExtractionResponse.php similarity index 54% rename from src/V2/Parsing/Inference/InferenceResponse.php rename to src/V2/Product/Extraction/ExtractionResponse.php index f7651a5a..c6cfd4a2 100644 --- a/src/V2/Parsing/Inference/InferenceResponse.php +++ b/src/V2/Product/Extraction/ExtractionResponse.php @@ -1,16 +1,18 @@ inference = new Inference($rawResponse['inference']); + $this->inference = new ExtractionInference($rawResponse['inference']); } } diff --git a/src/V2/Parsing/Inference/InferenceResult.php b/src/V2/Product/Extraction/ExtractionResult.php similarity index 88% rename from src/V2/Parsing/Inference/InferenceResult.php rename to src/V2/Product/Extraction/ExtractionResult.php index 83ca9395..4f8394cd 100644 --- a/src/V2/Parsing/Inference/InferenceResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -1,13 +1,15 @@ |null $webhooksIds List of webhook IDs. - * @param string|null $textContext Additional text context used by the model during + * @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 + * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during * inference. - * @param PollingOptions|null $pollingOptions Polling options. */ public function __construct( string $modelId, @@ -74,9 +72,8 @@ public function __construct( ?array $webhooksIds = null, ?string $textContext = null, DataSchema|string|array|null $dataSchema = null, - ?PollingOptions $pollingOptions = null, ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); $this->rag = $rag; $this->rawText = $rawText; diff --git a/src/V2/Product/Ocr/Params/OcrParameters.php b/src/V2/Product/Ocr/Params/OcrParameters.php index 436920a1..c22cca44 100644 --- a/src/V2/Product/Ocr/Params/OcrParameters.php +++ b/src/V2/Product/Ocr/Params/OcrParameters.php @@ -16,17 +16,15 @@ class OcrParameters extends BaseParameters public static string $slug = "ocr"; /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Split/Params/SplitParameters.php b/src/V2/Product/Split/Params/SplitParameters.php index d0be10d8..9571b7cc 100644 --- a/src/V2/Product/Split/Params/SplitParameters.php +++ b/src/V2/Product/Split/Params/SplitParameters.php @@ -16,17 +16,15 @@ class SplitParameters extends BaseParameters public static string $slug = "split"; /** - * @param string $modelId ID of the model. - * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. - * @param PollingOptions|null $pollingOptions Polling options. + * @param string $modelId ID of the model. + * @param string|null $alias Optional file alias. + * @param array|null $webhooksIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null, - ?PollingOptions $pollingOptions = null + ?array $webhooksIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds, $pollingOptions); + parent::__construct($modelId, $alias, $webhooksIds); } } diff --git a/src/V2/Product/Split/SplitRange.php b/src/V2/Product/Split/SplitRange.php index 8b212ff8..4a1b5abf 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -2,7 +2,7 @@ namespace Mindee\V2\Product\Split; -use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; /** * A single document as identified when splitting a multi-document source file. @@ -21,9 +21,9 @@ class SplitRange public string $documentType; /** - * @var InferenceResponse|null $extractionResponse The extraction response associated with the split. + * @var ExtractionResponse|null $extractionResponse The extraction response associated with the split. */ - public ?InferenceResponse $extractionResponse; + public ?ExtractionResponse $extractionResponse; /** @@ -34,7 +34,7 @@ public function __construct(array $rawResponse) $this->pageRange = $rawResponse['page_range']; $this->documentType = $rawResponse['document_type']; $this->extractionResponse = isset($rawResponse['extraction_response']) ? - new InferenceResponse($rawResponse['extraction_response']) : null; + new ExtractionResponse($rawResponse['extraction_response']) : null; } /** diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index c2648307..413e4ad0 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -113,9 +113,6 @@ public function testPDFCutNPages(array $indexes) $cutPdf->useTemplate($cutPdf->importPage($pageNumber + 1)); $basePdf->AddPage(); $basePdf->useTemplate($basePdf->importPage($pageNumber + 1)); - // TODO: comparing extracted page bytes content turns out to be unreliable when using FPDF. - // This will be left here until a better solution is found within the limitations of licensing. - // $this->assertEquals($cutPdf->Output('', 'S'), $basePdf->Output('', 'S')); } $basePdf->Close(); $cutPdf->Close(); @@ -370,8 +367,6 @@ public function testSourceTextPDFCompression() $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $sizeTextCompressed = filesize(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"); $this->assertEquals($sizeTextCompressed, $sizeOriginal); - // Note: Greater size when compressed is expected due to original not having any images, so the operation will - // be aborted. $this->assertEquals( str_repeat('*', 650), diff --git a/tests/V1/CLI/MindeeCLICommandTest.php b/tests/V1/CLI/MindeeCLICommandTest.php index fd222f94..27bac04e 100644 --- a/tests/V1/CLI/MindeeCLICommandTest.php +++ b/tests/V1/CLI/MindeeCLICommandTest.php @@ -20,8 +20,6 @@ protected function setUp(): void public function testInvalidFilePath() { $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); - // Note : a direct comparison here would be too complicated due to the fact that the output of the command has - // formatting applied by Symfony CLI. $this->assertEquals(1, $cmdOutput["code"]); $this->assertTrue(str_contains($cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); } diff --git a/tests/V1/Input/LocalResponseV1Test.php b/tests/V1/Input/LocalResponseV1Test.php index a0abae30..faaea2b3 100644 --- a/tests/V1/Input/LocalResponseV1Test.php +++ b/tests/V1/Input/LocalResponseV1Test.php @@ -74,12 +74,10 @@ public function testValidStringLocalResponse() public function testValidStreamLocalResponse() { - // Create a stream from the file content $stream = fopen('php://memory', 'r+'); fwrite($stream, file_get_contents($this->filePath)); rewind($stream); - // Create LocalResponse instance with the stream $localResponse = new LocalResponse($stream); $this->assertNotNull($localResponse->toArray(), 'Local response file should not be null'); @@ -102,7 +100,7 @@ public function testValidStreamLocalResponse() 'Valid signature should be valid' ); - fclose($stream); // Close the stream after use + fclose($stream); } public function testValidFilePathLocalResponse() diff --git a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php index efeeece1..124daa7e 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php @@ -7,7 +7,7 @@ class FullTextOCRTest extends TestCase { - private $extrasDir; // Adjust this path as needed + private $extrasDir; protected function setUp(): void { @@ -31,25 +31,4 @@ public function testGetsFullTextOCRResult() $this->assertEquals(trim($expectedText), trim(strval($fullTextOcr))); } - - // NOTE: disabled due to the current system used to manage pages of some APIs. - /* - private function loadPages() - { - $dummyClient = new \Mindee\Client("dummy-key"); - $localResponse = new \Mindee\Input\LocalResponse($this->extrasDir . '/full_text_ocr/complete.json'); - $response = $dummyClient->loadPrediction(InternationalIdV2::class, $localResponse); - return $response->document->inference->pages; - } - - public function testGetsFullTextOCRResultForPage() - { - $expectedText = file_get_contents($this->extrasDir . '/full_text_ocr/full_text_ocr.txt'); - - $pages = $this->loadPages(); - $page0Ocr = $pages[0]->extras->fullTextOcr->content; - - $this->assertEquals(implode("\n", explode("\n", $expectedText)), $page0Ocr); - } - */ } diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 91360e5e..985f4430 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -8,9 +8,9 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; use Mindee\V2\HTTP\MindeeAPIV2; -use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Parsing\JobResponse; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\ExtractionResponse; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -34,14 +34,14 @@ public function testEnqueuePostAsync(): void ->method('reqPostEnqueue') ->with( $this->isInstanceOf(LocalInputSource::class), - $this->isInstanceOf(InferenceParameters::class) + $this->isInstanceOf(ExtractionParameters::class) ) ->willReturn(new JobResponse(json_decode($syntheticResponse, true))); $mindeeClient = self::makeClientWithMockedApi($predictable); $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $params = new InferenceParameters('dummy-model-id', textContext: 'dummy text context'); + $params = new ExtractionParameters('dummy-model-id', textContext: 'dummy text context'); $response = $mindeeClient->enqueueInference($input, $params); @@ -79,16 +79,19 @@ public function testDocumentGetInferenceAsync(): void $this->assertFileExists($jsonFile, 'Test resource file must exist'); $json = json_decode(file_get_contents($jsonFile), true); - $processing = new InferenceResponse($json); + $processing = new ExtractionResponse($json); $predictable->expects($this->once()) - ->method('reqGetInference') - ->with($this->equalTo('12345678-1234-1234-1234-123456789abc')) + ->method('reqGetResult') + ->with( + $this->equalTo(ExtractionResponse::class), + $this->equalTo('12345678-1234-1234-1234-123456789abc') + ) ->willReturn($processing); $mindeeClient = self::makeClientWithMockedApi($predictable); - $response = $mindeeClient->getInference('12345678-1234-1234-1234-123456789abc'); + $response = $mindeeClient->getResult(ExtractionResponse::class, '12345678-1234-1234-1234-123456789abc'); $this->assertNotNull($response, 'must have a response'); $this->assertNotNull($response->inference, 'inference must have a response'); @@ -114,10 +117,10 @@ public function testInferenceLoadsLocally(): void $this->assertFileExists($jsonFile, 'Test resource file must exist'); $localResponse = new LocalResponse($jsonFile); - $loaded = $localResponse->deserializeResponse(InferenceResponse::class); + $loaded = $localResponse->deserializeResponse(ExtractionResponse::class); - $this->assertNotNull($loaded, 'Loaded InferenceResponse must not be null'); - $this->assertInstanceOf(InferenceResponse::class, $loaded); + $this->assertNotNull($loaded, 'Loaded ExtractionResponse must not be null'); + $this->assertInstanceOf(ExtractionResponse::class, $loaded); $modelId = $loaded->inference->model->id ?? null; $this->assertEquals( @@ -143,8 +146,8 @@ public function testInvalidBaseUrlRaisesMindeeException(): void try { $client = new Client('dummy-key'); $input = new PathInput(\TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $params = new InferenceParameters('dummy-model-id'); - $client->enqueueAndGetInference($input, $params); + $params = new ExtractionParameters('dummy-model-id'); + $client->enqueueAndGetResult(ExtractionResponse::class, $input, $params); } finally { if ($original === null) { putenv('MINDEE_V2_BASE_URL'); diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index de2d0fa9..e0a0d7e7 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -6,7 +6,8 @@ use Mindee\Input\PathInput; use Mindee\Input\URLInputSource; use Mindee\V2\Client; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\ExtractionResponse; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\TestCase; use TestingUtilities; @@ -26,9 +27,9 @@ protected function setUp(): void public function testParseFileEmptyMultiPageMustSucceed(): void { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters($this->modelId, rag: false, rawText: true); + $inferenceParams = new ExtractionParameters($this->modelId, rag: false, rawText: true); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); $this->assertNotNull($response); $inference = $response->inference; $this->assertNotNull($inference); @@ -64,9 +65,9 @@ public function testParseFileFilledSinglePageMustSucceed(): void TestingUtilities::getV1DataDir() . '/products/financial_document/default_sample.jpg' ); - $inferenceParams = new InferenceParameters($this->modelId, rag: false, textContext: 'this is an invoice'); + $inferenceParams = new ExtractionParameters($this->modelId, rag: false, textContext: 'this is an invoice'); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); $this->assertNotNull($response); $inference = $response->inference; $this->assertNotNull($inference); @@ -97,7 +98,7 @@ public function testInvalidUUIDMustThrowError(): void $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); - $inferenceParams = new InferenceParameters('INVALID MODEL ID'); + $inferenceParams = new ExtractionParameters('INVALID MODEL ID'); try { $this->mindeeClient->enqueueInference($source, $inferenceParams); @@ -112,7 +113,7 @@ public function testUnknownModelMustThrowError(): void { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters('fc405e37-4ba4-4d03-aeba-533a8d1f0f21', textContext: 'this is invalid'); + $inferenceParams = new ExtractionParameters('fc405e37-4ba4-4d03-aeba-533a8d1f0f21', textContext: 'this is invalid'); try { $this->mindeeClient->enqueueInference($source, $inferenceParams); @@ -127,7 +128,7 @@ public function testUnknownModelMustThrowError(): void public function testInvalidJobMustThrowError(): void { try { - $this->mindeeClient->getInference('fc405e37-4ba4-4d03-aeba-533a8d1f0f21'); + $this->mindeeClient->getResult(ExtractionResponse::class, 'fc405e37-4ba4-4d03-aeba-533a8d1f0f21'); } catch (MindeeV2HttpException $e) { $this->assertStringStartsWith('404-', $e->errorCode); $this->assertNotEmpty($e->title); @@ -139,7 +140,7 @@ public function testInvalidWebhookIDsMustThrowError() { $source = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage_cut-2.pdf'); - $inferenceParams = new InferenceParameters( + $inferenceParams = new ExtractionParameters( $this->modelId, null, null, @@ -163,9 +164,9 @@ public function testUrlInputSourceMustNotRaiseErrors(): void { $urlSource = new URLInputSource(getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')); - $inferenceParams = new InferenceParameters($this->modelId); + $inferenceParams = new ExtractionParameters($this->modelId); - $response = $this->mindeeClient->enqueueAndGetInference($urlSource, $inferenceParams); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $urlSource, $inferenceParams); $this->assertNotNull($response); $inference = $response->inference; $this->assertNotNull($inference); @@ -187,9 +188,9 @@ public function testDataSchemaMustSucceed(): void TestingUtilities::getV2DataDir() . '/products/extraction/data_schema_replace_param.json' ); - $inferenceParams = new InferenceParameters($this->modelId, dataSchema: $dataSchemaReplace); + $inferenceParams = new ExtractionParameters($this->modelId, dataSchema: $dataSchemaReplace); - $response = $this->mindeeClient->enqueueAndGetInference($source, $inferenceParams); + $response = $this->mindeeClient->enqueueAndGetResult(ExtractionResponse::class, $source, $inferenceParams); $this->assertNotNull($response); $inference = $response->inference; $this->assertNotNull($inference); @@ -222,7 +223,7 @@ public function testMultipleWebhooksMustSucceed(): void TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf' ); - $inferenceParams = new InferenceParameters($this->modelId, webhooksIds: [ + $inferenceParams = new ExtractionParameters($this->modelId, webhooksIds: [ getenv('MINDEE_V2_FAILURE_WEBHOOK_ID'), getenv('MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID')] ); diff --git a/tests/V2/FileOperations/CropFunctional.php b/tests/V2/FileOperations/CropFunctional.php index cc1ea6c6..6526ff1a 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -5,10 +5,10 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; use Mindee\V2\FileOperations\Crop; -use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Product\Crop\CropResponse; use Mindee\V2\Product\Crop\Params\CropParameters; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\ExtractionResponse; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\TestCase; class CropFunctional extends TestCase @@ -44,7 +44,7 @@ protected function tearDown(): void } } - private function checkFindocReturn(InferenceResponse $findocResponse): void + private function checkFindocReturn(ExtractionResponse $findocResponse): void { $this->assertGreaterThan(0, strlen($findocResponse->inference->model->id)); @@ -71,9 +71,9 @@ public function testExtractCropsFromImageCorrectly(): void $this->assertEquals('default_sample.jpg_page0-1.jpg', $extractedImages[1]->filename); $extractionInput = $extractedImages[0]->asInputSource(); - $findocParams = new InferenceParameters($this->findocModelId); + $findocParams = new ExtractionParameters($this->findocModelId); - $invoice0 = $this->client->enqueueAndGetResult(InferenceResponse::class, $extractionInput, $findocParams); + $invoice0 = $this->client->enqueueAndGetResult(ExtractionResponse::class, $extractionInput, $findocParams); $this->checkFindocReturn($invoice0); diff --git a/tests/V2/FileOperations/SplitFunctional.php b/tests/V2/FileOperations/SplitFunctional.php index 83119fbf..501cbffd 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -5,8 +5,8 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; use Mindee\V2\FileOperations\Split; -use Mindee\V2\Parsing\Inference\InferenceResponse; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\ExtractionResponse; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use Mindee\V2\Product\Split\Params\SplitParameters; use Mindee\V2\Product\Split\SplitResponse; use PHPUnit\Framework\TestCase; @@ -44,7 +44,7 @@ protected function tearDown(): void } } - private function checkFindocReturn(InferenceResponse $findocResponse): void + private function checkFindocReturn(ExtractionResponse $findocResponse): void { $this->assertGreaterThan(0, strlen($findocResponse->inference->model->id)); @@ -73,9 +73,9 @@ public function testExtractSplitsFromPDFCorrectly(): void $this->assertEquals('default_sample_002-002.pdf', $extractedSplits[1]->filename); $inferenceInput = $extractedSplits[0]->asInputSource(); - $findocParams = new InferenceParameters($this->findocModelId); + $findocParams = new ExtractionParameters($this->findocModelId); - $invoice0 = $this->client->enqueueAndGetResult(InferenceResponse::class, $inferenceInput, $findocParams); + $invoice0 = $this->client->enqueueAndGetResult(ExtractionResponse::class, $inferenceInput, $findocParams); $this->checkFindocReturn($invoice0); diff --git a/tests/V2/Input/InferenceParameterTest.php b/tests/V2/Input/InferenceParameterTest.php index 4d623d5d..2e32c100 100644 --- a/tests/V2/Input/InferenceParameterTest.php +++ b/tests/V2/Input/InferenceParameterTest.php @@ -4,7 +4,7 @@ use Mindee\V2\Product\Extraction\Params\DataSchema; -use Mindee\V2\Product\Extraction\Params\InferenceParameters; +use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\TestCase; class InferenceParameterTest extends TestCase @@ -21,14 +21,14 @@ protected function setUp(): void { } public function testDataSchemaShouldntReplaceWhenUnset() { - $params = new InferenceParameters('model_id', dataSchema: null); + $params = new ExtractionParameters('model_id', dataSchema: null); $this->assertFalse(isset($params->dataSchema)); } public function testDataSchemaShouldEquateNoMatterTheType(){ - $paramsDict = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaDict); - $paramsString = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaString); - $paramsObject = new InferenceParameters('model_id', dataSchema: $this->expectedSchemaObject); + $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); diff --git a/tests/V2/Input/LocalResponseV2Test.php b/tests/V2/Input/LocalResponseV2Test.php index 46026a58..5122fefa 100644 --- a/tests/V2/Input/LocalResponseV2Test.php +++ b/tests/V2/Input/LocalResponseV2Test.php @@ -3,7 +3,7 @@ namespace V2\Input; use Mindee\Input\LocalResponse; -use Mindee\V2\Parsing\Inference\InferenceResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; use PHPUnit\Framework\TestCase; class LocalResponseV2Test extends TestCase @@ -26,8 +26,8 @@ protected function assertLocalResponse(LocalResponse $localResponse): void $this->assertFalse($localResponse->isValidHMACSignature($fakeHMACSigning, "fake HMAC signature")); $this->assertEquals($signature, $localResponse->getHmacSignature($fakeHMACSigning)); $this->assertTrue($localResponse->isValidHMACSignature($fakeHMACSigning, $signature)); - $response = $localResponse->deserializeResponse(InferenceResponse::class); - $this->assertInstanceOf(InferenceResponse::class, $response); + $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); diff --git a/tests/V2/Parsing/InferenceResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php similarity index 98% rename from tests/V2/Parsing/InferenceResponseTest.php rename to tests/V2/Parsing/ExtractionResponseTest.php index caca52de..a5d44c10 100644 --- a/tests/V2/Parsing/InferenceResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -10,8 +10,8 @@ use Mindee\V2\Parsing\Inference\Field\ListField; use Mindee\V2\Parsing\Inference\Field\ObjectField; use Mindee\V2\Parsing\Inference\Field\SimpleField; -use Mindee\V2\Parsing\Inference\InferenceResponse; use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Product\Extraction\ExtractionResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; @@ -20,15 +20,15 @@ /** * InferenceV2 – field integrity checks */ -class InferenceResponseTest extends TestCase +class ExtractionResponseTest extends TestCase { - private function loadFromResource(string $resourcePath): InferenceResponse + private function loadFromResource(string $resourcePath): ExtractionResponse { $fullPath = TestingUtilities::getV2ProductDir() . "/$resourcePath"; $this->assertFileExists($fullPath, "Resource file must exist: $resourcePath"); $localResponse = new LocalResponse($fullPath); - return $localResponse->deserializeResponse(InferenceResponse::class); + return $localResponse->deserializeResponse(ExtractionResponse::class); } private function readFileAsString(string $path): string @@ -101,7 +101,7 @@ public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void $inference = $response->inference; $this->assertNotNull($inference, 'Inference must not be null'); - $this->assertEquals('12345678-1234-1234-1234-123456789abc', $inference->id, 'Inference ID mismatch'); + $this->assertEquals('12345678-1234-1234-1234-123456789abc', $inference->id, 'ExtractionInference ID mismatch'); $model = $inference->model; $this->assertNotNull($model, 'Model must not be null'); diff --git a/tests/V2/Product/CropTest.php b/tests/V2/Product/CropTest.php index eee10c35..4d868040 100644 --- a/tests/V2/Product/CropTest.php +++ b/tests/V2/Product/CropTest.php @@ -8,8 +8,6 @@ use Mindee\V2\Product\Crop\CropResponse; use Mindee\Geometry\Point; -// Added for the polygon coordinate assertions - require_once(__DIR__ . "/../../TestingUtilities.php"); /** @@ -86,7 +84,6 @@ public function testCropWhenSingleMustHaveValidProperties(): void $polygon = $firstCrop->location->polygon; $this->assertCount(4, $polygon->getCoordinates()); - // Note: Using assertEquals here instead of assertSame to allow for object value comparison $this->assertEquals(new Point(0.214, 0.036), $polygon->getCoordinates()[0]); $this->assertEquals(new Point(0.476, 0.036), $polygon->getCoordinates()[1]); $this->assertEquals(new Point(0.476, 0.949), $polygon->getCoordinates()[2]); @@ -158,8 +155,6 @@ public function testRstDisplayMustBeAccessible(): void $inference = $response->inference; $this->assertNotNull($inference); - // Assumes your Inference class implements the __toString() magic method - // which maps to C#'s ToString() $this->assertEquals( self::normalizeLineEndings($rstReference), self::normalizeLineEndings((string)$inference) diff --git a/tests/V2/Product/OcrTest.php b/tests/V2/Product/OcrTest.php index 01d027b5..0d6b9808 100644 --- a/tests/V2/Product/OcrTest.php +++ b/tests/V2/Product/OcrTest.php @@ -68,7 +68,6 @@ public function testOcrWhenSingleMustHaveValidProperties(): void $firstWord = $firstPage->words[0]; $this->assertSame("Shipper:", $firstWord->content); - // Using the getCoordinates() logic from the corrected file $this->assertCount(4, $firstWord->polygon->getCoordinates()); $fifthWord = $firstPage->words[4]; From dbdc368b5b0a6603ae35849e1b91df1e4da7a8fe Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Tue, 12 May 2026 15:41:05 +0200 Subject: [PATCH 03/11] :recycle: drop phpcs/phpcbf in favor of php-cs-fixer with stricter rules (#187) --- .github/workflows/_static-analysis.yml | 13 +- .php-cs-fixer.dist.php | 47 ++ bin/DocumentCommandConfig.php | 12 +- bin/MindeeCLICommand.php | 95 ++-- bin/MindeeCLIDocuments.php | 81 ++-- bin/cli.php | 7 +- composer.json | 7 +- phpcs.xml | 313 ------------- src/ClientOptions/PollingOptions.php | 8 +- src/CustomSleepMixin.php | 5 +- src/Dependency/DependencyChecker.php | 39 +- src/Error/ErrorCode.php | 2 + src/Error/MindeeApiException.php | 6 +- src/Error/MindeeClientException.php | 6 +- src/Error/MindeeException.php | 6 +- src/Error/MindeeGeometryException.php | 6 +- src/Error/MindeeHttpClientException.php | 6 +- src/Error/MindeeHttpException.php | 31 +- src/Error/MindeeHttpServerException.php | 6 +- src/Error/MindeeImageException.php | 6 +- src/Error/MindeeInputException.php | 6 +- src/Error/MindeeMimeTypeException.php | 6 +- src/Error/MindeePDFException.php | 6 +- src/Error/MindeeSourceException.php | 6 +- src/Error/MindeeUnhandledException.php | 6 +- src/Error/MindeeUnsetException.php | 2 + src/Error/MindeeV2HttpException.php | 4 +- src/Error/MindeeV2HttpUnknownException.php | 4 +- src/Extraction/ExtractedImage.php | 37 +- src/Extraction/ExtractedPDF.php | 5 +- src/Extraction/ImageExtractor.php | 73 +-- src/Extraction/PDFExtractor.php | 31 +- src/Geometry/BBox.php | 7 +- src/Geometry/BBoxUtils.php | 7 +- src/Geometry/MinMax.php | 2 + src/Geometry/MinMaxUtils.php | 6 +- src/Geometry/Point.php | 15 +- src/Geometry/Polygon.php | 18 +- src/Geometry/PolygonUtils.php | 28 +- src/Image/ImageCompressor.php | 24 +- src/Image/ImageUtils.php | 61 +-- src/Input/Base64Input.php | 13 +- src/Input/BytesInput.php | 9 +- src/Input/FileInput.php | 6 +- src/Input/InputSource.php | 6 +- src/Input/LocalInputSource.php | 72 +-- src/Input/LocalResponse.php | 7 +- src/Input/PageOptions.php | 12 +- src/Input/PathInput.php | 6 +- src/Input/URLInputSource.php | 51 +-- src/PDF/CustomFPDI.php | 28 +- src/PDF/PDFCompressor.php | 51 ++- src/PDF/PDFUtils.php | 42 +- src/Parsing/SummaryHelper.php | 19 +- src/V1/Client.php | 165 ++++--- src/V1/ClientOptions/CommonOptions.php | 6 +- src/V1/ClientOptions/PredictMethodOptions.php | 14 +- src/V1/ClientOptions/PredictOptions.php | 20 +- src/V1/ClientOptions/WorkflowOptions.php | 14 +- src/V1/HTTP/BaseAPI.php | 18 +- src/V1/HTTP/BaseEndpoint.php | 10 +- src/V1/HTTP/Endpoint.php | 26 +- src/V1/HTTP/MindeeAPI.php | 18 +- src/V1/HTTP/MindeeWorkflowAPI.php | 12 +- src/V1/HTTP/ResponseValidation.php | 22 +- src/V1/HTTP/WorkflowEndpoint.php | 8 +- src/V1/Image/ImageExtractor.php | 6 +- src/V1/Parsing/Common/ApiRequest.php | 2 + src/V1/Parsing/Common/ApiResponse.php | 2 + .../Parsing/Common/AsyncPredictResponse.php | 8 +- src/V1/Parsing/Common/Document.php | 21 +- src/V1/Parsing/Common/Execution.php | 33 +- src/V1/Parsing/Common/ExecutionFile.php | 2 + src/V1/Parsing/Common/Extras/CropperExtra.php | 10 +- src/V1/Parsing/Common/Extras/Extras.php | 14 +- .../Common/Extras/FullTextOcrExtra.php | 2 + src/V1/Parsing/Common/Extras/RAGExtra.php | 2 + src/V1/Parsing/Common/Inference.php | 11 +- src/V1/Parsing/Common/Job.php | 22 +- src/V1/Parsing/Common/OCR/MVisionV1.php | 5 +- src/V1/Parsing/Common/OCR/OCR.php | 10 +- src/V1/Parsing/Common/OCR/OCRLine.php | 10 +- src/V1/Parsing/Common/OCR/OCRPage.php | 20 +- src/V1/Parsing/Common/OCR/OCRWord.php | 2 + src/V1/Parsing/Common/OrientationField.php | 17 +- src/V1/Parsing/Common/Page.php | 6 +- src/V1/Parsing/Common/PredictResponse.php | 4 +- src/V1/Parsing/Common/Prediction.php | 2 + src/V1/Parsing/Common/Product.php | 2 + src/V1/Parsing/Common/WorkflowResponse.php | 4 +- .../Parsing/Generated/GeneratedListField.php | 19 +- .../Generated/GeneratedObjectField.php | 19 +- src/V1/Parsing/Standard/AddressField.php | 11 +- src/V1/Parsing/Standard/AmountField.php | 16 +- src/V1/Parsing/Standard/BaseField.php | 20 +- src/V1/Parsing/Standard/BooleanField.php | 12 +- .../Parsing/Standard/ClassificationField.php | 10 +- .../Standard/CompanyRegistrationField.php | 15 +- src/V1/Parsing/Standard/DateField.php | 10 +- .../Parsing/Standard/FieldConfidenceMixin.php | 7 +- .../Parsing/Standard/FieldPositionMixin.php | 7 +- src/V1/Parsing/Standard/LocaleField.php | 23 +- .../Parsing/Standard/PaymentDetailsField.php | 34 +- src/V1/Parsing/Standard/PositionField.php | 41 +- src/V1/Parsing/Standard/StringField.php | 16 +- src/V1/Parsing/Standard/TaxField.php | 45 +- src/V1/Parsing/Standard/Taxes.php | 17 +- src/V1/Parsing/SummaryHelperV1.php | 8 +- .../Product/BarcodeReader/BarcodeReaderV1.php | 2 + .../BarcodeReader/BarcodeReaderV1Document.php | 14 +- .../Product/BillOfLading/BillOfLadingV1.php | 2 + .../BillOfLading/BillOfLadingV1Carrier.php | 11 +- .../BillOfLadingV1CarrierItem.php | 23 +- .../BillOfLadingV1CarrierItems.php | 12 +- .../BillOfLading/BillOfLadingV1Consignee.php | 11 +- .../BillOfLading/BillOfLadingV1Document.php | 16 +- .../BillOfLadingV1NotifyParty.php | 11 +- .../BillOfLading/BillOfLadingV1Shipper.php | 11 +- .../Product/BusinessCard/BusinessCardV1.php | 2 + .../BusinessCard/BusinessCardV1Document.php | 10 +- src/V1/Product/Cropper/CropperV1.php | 2 + src/V1/Product/Cropper/CropperV1Document.php | 2 + src/V1/Product/Cropper/CropperV1Page.php | 10 +- .../Product/DeliveryNote/DeliveryNoteV1.php | 2 + .../DeliveryNote/DeliveryNoteV1Document.php | 6 +- .../Product/DriverLicense/DriverLicenseV1.php | 2 + .../DriverLicense/DriverLicenseV1Document.php | 6 +- .../FinancialDocument/FinancialDocumentV1.php | 2 + .../FinancialDocumentV1Document.php | 26 +- .../FinancialDocumentV1LineItem.php | 31 +- .../FinancialDocumentV1LineItems.php | 12 +- .../BankAccountDetailsV1.php | 2 + .../BankAccountDetailsV1Document.php | 6 +- .../BankAccountDetailsV2.php | 2 + .../BankAccountDetailsV2Bban.php | 11 +- .../BankAccountDetailsV2Document.php | 8 +- src/V1/Product/Fr/CarteGrise/CarteGriseV1.php | 2 + .../Fr/CarteGrise/CarteGriseV1Document.php | 6 +- src/V1/Product/Fr/EnergyBill/EnergyBillV1.php | 2 + .../Fr/EnergyBill/EnergyBillV1Document.php | 20 +- .../EnergyBill/EnergyBillV1EnergyConsumer.php | 11 +- .../EnergyBill/EnergyBillV1EnergySupplier.php | 11 +- .../Fr/EnergyBill/EnergyBillV1EnergyUsage.php | 27 +- .../EnergyBill/EnergyBillV1EnergyUsages.php | 12 +- .../Fr/EnergyBill/EnergyBillV1MeterDetail.php | 11 +- .../EnergyBill/EnergyBillV1Subscription.php | 23 +- .../EnergyBill/EnergyBillV1Subscriptions.php | 12 +- .../EnergyBillV1TaxesAndContribution.php | 23 +- .../EnergyBillV1TaxesAndContributions.php | 12 +- src/V1/Product/Fr/HealthCard/HealthCardV1.php | 2 + .../Fr/HealthCard/HealthCardV1Document.php | 10 +- src/V1/Product/Fr/IdCard/IdCardV1.php | 2 + src/V1/Product/Fr/IdCard/IdCardV1Document.php | 10 +- src/V1/Product/Fr/IdCard/IdCardV1Page.php | 6 +- src/V1/Product/Fr/IdCard/IdCardV2.php | 2 + src/V1/Product/Fr/IdCard/IdCardV2Document.php | 10 +- src/V1/Product/Fr/IdCard/IdCardV2Page.php | 6 +- src/V1/Product/Fr/Payslip/PayslipV3.php | 2 + .../Fr/Payslip/PayslipV3BankAccountDetail.php | 11 +- .../Product/Fr/Payslip/PayslipV3Document.php | 24 +- .../Product/Fr/Payslip/PayslipV3Employee.php | 11 +- .../Product/Fr/Payslip/PayslipV3Employer.php | 11 +- .../Fr/Payslip/PayslipV3Employment.php | 11 +- .../Fr/Payslip/PayslipV3PaidTimeOff.php | 23 +- .../Fr/Payslip/PayslipV3PaidTimeOffs.php | 12 +- .../Product/Fr/Payslip/PayslipV3PayDetail.php | 51 ++- .../Product/Fr/Payslip/PayslipV3PayPeriod.php | 11 +- .../Fr/Payslip/PayslipV3SalaryDetail.php | 27 +- .../Fr/Payslip/PayslipV3SalaryDetails.php | 12 +- src/V1/Product/Generated/GeneratedV1.php | 2 + .../Product/Generated/GeneratedV1Document.php | 16 +- src/V1/Product/Generated/GeneratedV1Page.php | 20 +- .../Generated/GeneratedV1Prediction.php | 10 +- .../Ind/IndianPassport/IndianPassportV1.php | 2 + .../IndianPassportV1Document.php | 6 +- .../InternationalId/InternationalIdV2.php | 2 + .../InternationalIdV2Document.php | 14 +- src/V1/Product/Invoice/InvoiceV4.php | 2 + src/V1/Product/Invoice/InvoiceV4Document.php | 24 +- src/V1/Product/Invoice/InvoiceV4LineItem.php | 31 +- src/V1/Product/Invoice/InvoiceV4LineItems.php | 12 +- .../InvoiceSplitter/InvoiceSplitterV1.php | 2 + .../InvoiceSplitterV1Document.php | 10 +- .../InvoiceSplitterV1InvoicePageGroup.php | 11 +- .../InvoiceSplitterV1InvoicePageGroups.php | 12 +- .../MultiReceiptsDetectorV1.php | 2 + .../MultiReceiptsDetectorV1Document.php | 10 +- .../NutritionFactsLabelV1.php | 2 + .../NutritionFactsLabelV1AddedSugar.php | 23 +- .../NutritionFactsLabelV1Calorie.php | 23 +- .../NutritionFactsLabelV1Cholesterol.php | 23 +- .../NutritionFactsLabelV1DietaryFiber.php | 23 +- .../NutritionFactsLabelV1Document.php | 32 +- .../NutritionFactsLabelV1Nutrient.php | 23 +- .../NutritionFactsLabelV1Nutrients.php | 12 +- .../NutritionFactsLabelV1Protein.php | 23 +- .../NutritionFactsLabelV1SaturatedFat.php | 23 +- .../NutritionFactsLabelV1ServingSize.php | 15 +- .../NutritionFactsLabelV1Sodium.php | 23 +- ...NutritionFactsLabelV1TotalCarbohydrate.php | 23 +- .../NutritionFactsLabelV1TotalFat.php | 23 +- .../NutritionFactsLabelV1TotalSugar.php | 23 +- .../NutritionFactsLabelV1TransFat.php | 23 +- src/V1/Product/Passport/PassportV1.php | 2 + .../Product/Passport/PassportV1Document.php | 10 +- src/V1/Product/Receipt/ReceiptV5.php | 2 + src/V1/Product/Receipt/ReceiptV5Document.php | 12 +- src/V1/Product/Receipt/ReceiptV5LineItem.php | 23 +- src/V1/Product/Receipt/ReceiptV5LineItems.php | 12 +- src/V1/Product/Resume/ResumeV1.php | 2 + src/V1/Product/Resume/ResumeV1Certificate.php | 11 +- .../Product/Resume/ResumeV1Certificates.php | 12 +- src/V1/Product/Resume/ResumeV1Document.php | 32 +- src/V1/Product/Resume/ResumeV1Education.php | 11 +- src/V1/Product/Resume/ResumeV1Educations.php | 12 +- src/V1/Product/Resume/ResumeV1Language.php | 11 +- src/V1/Product/Resume/ResumeV1Languages.php | 12 +- .../Resume/ResumeV1ProfessionalExperience.php | 11 +- .../ResumeV1ProfessionalExperiences.php | 12 +- .../Resume/ResumeV1SocialNetworksUrl.php | 11 +- .../Resume/ResumeV1SocialNetworksUrls.php | 12 +- src/V1/Product/Us/BankCheck/BankCheckV1.php | 2 + .../Us/BankCheck/BankCheckV1Document.php | 10 +- .../Product/Us/BankCheck/BankCheckV1Page.php | 10 +- .../Us/HealthcareCard/HealthcareCardV1.php | 2 + .../HealthcareCard/HealthcareCardV1Copay.php | 15 +- .../HealthcareCard/HealthcareCardV1Copays.php | 12 +- .../HealthcareCardV1Document.php | 12 +- src/V1/Product/Us/UsMail/UsMailV3.php | 2 + src/V1/Product/Us/UsMail/UsMailV3Document.php | 14 +- .../Us/UsMail/UsMailV3RecipientAddress.php | 11 +- .../Us/UsMail/UsMailV3RecipientAddresses.php | 12 +- .../Us/UsMail/UsMailV3SenderAddress.php | 11 +- src/V2/Client.php | 30 +- src/V2/ClientOptions/BaseParameters.php | 8 +- src/V2/FileOperations/Crop.php | 6 +- src/V2/FileOperations/CropFiles.php | 19 +- src/V2/FileOperations/Split.php | 6 +- src/V2/FileOperations/SplitFiles.php | 17 +- src/V2/HTTP/MindeeAPIV2.php | 37 +- src/V2/Parsing/BaseInference.php | 2 + src/V2/Parsing/ErrorItem.php | 2 + src/V2/Parsing/ErrorResponse.php | 8 +- src/V2/Parsing/Inference/BaseResponse.php | 2 + src/V2/Parsing/Inference/Field/BaseField.php | 14 +- .../Inference/Field/FieldConfidence.php | 2 + .../Parsing/Inference/Field/FieldLocation.php | 5 +- .../Inference/Field/InferenceFields.php | 15 +- src/V2/Parsing/Inference/Field/ListField.php | 11 +- .../Parsing/Inference/Field/ObjectField.php | 18 +- .../Parsing/Inference/Field/SimpleField.php | 15 +- .../Inference/InferenceActiveOptions.php | 10 +- src/V2/Parsing/Inference/InferenceFile.php | 2 + src/V2/Parsing/Inference/InferenceJob.php | 2 + src/V2/Parsing/Inference/InferenceModel.php | 2 + src/V2/Parsing/Inference/RAGMetadata.php | 2 + src/V2/Parsing/Inference/RawText.php | 4 + src/V2/Parsing/Inference/RawTextPage.php | 3 +- src/V2/Parsing/Job.php | 5 +- src/V2/Parsing/JobResponse.php | 2 + src/V2/Parsing/JobWebhook.php | 3 +- .../ClassificationClassifier.php | 6 +- .../ClassificationInference.php | 3 +- .../Classification/ClassificationResponse.php | 2 + .../Classification/ClassificationResult.php | 2 + .../Params/ClassificationParameters.php | 6 +- src/V2/Product/Crop/CropInference.php | 2 + src/V2/Product/Crop/CropItem.php | 8 +- src/V2/Product/Crop/CropResponse.php | 2 + src/V2/Product/Crop/CropResult.php | 4 +- src/V2/Product/Crop/Params/CropParameters.php | 6 +- .../Extraction/ExtractionInference.php | 3 +- .../Product/Extraction/ExtractionResponse.php | 2 + .../Product/Extraction/ExtractionResult.php | 2 + .../Product/Extraction/Params/DataSchema.php | 15 +- .../Params/DataSchemaActiveOption.php | 2 + .../Extraction/Params/DataSchemaField.php | 2 + .../Extraction/Params/DataSchemaReplace.php | 15 +- .../Params/ExtractionParameters.php | 34 +- src/V2/Product/Ocr/OcrInference.php | 2 + src/V2/Product/Ocr/OcrPage.php | 4 +- src/V2/Product/Ocr/OcrResponse.php | 2 + src/V2/Product/Ocr/OcrResult.php | 6 +- src/V2/Product/Ocr/OcrWord.php | 2 + src/V2/Product/Ocr/Params/OcrParameters.php | 6 +- .../Product/Split/Params/SplitParameters.php | 6 +- src/V2/Product/Split/SplitInference.php | 2 + src/V2/Product/Split/SplitRange.php | 8 +- src/V2/Product/Split/SplitResponse.php | 2 + src/V2/Product/Split/SplitResult.php | 4 +- src/version.php | 2 + tests/ClientTest.php | 65 +-- tests/CustomSleepMixinTest.php | 43 +- .../DependencyCheckerNoExtendedTestPDF.php | 15 +- .../Dependencies/DependencyCheckerPDFTest.php | 14 +- tests/Geometry/BBoxTest.php | 46 +- tests/Geometry/PolygonUtilsTest.php | 44 +- tests/Input/LocalInputSourceTest.php | 144 +++--- tests/Input/URLInputSourceTest.php | 15 +- tests/TestingUtilities.php | 18 +- tests/V1/CLI/MindeeCLICommandTest.php | 23 +- .../V1/CLI/MindeeCLICommandTestFunctional.php | 17 +- tests/V1/CLI/MindeeCLITestingUtilities.php | 4 +- tests/V1/Error/MindeeHttpExceptionTest.php | 65 +-- tests/V1/Extraction/ImageExtractorTest.php | 80 ++-- ...ceSplitterAutoExtractionTestFunctional.php | 20 +- tests/V1/Extraction/PDFExtractorTest.php | 57 +-- tests/V1/Http/MindeeApiTest.php | 26 +- tests/V1/Input/LocalResponseV1Test.php | 47 +- .../V1/Input/URLInputSourceTestFunctional.php | 29 +- .../Common/AsyncPredictResponseTest.php | 61 +-- .../Common/Extras/CropperExtraTest.php | 35 +- .../Extras/ExtrasIntegrationFunctional.php | 18 +- .../Common/Extras/FullTextOcrExtraTest.php | 17 +- tests/V1/Parsing/Common/OCR/OCRTest.php | 38 +- .../V1/Parsing/Common/PredictResponseTest.php | 13 +- .../BarcodeReader/BarcodeReaderV1Test.php | 21 +- .../BillOfLading/BillOfLadingV1Test.php | 61 +-- .../BusinessCard/BusinessCardV1Test.php | 39 +- tests/V1/Product/Cropper/CropperV1Test.php | 28 +- .../DeliveryNote/DeliveryNoteV1Test.php | 31 +- .../DriverLicense/DriverLicenseV1Test.php | 43 +- .../FinancialDocumentV1Test.php | 88 ++-- .../BankAccountDetailsV1Test.php | 23 +- .../BankAccountDetailsV2Test.php | 31 +- .../Fr/CarteGrise/CarteGriseV1Test.php | 99 +++-- .../Fr/EnergyBill/EnergyBillV1Test.php | 53 +-- .../Fr/HealthCard/HealthCardV1Test.php | 25 +- tests/V1/Product/Fr/IdCard/IdCardV1Test.php | 46 +- tests/V1/Product/Fr/IdCard/IdCardV2Test.php | 56 +-- tests/V1/Product/Fr/Payslip/PayslipV3Test.php | 99 +++-- .../V1/Product/Generated/GeneratedV1Test.php | 420 +++++++++--------- .../IndianPassport/IndianPassportV1Test.php | 59 +-- .../InternationalId/InternationalIdV2Test.php | 49 +- tests/V1/Product/Invoice/InvoiceV4Test.php | 67 +-- .../InvoiceSplitter/InvoiceSplitterV1Test.php | 19 +- .../MultiReceiptsDetectorV1Test.php | 19 +- .../NutritionFactsLabelV1Test.php | 93 ++-- tests/V1/Product/Passport/PassportV1Test.php | 39 +- tests/V1/Product/Receipt/ReceiptV5Test.php | 45 +- tests/V1/Product/Resume/ResumeV1Test.php | 49 +- .../Product/Us/BankCheck/BankCheckV1Test.php | 38 +- .../HealthcareCard/HealthcareCardV1Test.php | 45 +- tests/V1/Product/Us/UsMail/UsMailV3Test.php | 35 +- tests/V1/Standard/AmountFieldTest.php | 14 +- tests/V1/Standard/ClassificationFieldTest.php | 16 +- .../Standard/CompanyRegistrationFieldTest.php | 14 +- tests/V1/Standard/DateFieldTest.php | 19 +- tests/V1/Standard/LocaleFieldTest.php | 22 +- tests/V1/Standard/PaymentDetailsFieldTest.php | 32 +- tests/V1/Standard/PositionFieldTest.php | 22 +- tests/V1/Standard/StringFieldTest.php | 28 +- tests/V1/Standard/TaxesTest.php | 30 +- tests/V1/Workflow/WorkflowTest.php | 66 +-- tests/V1/Workflow/WorkflowTestFunctional.php | 36 +- tests/V2/ClientOptions/BaseParametersTest.php | 10 +- tests/V2/ClientV2Test.php | 62 +-- tests/V2/ClientV2TestFunctional.php | 122 ++--- tests/V2/FileOperations/CropFunctional.php | 41 +- tests/V2/FileOperations/CropTest.php | 32 +- tests/V2/FileOperations/SplitFunctional.php | 37 +- tests/V2/FileOperations/SplitTest.php | 23 +- tests/V2/Input/InferenceParameterTest.php | 23 +- tests/V2/Input/LocalResponseV2Test.php | 35 +- tests/V2/Parsing/ExtractionResponseTest.php | 340 +++++++------- tests/V2/Parsing/JobResponseTest.php | 45 +- tests/V2/Product/ClassificationFunctional.php | 14 +- tests/V2/Product/ClassificationTest.php | 26 +- tests/V2/Product/CropFunctional.php | 50 +-- tests/V2/Product/CropTest.php | 94 ++-- tests/V2/Product/OcrFunctional.php | 17 +- tests/V2/Product/OcrTest.php | 51 ++- tests/V2/Product/SplitFunctional.php | 17 +- tests/V2/Product/SplitTest.php | 55 ++- 374 files changed, 4353 insertions(+), 3915 deletions(-) create mode 100644 .php-cs-fixer.dist.php delete mode 100644 phpcs.xml 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]); } } From 8232cc2024dcc1e0794ae88437e8b8101a670885 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Tue, 26 May 2026 17:42:32 +0200 Subject: [PATCH 04/11] :wrench: add PHPstan and remove PHP Code Sniffer (#188) --- .github/workflows/_static-analysis.yml | 5 +- composer.json | 4 +- docs/code_samples/v2_ocr.txt | 6 +- src/Dependency/DependencyChecker.php | 1 + src/Error/MindeeHttpException.php | 22 ++--- src/Error/MindeeV2HttpException.php | 3 +- src/Extraction/ExtractedImage.php | 6 +- src/Extraction/ImageExtractor.php | 24 +++--- src/Extraction/PDFExtractor.php | 8 +- src/Geometry/BBox.php | 4 +- src/Geometry/BBoxUtils.php | 24 +++--- src/Geometry/MinMaxUtils.php | 14 +++- src/Geometry/Point.php | 11 +-- src/Geometry/Polygon.php | 6 +- src/Geometry/PolygonUtils.php | 17 ++-- src/Image/ImageCompressor.php | 6 +- src/Image/ImageUtils.php | 12 ++- src/Input/Base64Input.php | 2 +- src/Input/BytesInput.php | 2 +- src/Input/FileInput.php | 20 ++--- src/Input/LocalInputSource.php | 4 +- src/Input/LocalResponse.php | 67 +++++++-------- src/Input/PageOptions.php | 4 +- src/PDF/CustomFPDI.php | 10 ++- src/PDF/PDFCompressor.php | 83 ++----------------- src/PDF/PDFUtils.php | 39 +++++---- src/Parsing/SummaryHelper.php | 6 +- src/V1/Client.php | 27 +++--- src/V1/ClientOptions/CommonOptions.php | 3 +- src/V1/HTTP/BaseAPI.php | 6 +- src/V1/HTTP/BaseEndpoint.php | 16 ++-- src/V1/HTTP/Endpoint.php | 12 ++- src/V1/HTTP/MindeeAPI.php | 2 +- src/V1/HTTP/MindeeWorkflowAPI.php | 2 +- src/V1/HTTP/ResponseValidation.php | 9 +- src/V1/HTTP/WorkflowEndpoint.php | 6 ++ src/V1/Parsing/Common/ApiRequest.php | 20 ++--- src/V1/Parsing/Common/ApiResponse.php | 4 +- .../Parsing/Common/AsyncPredictResponse.php | 2 +- src/V1/Parsing/Common/Document.php | 18 ++-- src/V1/Parsing/Common/Execution.php | 2 +- src/V1/Parsing/Common/ExecutionFile.php | 2 +- src/V1/Parsing/Common/Extras/CropperExtra.php | 4 +- src/V1/Parsing/Common/Extras/Extras.php | 32 +++---- ...lTextOcrExtra.php => FullTextOCRExtra.php} | 4 +- src/V1/Parsing/Common/Extras/RAGExtra.php | 2 +- src/V1/Parsing/Common/Inference.php | 16 ++-- src/V1/Parsing/Common/Job.php | 22 +++-- src/V1/Parsing/Common/OCR/MVisionV1.php | 4 +- src/V1/Parsing/Common/OCR/OCR.php | 4 +- src/V1/Parsing/Common/OCR/OCRLine.php | 4 +- src/V1/Parsing/Common/OCR/OCRPage.php | 16 ++-- src/V1/Parsing/Common/OCR/OCRWord.php | 6 +- src/V1/Parsing/Common/OrientationField.php | 10 +-- src/V1/Parsing/Common/Page.php | 32 ++++--- src/V1/Parsing/Common/PredictResponse.php | 2 +- src/V1/Parsing/Common/Product.php | 6 +- src/V1/Parsing/Common/WorkflowResponse.php | 2 +- .../Parsing/Generated/GeneratedListField.php | 15 ++-- .../Generated/GeneratedObjectField.php | 52 +++++++++++- src/V1/Parsing/Standard/AddressField.php | 2 +- src/V1/Parsing/Standard/AmountField.php | 9 +- src/V1/Parsing/Standard/BaseField.php | 13 +-- src/V1/Parsing/Standard/BooleanField.php | 9 +- .../Parsing/Standard/ClassificationField.php | 9 +- .../Standard/CompanyRegistrationField.php | 7 +- src/V1/Parsing/Standard/DateField.php | 18 ++-- .../Parsing/Standard/FieldConfidenceMixin.php | 2 +- .../Parsing/Standard/FieldPositionMixin.php | 2 +- src/V1/Parsing/Standard/LocaleField.php | 5 +- .../Parsing/Standard/PaymentDetailsField.php | 5 +- src/V1/Parsing/Standard/PositionField.php | 23 ++--- src/V1/Parsing/Standard/StringField.php | 7 +- src/V1/Parsing/Standard/TaxField.php | 10 +-- src/V1/Parsing/Standard/Taxes.php | 3 +- .../Product/BarcodeReader/BarcodeReaderV1.php | 2 +- .../BarcodeReader/BarcodeReaderV1Document.php | 7 +- .../Product/BillOfLading/BillOfLadingV1.php | 2 +- .../BillOfLading/BillOfLadingV1Carrier.php | 22 ++--- .../BillOfLadingV1CarrierItem.php | 24 ++---- .../BillOfLadingV1CarrierItems.php | 3 +- .../BillOfLading/BillOfLadingV1Consignee.php | 24 ++---- .../BillOfLading/BillOfLadingV1Document.php | 10 +-- .../BillOfLadingV1NotifyParty.php | 23 ++--- .../BillOfLading/BillOfLadingV1Shipper.php | 23 ++--- .../Product/BusinessCard/BusinessCardV1.php | 2 +- .../BusinessCard/BusinessCardV1Document.php | 4 +- src/V1/Product/Cropper/CropperV1.php | 4 +- src/V1/Product/Cropper/CropperV1Document.php | 5 ++ src/V1/Product/Cropper/CropperV1Page.php | 4 +- .../Product/DeliveryNote/DeliveryNoteV1.php | 2 +- .../DeliveryNote/DeliveryNoteV1Document.php | 2 +- .../Product/DriverLicense/DriverLicenseV1.php | 2 +- .../DriverLicense/DriverLicenseV1Document.php | 2 +- .../FinancialDocument/FinancialDocumentV1.php | 2 +- .../FinancialDocumentV1Document.php | 10 +-- .../FinancialDocumentV1LineItem.php | 26 ++---- .../FinancialDocumentV1LineItems.php | 3 +- .../BankAccountDetailsV1.php | 2 +- .../BankAccountDetailsV1Document.php | 2 +- .../BankAccountDetailsV2.php | 2 +- .../BankAccountDetailsV2Bban.php | 23 ++--- .../BankAccountDetailsV2Document.php | 4 +- src/V1/Product/Fr/CarteGrise/CarteGriseV1.php | 2 +- .../Fr/CarteGrise/CarteGriseV1Document.php | 2 +- src/V1/Product/Fr/EnergyBill/EnergyBillV1.php | 2 +- .../Fr/EnergyBill/EnergyBillV1Document.php | 8 +- .../EnergyBill/EnergyBillV1EnergyConsumer.php | 21 ++--- .../EnergyBill/EnergyBillV1EnergySupplier.php | 21 ++--- .../Fr/EnergyBill/EnergyBillV1EnergyUsage.php | 26 ++---- .../EnergyBill/EnergyBillV1EnergyUsages.php | 3 +- .../Fr/EnergyBill/EnergyBillV1MeterDetail.php | 22 ++--- .../EnergyBill/EnergyBillV1Subscription.php | 24 ++---- .../EnergyBill/EnergyBillV1Subscriptions.php | 3 +- .../EnergyBillV1TaxesAndContribution.php | 24 ++---- .../EnergyBillV1TaxesAndContributions.php | 3 +- src/V1/Product/Fr/HealthCard/HealthCardV1.php | 2 +- .../Fr/HealthCard/HealthCardV1Document.php | 4 +- src/V1/Product/Fr/IdCard/IdCardV1.php | 2 +- src/V1/Product/Fr/IdCard/IdCardV1Document.php | 5 +- src/V1/Product/Fr/IdCard/IdCardV1Page.php | 2 +- src/V1/Product/Fr/IdCard/IdCardV2.php | 2 +- src/V1/Product/Fr/IdCard/IdCardV2Document.php | 4 +- src/V1/Product/Fr/IdCard/IdCardV2Page.php | 2 +- src/V1/Product/Fr/Payslip/PayslipV3.php | 2 +- .../Fr/Payslip/PayslipV3BankAccountDetail.php | 22 ++--- .../Product/Fr/Payslip/PayslipV3Document.php | 15 ++-- .../Product/Fr/Payslip/PayslipV3Employee.php | 26 ++---- .../Product/Fr/Payslip/PayslipV3Employer.php | 26 ++---- .../Fr/Payslip/PayslipV3Employment.php | 26 ++---- .../Fr/Payslip/PayslipV3PaidTimeOff.php | 23 ++--- .../Fr/Payslip/PayslipV3PaidTimeOffs.php | 3 +- .../Product/Fr/Payslip/PayslipV3PayDetail.php | 29 ++----- .../Product/Fr/Payslip/PayslipV3PayPeriod.php | 24 ++---- .../Fr/Payslip/PayslipV3SalaryDetail.php | 23 ++--- .../Fr/Payslip/PayslipV3SalaryDetails.php | 3 +- src/V1/Product/Generated/GeneratedV1.php | 2 +- .../Product/Generated/GeneratedV1Document.php | 8 +- src/V1/Product/Generated/GeneratedV1Page.php | 9 +- .../Generated/GeneratedV1Prediction.php | 3 +- .../Ind/IndianPassport/IndianPassportV1.php | 2 +- .../IndianPassportV1Document.php | 2 +- .../InternationalId/InternationalIdV2.php | 2 +- .../InternationalIdV2Document.php | 6 +- src/V1/Product/Invoice/InvoiceV4.php | 2 +- src/V1/Product/Invoice/InvoiceV4Document.php | 10 +-- src/V1/Product/Invoice/InvoiceV4LineItem.php | 26 ++---- src/V1/Product/Invoice/InvoiceV4LineItems.php | 3 +- .../InvoiceSplitter/InvoiceSplitterV1.php | 2 +- .../InvoiceSplitterV1Document.php | 2 +- .../InvoiceSplitterV1InvoicePageGroup.php | 19 ++--- .../InvoiceSplitterV1InvoicePageGroups.php | 3 +- .../MultiReceiptsDetectorV1.php | 2 +- .../MultiReceiptsDetectorV1Document.php | 4 +- .../NutritionFactsLabelV1.php | 2 +- .../NutritionFactsLabelV1AddedSugar.php | 22 ++--- .../NutritionFactsLabelV1Calorie.php | 22 ++--- .../NutritionFactsLabelV1Cholesterol.php | 22 ++--- .../NutritionFactsLabelV1DietaryFiber.php | 22 ++--- .../NutritionFactsLabelV1Document.php | 26 +++--- .../NutritionFactsLabelV1Nutrient.php | 23 ++--- .../NutritionFactsLabelV1Nutrients.php | 3 +- .../NutritionFactsLabelV1Protein.php | 22 ++--- .../NutritionFactsLabelV1SaturatedFat.php | 22 ++--- .../NutritionFactsLabelV1ServingSize.php | 21 ++--- .../NutritionFactsLabelV1Sodium.php | 23 ++--- ...NutritionFactsLabelV1TotalCarbohydrate.php | 22 ++--- .../NutritionFactsLabelV1TotalFat.php | 22 ++--- .../NutritionFactsLabelV1TotalSugar.php | 23 ++--- .../NutritionFactsLabelV1TransFat.php | 22 ++--- src/V1/Product/Passport/PassportV1.php | 2 +- .../Product/Passport/PassportV1Document.php | 4 +- src/V1/Product/Receipt/ReceiptV5.php | 2 +- src/V1/Product/Receipt/ReceiptV5Document.php | 4 +- src/V1/Product/Receipt/ReceiptV5LineItem.php | 22 ++--- src/V1/Product/Receipt/ReceiptV5LineItems.php | 3 +- src/V1/Product/Resume/ResumeV1.php | 2 +- src/V1/Product/Resume/ResumeV1Certificate.php | 22 ++--- .../Product/Resume/ResumeV1Certificates.php | 3 +- src/V1/Product/Resume/ResumeV1Document.php | 10 +-- src/V1/Product/Resume/ResumeV1Education.php | 25 ++---- src/V1/Product/Resume/ResumeV1Educations.php | 3 +- src/V1/Product/Resume/ResumeV1Language.php | 20 ++--- src/V1/Product/Resume/ResumeV1Languages.php | 3 +- .../Resume/ResumeV1ProfessionalExperience.php | 27 ++---- .../ResumeV1ProfessionalExperiences.php | 3 +- .../Resume/ResumeV1SocialNetworksUrl.php | 20 ++--- .../Resume/ResumeV1SocialNetworksUrls.php | 3 +- src/V1/Product/Us/BankCheck/BankCheckV1.php | 2 +- .../Us/BankCheck/BankCheckV1Document.php | 4 +- .../Product/Us/BankCheck/BankCheckV1Page.php | 4 +- .../Us/HealthcareCard/HealthcareCardV1.php | 2 +- .../HealthcareCard/HealthcareCardV1Copay.php | 20 ++--- .../HealthcareCard/HealthcareCardV1Copays.php | 3 +- .../HealthcareCardV1Document.php | 4 +- src/V1/Product/Us/UsMail/UsMailV3.php | 2 +- src/V1/Product/Us/UsMail/UsMailV3Document.php | 6 +- .../Us/UsMail/UsMailV3RecipientAddress.php | 26 ++---- .../Us/UsMail/UsMailV3RecipientAddresses.php | 3 +- .../Us/UsMail/UsMailV3SenderAddress.php | 24 ++---- src/V2/ClientOptions/BaseParameters.php | 9 +- src/V2/FileOperations/CropFiles.php | 6 +- src/V2/FileOperations/SplitFiles.php | 4 +- src/V2/HTTP/MindeeAPIV2.php | 29 ++----- src/V2/Parsing/BaseInference.php | 2 +- src/V2/Parsing/ErrorItem.php | 2 +- src/V2/Parsing/ErrorResponse.php | 18 ++-- src/V2/Parsing/Inference/BaseResponse.php | 4 +- src/V2/Parsing/Inference/Field/BaseField.php | 13 ++- .../Parsing/Inference/Field/FieldLocation.php | 10 +-- .../Inference/Field/InferenceFields.php | 16 ++-- src/V2/Parsing/Inference/Field/ListField.php | 18 ++-- .../Parsing/Inference/Field/ObjectField.php | 8 +- .../Parsing/Inference/Field/SimpleField.php | 8 +- .../Inference/InferenceActiveOptions.php | 16 ++-- src/V2/Parsing/Inference/InferenceFile.php | 12 +-- src/V2/Parsing/Inference/InferenceJob.php | 6 +- src/V2/Parsing/Inference/InferenceModel.php | 6 +- src/V2/Parsing/Inference/RAGMetadata.php | 2 +- src/V2/Parsing/Inference/RawText.php | 8 +- src/V2/Parsing/Inference/RawTextPage.php | 9 +- src/V2/Parsing/Job.php | 34 ++++---- src/V2/Parsing/JobResponse.php | 2 +- src/V2/Parsing/JobWebhook.php | 18 ++-- .../ClassificationClassifier.php | 2 +- .../ClassificationInference.php | 2 +- .../Classification/ClassificationResponse.php | 2 +- .../Classification/ClassificationResult.php | 2 +- src/V2/Product/Crop/CropInference.php | 2 +- src/V2/Product/Crop/CropItem.php | 2 +- src/V2/Product/Crop/CropResponse.php | 2 +- src/V2/Product/Crop/CropResult.php | 2 +- .../Extraction/ExtractionInference.php | 2 +- .../Product/Extraction/ExtractionResponse.php | 2 +- .../Product/Extraction/ExtractionResult.php | 14 ++-- .../Product/Extraction/Params/DataSchema.php | 6 +- .../Params/DataSchemaActiveOption.php | 6 +- .../Extraction/Params/DataSchemaField.php | 34 ++++---- .../Extraction/Params/DataSchemaReplace.php | 14 ++-- .../Params/ExtractionParameters.php | 6 +- .../OcrInference.php => OCR/OCRInference.php} | 12 +-- .../{Ocr/OcrPage.php => OCR/OCRPage.php} | 10 +-- .../OcrResponse.php => OCR/OCRResponse.php} | 12 +-- .../{Ocr/OcrResult.php => OCR/OCRResult.php} | 10 +-- .../{Ocr/OcrWord.php => OCR/OCRWord.php} | 6 +- .../Params/OCRParameters.php} | 4 +- src/V2/Product/Split/SplitInference.php | 2 +- src/V2/Product/Split/SplitRange.php | 2 +- src/V2/Product/Split/SplitResponse.php | 2 +- src/V2/Product/Split/SplitResult.php | 2 +- .../V1/CLI/MindeeCLICommandTestFunctional.php | 1 + .../Extras/ExtrasIntegrationFunctional.php | 2 +- ...ExtraTest.php => FullTextOCRExtraTest.php} | 2 +- tests/V2/ClientOptions/BaseParametersTest.php | 2 +- tests/V2/ClientV2Test.php | 2 +- tests/V2/Parsing/ExtractionResponseTest.php | 2 +- .../{OcrFunctional.php => OCRFunctional.php} | 12 +-- tests/V2/Product/{OcrTest.php => OCRTest.php} | 12 +-- 258 files changed, 1160 insertions(+), 1546 deletions(-) rename src/V1/Parsing/Common/Extras/{FullTextOcrExtra.php => FullTextOCRExtra.php} (84%) rename src/V2/Product/{Ocr/OcrInference.php => OCR/OCRInference.php} (56%) rename src/V2/Product/{Ocr/OcrPage.php => OCR/OCRPage.php} (71%) rename src/V2/Product/{Ocr/OcrResponse.php => OCR/OCRResponse.php} (52%) rename src/V2/Product/{Ocr/OcrResult.php => OCR/OCRResult.php} (72%) rename src/V2/Product/{Ocr/OcrWord.php => OCR/OCRWord.php} (81%) rename src/V2/Product/{Ocr/Params/OcrParameters.php => OCR/Params/OCRParameters.php} (88%) rename tests/V1/Parsing/Common/Extras/{FullTextOcrExtraTest.php => FullTextOCRExtraTest.php} (95%) rename tests/V2/Product/{OcrFunctional.php => OCRFunctional.php} (79%) rename tests/V2/Product/{OcrTest.php => OCRTest.php} (91%) diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 8aaf8407..510b2452 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -34,4 +34,7 @@ jobs: - name: Run lint run: | composer lint - + + - name: Run PHPStan + run: | + composer phpstan diff --git a/composer.json b/composer.json index a8315df5..96a7daaf 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,8 @@ "require-dev": { "friendsofphp/php-cs-fixer": "^3.38", "phpunit/phpunit": "^9.6", - "madewithlove/license-checker": "^v1.0" + "madewithlove/license-checker": "^v1.0", + "phpstan/phpstan": "^2.1" }, "suggest": { "ext-imagick": "Required for PDF rasterization and image processing features", @@ -33,6 +34,7 @@ ], "scripts": { "lint": "php-cs-fixer fix --dry-run --diff", + "phpstan": "phpstan analyse src --level 6", "format": "php-cs-fixer fix" } } diff --git a/docs/code_samples/v2_ocr.txt b/docs/code_samples/v2_ocr.txt index 5beba83d..3921f550 100644 --- a/docs/code_samples/v2_ocr.txt +++ b/docs/code_samples/v2_ocr.txt @@ -1,8 +1,8 @@ readImage( + /** @phpstan-ignore-next-line */ TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg" ); } catch (Exception $e) { diff --git a/src/Error/MindeeHttpException.php b/src/Error/MindeeHttpException.php index f2f33d46..f83692d3 100644 --- a/src/Error/MindeeHttpException.php +++ b/src/Error/MindeeHttpException.php @@ -25,20 +25,20 @@ class MindeeHttpException extends MindeeException */ public int $statusCode; /** - * @var string|mixed|null API code as sent by the server. + * @var string|null API code as sent by the server. */ public ?string $apiCode; /** - * @var mixed|null API details field as sent by the server. + * @var string|array>|null API details field as sent by the server. */ - public $apiDetails; + public string|array|null $apiDetails; /** - * @var string|mixed|null API message field as sent by the server. + * @var string|array>|null API message field as sent by the server. */ - public ?string $apiMessage; + public string|array|null $apiMessage; /** - * @param array $httpError Array containing the error data. + * @param array> $httpError Array containing the error data. * @param string $url Remote URL the error was found on. * @param integer $code Error code. */ @@ -71,11 +71,11 @@ public function __construct(array $httpError, string $url, int $code) /** * Builds an appropriate error object from the server reply. * - * @param array|string $response Parsed server response. + * @param array>|string|null $response Parsed server response. * @return string[] * @throws MindeeException Throws if the error itself can't be built. */ - public static function createErrorObj($response): array + public static function createErrorObj(array|string|null $response): array { if (is_string($response)) { if (str_contains($response, 'Maximum pdf pages')) { @@ -125,7 +125,7 @@ public static function createErrorObj($response): array ) { return $response['api_request']['error']; } - if (!$response) { + if (!isset($response)) { throw new MindeeException( "Request to the API failed.", ErrorCode::API_REQUEST_FAILED @@ -139,9 +139,9 @@ public static function createErrorObj($response): array /** * @param string $url Remote URL the error was found on. - * @param array|string|boolean $response Raw server response. + * @param array|string|null $response Raw server response. */ - public static function handleError(string $url, $response): self + public static function handleError(string $url, array|string|null $response): self { if (is_array($response)) { $dataResponse = $response['data'] ?? ["data" => null]; diff --git a/src/Error/MindeeV2HttpException.php b/src/Error/MindeeV2HttpException.php index 22766176..75f23d01 100644 --- a/src/Error/MindeeV2HttpException.php +++ b/src/Error/MindeeV2HttpException.php @@ -4,6 +4,7 @@ namespace Mindee\Error; +use Mindee\V2\Parsing\ErrorItem; use Mindee\V2\Parsing\ErrorResponse; /** @@ -29,7 +30,7 @@ class MindeeV2HttpException extends MindeeException */ public ?string $errorCode; /** - * @var array List of associated errors. + * @var array List of associated errors. */ public array $errors; diff --git a/src/Extraction/ExtractedImage.php b/src/Extraction/ExtractedImage.php index 1725f366..d7a694e6 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Extraction/ExtractedImage.php @@ -47,7 +47,7 @@ class ExtractedImage /** * Initializes a new instance of the ExtractedImage class. * - * @param mixed $image The extracted image. Not explicitly typed as \Imagick to avoid errors. + * @param Imagick $image The extracted image. * @param string $filename The filename for the image. * @param string $saveFormat The format to save the image. * @param integer $pageIndex The page index of the image. @@ -55,7 +55,7 @@ class ExtractedImage * * @throws MindeeUnhandledException Throws if PDF operations aren't supported. */ - public function __construct(mixed $image, string $filename, string $saveFormat, int $pageIndex, int $index) + public function __construct(Imagick $image, string $filename, string $saveFormat, int $pageIndex, int $index) { DependencyChecker::isImageMagickAvailable(); DependencyChecker::isGhostscriptAvailable(); @@ -85,7 +85,7 @@ public function writeToFile(string $outputPath, ?string $format = null, int $qua $quality = min(100, max(0, $quality)); if ('png' === $format) { $finalQuality = round($quality * 0.09); - $this->image->setOption('png:compression-level', $finalQuality); + $this->image->setOption('png:compression-level', (string) $finalQuality); } elseif (in_array($format, ['jpg', 'jpeg'], true)) { $this->image->setImageCompression(Imagick::COMPRESSION_JPEG); } diff --git a/src/Extraction/ImageExtractor.php b/src/Extraction/ImageExtractor.php index 498c1df7..80512d48 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Extraction/ImageExtractor.php @@ -4,6 +4,7 @@ namespace Mindee\Extraction; +use Exception; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeGeometryException; @@ -11,6 +12,7 @@ use Mindee\Error\MindeePDFException; use Mindee\Geometry\BBox; use Mindee\Geometry\BBoxUtils; +use Mindee\Geometry\Point; use Mindee\Geometry\Polygon; use Mindee\Input\LocalInputSource; use Mindee\V1\Parsing\Standard\BaseField; @@ -129,11 +131,11 @@ public function getPageCount(): int /** * Extract multiple images on a given page from a list of fields having position data. * - * @param array $fields List of Fields to extract. + * @param array> $fields List of Fields to extract. * @param integer $pageIndex The page index to extract, begins at 0. * @param null|string $outputName The base output filename, must have an image extension. * - * @return array a list of extracted images + * @return array a list of extracted images */ public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array { @@ -144,12 +146,12 @@ public function extractImagesFromPage(array $fields, int $pageIndex, ?string $ou /** * Extracts images from a page. * - * @param array $polygons List of polygons to extract. + * @param array> $polygons List of polygons to extract. * @param integer $pageIndex The page index to extract, begins at 0. * @param null|string $filenamePrefix Output filename prefix. * @param null|string $format Save format for extracted images. Defaults to the original format. * - * @return array an array of created images + * @return array An array of created images * @throws MindeeImageException Throws if the image can't be processed. */ public function extractPolygonsFromPage( @@ -173,7 +175,7 @@ public function extractPolygonsFromPage( $saveFormat ); } - } catch (ImagickException $e) { + } catch (Exception $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } @@ -205,16 +207,15 @@ public function extractPolygonFromPage( } catch (ImagickException $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } - $filename ??= $this->filename; $format ??= $this->saveFormat; - $filename ??= sprintf('%s.%s_page%d-%d.%s', $filename, $format, $pageIndex, $index, $format); + $filename ??= sprintf('%s_page%d-%d.%s', $this->filename, $pageIndex, $index, $format); return new ExtractedImage($extractedImageData, $filename, $format, $pageIndex, $index); } /** * Extracts a single image from a Position field. * - * @param BaseField $field The field to extract. + * @param BaseField $field The field to extract. * @param integer $pageIndex The page index to extract, begins at 0. * @param integer $index The index to use for naming the extracted image. * @param string $filename The output filename. @@ -264,16 +265,15 @@ public function getInputSource(): LocalInputSource /** * Extracts images from a page. * - * @param array $fields List of Fields to extract. + * @param array> $fields List of Fields to extract. * @param integer $pageIndex The page index to extract, begins at 0. * @param string $outputName Name of the created file. * @param string $format The output format. * - * @return array an array of created images + * @return array An array of created images */ protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array { - $format ??= $this->saveFormat; $extractedImages = []; $i = 0; @@ -316,7 +316,7 @@ protected function extractImageFromBbox(BBox $bbox, int|float $pageIndex): Imagi * Splits the filename into name and extension. * * @param string $filename Name of the file. - * @return array An array containing the name and extension of the file. + * @return array{0: string, 1: string} An array containing the name and extension of the file. */ protected static function splitNameStrict(string $filename): array { diff --git a/src/Extraction/PDFExtractor.php b/src/Extraction/PDFExtractor.php index a11f7fb1..bffe885c 100644 --- a/src/Extraction/PDFExtractor.php +++ b/src/Extraction/PDFExtractor.php @@ -86,14 +86,14 @@ public function getPageCount(): int /** * Extracts sub-documents from the source document using list of page indexes. * - * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * * @return ExtractedPDF[] list of extracted documents * * @throws MindeePDFException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. * @throws InvalidArgumentException Throws if invalid indexes are provided. */ - public function extractSubDocuments(mixed $pageIndexes): array + public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes): array { $extractedPdfs = []; @@ -141,12 +141,12 @@ public function extractSubDocuments(mixed $pageIndexes): array /** * Extracts invoices as complete PDFs from the document. * - * @param array|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * @param boolean $strict Whether to trust confidence scores or not. * * @return ExtractedPDF[] a list of extracted invoices */ - public function extractInvoices(mixed $pageIndexes, bool $strict = false): array + public function extractInvoices(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes, bool $strict = false): array { if (empty($pageIndexes)) { return []; diff --git a/src/Geometry/BBox.php b/src/Geometry/BBox.php index e6ebac3c..dd0c6d32 100644 --- a/src/Geometry/BBox.php +++ b/src/Geometry/BBox.php @@ -83,9 +83,9 @@ public function getMaxY(): float /** * Extends the BBox with the provided points. * - * @param array|Polygon $points Series of points to add to the BBox. + * @param array|Polygon $points Series of points to add to the BBox. */ - public function extendWith(Polygon|array $points): void + public function extendWith(array|Polygon $points): void { if ($points instanceof Polygon) { $sequence = $points->getCoordinates(); diff --git a/src/Geometry/BBoxUtils.php b/src/Geometry/BBoxUtils.php index af3a4ec6..b089f996 100644 --- a/src/Geometry/BBoxUtils.php +++ b/src/Geometry/BBoxUtils.php @@ -30,31 +30,27 @@ public static function generateBBoxFromPolygon(Polygon $polygon): ?BBox /** * Generates a BBox from an array of polygons. Returns null if no polygons are provided. * - * @param array $polygons Series of polygons to get the BBox of. + * @param array $polygons Series of polygons to get the BBox of. */ public static function generateBBoxFromPolygons(array $polygons): ?BBox { - if (!$polygons) { - return null; - } - $merged = $polygons[0]; + $bboxes = []; + foreach ($polygons as $polygon) { - if ($polygon && $merged !== $polygon) { - $merged = PolygonUtils::merge($merged, $polygon); + if (null === $polygon || !$polygon->getCoordinates()) { + continue; } + + $bboxes[] = self::generateBBoxFromPolygon($polygon); } - return new BBox( - $merged->getMinX(), - $merged->getMaxX(), - $merged->getMinY(), - $merged->getMaxY(), - ); + + return self::mergeBBoxes($bboxes); } /** * Merges an array of bboxes. * - * @param array $bboxes BBoxes to merge. + * @param array $bboxes BBoxes to merge. */ public static function mergeBBoxes(array $bboxes): ?BBox { diff --git a/src/Geometry/MinMaxUtils.php b/src/Geometry/MinMaxUtils.php index 55f30026..1c1b9331 100644 --- a/src/Geometry/MinMaxUtils.php +++ b/src/Geometry/MinMaxUtils.php @@ -17,11 +17,14 @@ class MinMaxUtils /** * Retrieves the upper and lower bounds of the y-axis from an array of points. * - * @param array $points An array of points. + * @param array|Polygon $points An array of points. * @throws MindeeGeometryException Throws if the provided array is too small. */ - public static function getMinMaxY(array $points): MinMax + public static function getMinMaxY(array|Polygon $points): MinMax { + if ($points instanceof Polygon) { + $points = $points->getCoordinates(); + } if (count($points) < 1) { throw new MindeeGeometryException( 'The provided point array must have at least 1 point to calculate the Y bounds.', @@ -38,11 +41,14 @@ public static function getMinMaxY(array $points): MinMax /** * Retrieves the upper and lower bounds of the x-axis from an array of points. * - * @param array $points An array of points. + * @param array|Polygon $points An array of points. * @throws MindeeGeometryException Throws if the provided array is too small. */ - public static function getMinMaxX(array $points): MinMax + public static function getMinMaxX(array|Polygon $points): MinMax { + if ($points instanceof Polygon) { + $points = $points->getCoordinates(); + } if (count($points) < 1) { throw new MindeeGeometryException( 'The provided point array must have at least 1 point to calculate the X bounds.', diff --git a/src/Geometry/Point.php b/src/Geometry/Point.php index 99c93529..57906202 100644 --- a/src/Geometry/Point.php +++ b/src/Geometry/Point.php @@ -5,10 +5,13 @@ namespace Mindee\Geometry; use ArrayAccess; +use BadMethodCallException; use InvalidArgumentException; /** * Representation of the coordinates of a point. + * + * @implements ArrayAccess */ class Point implements ArrayAccess { @@ -101,12 +104,6 @@ public function offsetSet($offset, $value): void */ public function offsetUnset($offset): void { - if ($offset === 0) { - $this->x = null; - } elseif ($offset === 1) { - $this->y = null; - } else { - throw new InvalidArgumentException("Use 0 for X or 1 for Y"); - } + throw new BadMethodCallException("Cannot unset coordinates of a Point."); } } diff --git a/src/Geometry/Polygon.php b/src/Geometry/Polygon.php index b458eec0..75aad681 100644 --- a/src/Geometry/Polygon.php +++ b/src/Geometry/Polygon.php @@ -12,7 +12,7 @@ class Polygon { /** - * @var Point[]|null Vertices of the polygon. + * @var array|null Vertices of the polygon. */ public ?array $coordinates; @@ -27,7 +27,7 @@ class Polygon private MinMax $minMaxX; /** - * @param array|null $coordinates Coordinates of the polygon as a set of Points. + * @param array>|array|null $coordinates Coordinates of the polygon as a set of Points. */ public function __construct(?array $coordinates = null) { @@ -146,7 +146,7 @@ public function isEmpty(): bool /** * Retrieves the coordinates of the polygon. - * + * @return array|null Coordinates of the polygon. */ public function getCoordinates(): ?array { diff --git a/src/Geometry/PolygonUtils.php b/src/Geometry/PolygonUtils.php index 02297b28..3668b3ec 100644 --- a/src/Geometry/PolygonUtils.php +++ b/src/Geometry/PolygonUtils.php @@ -17,10 +17,13 @@ abstract class PolygonUtils /** * Gets the centroid (Point) of a set of points. * - * @param array $vertices Array of points. + * @param array|Polygon $vertices Array of points. */ - public static function getCentroid(array $vertices): Point + public static function getCentroid(array|Polygon $vertices): Point { + if ($vertices instanceof Polygon) { + $vertices = $vertices->getCoordinates(); + } $verticesSum = count($vertices); $xSum = 0.0; @@ -45,7 +48,7 @@ public static function getCentroid(array $vertices): Point public static function compareOnY(Polygon $polygon1, Polygon $polygon2): int { $sort = ($polygon1->getMinY() - $polygon2->getMinY()); - if ($sort === 0) { + if ($sort === 0.0) { return 0; } return $sort < 0 ? -1 : 1; @@ -106,15 +109,15 @@ public static function createBoundingBoxFrom(Polygon $base, ?Polygon $target = n /** * Generates a quadrilateral Polygon from a given prediction. * - * @param array $prediction Raw prediction array. + * @param array> $rawResponse Raw prediction array. * @throws MindeeGeometryException Throws if the polygon isn't a quadrilateral. */ - public static function quadrilateralFromPrediction(array $prediction): Polygon + public static function quadrilateralFromPrediction(array $rawResponse): Polygon { - if (count($prediction) !== 4) { + if (count($rawResponse) !== 4) { throw new MindeeGeometryException('Prediction must have exactly 4 points.'); } - return new Polygon($prediction); + return new Polygon($rawResponse); } /** diff --git a/src/Image/ImageCompressor.php b/src/Image/ImageCompressor.php index 1051c268..1c6b870f 100644 --- a/src/Image/ImageCompressor.php +++ b/src/Image/ImageCompressor.php @@ -4,12 +4,14 @@ namespace Mindee\Image; +use Imagick; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeImageException; use Mindee\Error\MindeeUnhandledException; use CURLFile; use Exception; +use SplFileObject; /** * Image compressor class to handle image compression. @@ -17,7 +19,7 @@ class ImageCompressor { /** - * @param mixed $inputImage Input image. Accepts SplFileObject, CURLFile, Imagick & resources. + * @param Imagick|SplFileObject|CURLFile|string|resource $inputImage Input image. Accepts SplFileObject, CURLFile, Imagick & resources. * @param integer|null $quality Quality to apply to the image. * @param integer|null $maxWidth Maximum width to constrain the image to. * Defaults to the image's size if unset. @@ -29,7 +31,7 @@ class ImageCompressor * @throws MindeeUnhandledException Throws if one of the dependencies isn't installed. */ public static function compress( - $inputImage, + mixed $inputImage, ?int $quality = 85, ?int $maxWidth = null, ?int $maxHeight = null diff --git a/src/Image/ImageUtils.php b/src/Image/ImageUtils.php index d8330892..43fb6837 100644 --- a/src/Image/ImageUtils.php +++ b/src/Image/ImageUtils.php @@ -21,7 +21,7 @@ class ImageUtils { /** - * @param mixed $image Image handle. + * @param Imagick|SplFileObject|CURLFile|string|resource $image Image handle. * @return Imagick A valid Imagick handle, CURLFile, SplFileObject or resource. * The resulting image is formatted to jpeg. * @throws MindeeImageException Throws if something goes wrong during image conversion. @@ -31,7 +31,6 @@ public static function toMagickImage(mixed $image): Imagick try { if ($image instanceof Imagick) { $imagickHandle = $image; - $imagickHandle->setImageFormat('jpeg'); } elseif ($image instanceof SplFileObject) { $imagickHandle = new Imagick(); $imagickHandle->readImage($image->getRealPath()); @@ -43,7 +42,14 @@ public static function toMagickImage(mixed $image): Imagick $imagickHandle->readImage($image); } elseif (is_resource($image)) { $imagickHandle = new Imagick(); - $imagickHandle->readImageBlob($image); + rewind($image); + $imageData = stream_get_contents($image); + + if ($imageData === false) { + throw new MindeeImageException('Failed to read from image resource.'); + } + + $imagickHandle->readImageBlob($imageData); } else { throw new MindeeImageException( 'Input image must be a SplFileObject, path, resource or Imagick handle.' diff --git a/src/Input/Base64Input.php b/src/Input/Base64Input.php index e38a2c5f..cadbcbe3 100644 --- a/src/Input/Base64Input.php +++ b/src/Input/Base64Input.php @@ -35,7 +35,7 @@ public function __construct(string $strBase64, string $fileName) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/BytesInput.php b/src/Input/BytesInput.php index a5084b16..bc5ad5b4 100644 --- a/src/Input/BytesInput.php +++ b/src/Input/BytesInput.php @@ -35,7 +35,7 @@ public function __construct(string $fileBytes, string $fileName) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/FileInput.php b/src/Input/FileInput.php index 289f2aef..f2bbff0e 100644 --- a/src/Input/FileInput.php +++ b/src/Input/FileInput.php @@ -14,14 +14,14 @@ class FileInput extends LocalInputSource { /** - * @var mixed $file A file-like object compatible with CURLFile. + * @var resource $file A file resource compatible with CURLFile. */ - private mixed $file; + private $file; /** - * @param mixed &$file File reference. + * @param resource &$file File reference. */ - public function __construct(mixed &$file) + public function __construct(&$file) { $this->file = &$file; $this->filePath = stream_get_meta_data($this->file)['uri']; @@ -33,21 +33,11 @@ public function __construct(mixed &$file) /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { $fileContents = fread($this->file, filesize($this->filePath)); return [$this->fileName, $fileContents]; } - - /** - * Returns the reference to the file object. Only used for testing purposes. - * - * @return mixed - */ - public function getFilePtr() - { - return $this->file; - } } diff --git a/src/Input/LocalInputSource.php b/src/Input/LocalInputSource.php index 9016e8b9..968a29b4 100644 --- a/src/Input/LocalInputSource.php +++ b/src/Input/LocalInputSource.php @@ -163,7 +163,7 @@ private function saveBytesAsFile(string $fileBytes): void /** * Create a new PDF from pages and set it as the main file object. - * @param array $pageNumbers Array of page numbers to add to the newly created PDF. + * @param array $pageNumbers Array of page numbers to add to the newly created PDF. * @throws MindeePDFException Throws if the pdf file can't be processed. */ public function mergePDFPages(array $pageNumbers): void @@ -222,7 +222,7 @@ public function isPDFEmpty(int $threshold = 1024): bool /** * Reads the contents of the file. - * + * @return array{0: string, 1: string} File name and contents as a tuple. */ public function readContents(): array { diff --git a/src/Input/LocalResponse.php b/src/Input/LocalResponse.php index 62805ef3..6f48dede 100644 --- a/src/Input/LocalResponse.php +++ b/src/Input/LocalResponse.php @@ -4,9 +4,11 @@ namespace Mindee\Input; +use CURLFile; use Exception; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; +use SplFileObject; use function is_array; use function is_resource; @@ -18,54 +20,46 @@ class LocalResponse { /** - * @var mixed $file File object of the local response. + * @var resource $file File object of the local response. */ private $file; /** - * @param mixed $inputFile A string, path or file-like object to load as a local response. + * @param resource|string|array $inputFile A string, path or file-like object to load as a local response. * @throws MindeeException Throws if the input file isn't acceptable. */ public function __construct(mixed $inputFile) { - if (is_resource($inputFile) && get_resource_type($inputFile) === 'file') { - $content = fread($inputFile, filesize($inputFile)); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_resource($inputFile) && get_resource_type($inputFile) === 'stream') { - $content = stream_get_contents($inputFile); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_string($inputFile) && file_exists($inputFile)) { - $content = file_get_contents($inputFile); - $strStripped = str_replace(["\r", "\n"], '', $content); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); + if (is_resource($inputFile)) { + $resourceType = get_resource_type($inputFile); + if ($resourceType === 'file') { + $content = fread($inputFile, fstat($inputFile)['size']); + } elseif ($resourceType === 'stream') { + $content = stream_get_contents($inputFile); + } else { + throw new MindeeException("Unsupported resource type.", ErrorCode::USER_INPUT_ERROR); + } } elseif (is_string($inputFile)) { - $strStripped = str_replace(["\r", "\n"], '', $inputFile); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); - } elseif (is_string($inputFile) || is_array($inputFile)) { - $strStripped = str_replace(["\r", "\n"], '', $inputFile); - $this->file = fopen('php://memory', 'r+'); - fwrite($this->file, $strStripped); - rewind($this->file); + if (file_exists($inputFile) && is_file($inputFile)) { + $content = file_get_contents($inputFile); + } else { + $content = $inputFile; + } + } elseif (is_array($inputFile)) { + $content = implode('', $inputFile); } else { - throw new MindeeException( - "Incompatible type for input.", - ErrorCode::USER_INPUT_ERROR - ); + throw new MindeeException("Incompatible type for input.", ErrorCode::USER_INPUT_ERROR); } + + $strStripped = str_replace(["\r", "\n"], '', (string) $content); + $this->file = fopen('php://memory', 'r+'); + fwrite($this->file, $strStripped); + rewind($this->file); } /** * @throws MindeeException Throws if the file contents cannot be converted to a valid array. + * @return array> The file contents. */ public function toArray(): array { @@ -124,10 +118,9 @@ public function isValidHMACSignature(string $secretKey, string $signature): bool /** * Deserialize the loaded local response into the requested BaseResponse-derived class. * - * Typically used when dealing with V2 webhook callbacks. - * - * @param string $responseClass The class name into which the payload should be deserialized. - * @return mixed An instance of responseClass populated with the file content. + * @template T + * @param class-string $responseClass The class name into which the payload should be deserialized. + * @return T An instance of responseClass populated with the file content. * @throws MindeeException If the provided class cannot be instantiated. */ public function deserializeResponse(string $responseClass): mixed diff --git a/src/Input/PageOptions.php b/src/Input/PageOptions.php index b39a8412..999c6867 100644 --- a/src/Input/PageOptions.php +++ b/src/Input/PageOptions.php @@ -23,7 +23,7 @@ class PageOptions { /** - * @var array|null Indexes of the page to apply the transformations to. + * @var array|null Indexes of the page to apply the transformations to. */ public ?array $pageIndexes; /** @@ -36,7 +36,7 @@ class PageOptions public int $onMinPage; /** - * @param array|null $pageIndexes Indexes of the page. + * @param array|null $pageIndexes Indexes of the page. * @param string $operation Operation to apply. * @param integer $onMinPage Minimum page amount. */ diff --git a/src/PDF/CustomFPDI.php b/src/PDF/CustomFPDI.php index de9ffc07..b72e8645 100644 --- a/src/PDF/CustomFPDI.php +++ b/src/PDF/CustomFPDI.php @@ -19,7 +19,7 @@ class CustomFPDI extends Fpdi /** * @var integer Angle for the rotation. */ - protected $angle = 0; + protected int $angle = 0; /** * Rotates the current drawing context. @@ -30,10 +30,10 @@ class CustomFPDI extends Fpdi */ public function rotate(float $angle, float $x = -1, float $y = -1): void { - if ($x === -1) { + if ((int) $x === -1) { $x = $this->x; } - if ($y === -1) { + if ((int) $y === -1) { $y = $this->y; } @@ -64,7 +64,7 @@ public function rotate(float $angle, float $x = -1, float $y = -1): void * Ends the page, resetting any rotation. * */ - protected function _endpage(): void //phpcs:ignore + protected function _endpage(): void { if ($this->angle !== 0) { $this->angle = 0; @@ -72,6 +72,7 @@ protected function _endpage(): void //phpcs:ignore } parent::_endpage(); } + /** * Starts a new transformation. * @@ -80,6 +81,7 @@ public function startTransform(): void { $this->_out('q'); } + /** * Stops the current transformation. * diff --git a/src/PDF/PDFCompressor.php b/src/PDF/PDFCompressor.php index b244772a..a2681a6f 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/PDF/PDFCompressor.php @@ -11,14 +11,12 @@ use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; use Smalot\PdfParser\Config; -use Smalot\PdfParser\Document; use Smalot\PdfParser\Page; use Smalot\PdfParser\Parser; use CURLFile; use Exception; use Imagick; - -use function count; +use SplFileObject; /** * PDF compression class. @@ -28,7 +26,7 @@ class PDFCompressor /** * Compresses each page of a provided PDF stream. Skips if force_source_text isn't set and source text is detected. * - * @param mixed $input Path to the PDF file. + * @param resource|string|SplFileObject|CURLFile $input Path to the PDF file. * @param integer $quality Compression quality (70-100 for most JPG images in the test dataset). * @param boolean $forceSourceTextCompression If true, attempts to re-write detected text. * @param boolean $disableSourceText If true, doesn't re-apply source text to the original PDF. @@ -37,7 +35,7 @@ class PDFCompressor * @throws MindeeUnhandledException Throws if one of the dependencies isn't installed. */ public static function compress( - $input, + mixed $input, int $quality = 85, bool $forceSourceTextCompression = false, bool $disableSourceText = true @@ -118,7 +116,7 @@ public static function compress( * @param CustomFPDI $outputPdf Output PDF handle. * @throws MindeePDFException Throws if text can't be inserted into the page. */ - private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void + protected static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void { try { $textElements = PDFUtils::extractTextElements($inputPage); @@ -134,85 +132,16 @@ private static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf } } - /** - * Creates the final output PDF, optionally injecting text from the original PDF. - * - * @param CustomFPDI $processedPdf The FPDI object containing the processed pages. - * @param boolean $disableSourceText Whether to disable source text injection. - * @param Document $originalPdf The original PDF document (used for text injection). - * @return string Path to the output PDF file - * @throws MindeePDFException If there's an error creating the output PDF. - */ - private static function createOutputPdf( - CustomFPDI $processedPdf, - bool $disableSourceText, - Document $originalPdf - ): string { - try { - if (!$disableSourceText) { - static::injectText($originalPdf, $processedPdf); - } - - $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; - $processedPdf->Output('F', $outputPath); - - return $outputPath; - } catch (Exception $e) { - throw new MindeePDFException( - "Couldn't create output PDF.", - ErrorCode::PDF_CANT_CREATE, - $e - ); - } - } - - - /** - * Extracts text from a source text PDF, and injects it into a newly-created one. - * - * @param Document $inputPdf Input PDF document. - * @param CustomFPDI $outputPdf The output PDF object. - * @throws MindeePDFException Throws if the text can't be injected. - */ - private static function injectText(Document $inputPdf, CustomFPDI $outputPdf): void - { - try { - $pages = $inputPdf->getPages(); - $pageCount = count($pages); - - for ($i = 1; $i <= $pageCount; $i++) { - $textElements = PDFUtils::extractTextElements($pages[$i - 1]); - - if (!empty($textElements)) { - $tplIdx = $outputPdf->importPage($i); - $size = $outputPdf->getTemplateSize($tplIdx); - $outputPdf->AddPage($size['orientation'], [$size['width'], $size['height']]); - $outputPdf->useTemplate($tplIdx); - foreach ($textElements as $element) { - PDFUtils::addTextElement($outputPdf, $element); - } - } - } - } catch (Exception $e) { - throw new MindeePDFException( - "Couldn't inject text into the new file.", - ErrorCode::PDF_CANT_EDIT, - $e - ); - } - } - - /** * Processes a single PDF page, rasterizing it to a JPEG image. * * @param string $sourcePdfPath Path to the source PDF file. * @param integer $pageIndex The index of the page to process. * @param integer $imageQuality The quality setting for JPEG compression. - * @return array Path to the temporary JPEG file and orientation of the page. + * @return array{0: string, 1: string} Path to the temporary JPEG file and orientation of the page. * @throws MindeePDFException If there's an error processing the page. */ - private static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array + protected static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array { try { $singlePagePdf = new Fpdi(); diff --git a/src/PDF/PDFUtils.php b/src/PDF/PDFUtils.php index 686a88fa..1eb6718c 100644 --- a/src/PDF/PDFUtils.php +++ b/src/PDF/PDFUtils.php @@ -10,6 +10,7 @@ use Mindee\Error\MindeeImageException; use Mindee\Error\MindeePDFException; use Smalot\PdfParser\Config; +use Smalot\PdfParser\Font; use Smalot\PdfParser\Page; use Smalot\PdfParser\Parser; use Imagick; @@ -25,7 +26,7 @@ class PDFUtils { /** - * @param mixed $input Input file. Accepts SplFileObject, Imagick, Curl, resources & paths. + * @param SplFileObject|Imagick|CURLFile|string|resource $input Input file. Accepts SplFileObject, Imagick, Curl, resources & paths. * @return string Path of the file. * @throws MindeePDFException Throws if a path can't be extracted from the input. */ @@ -42,13 +43,18 @@ public static function extractFilePath(mixed $input): string } elseif ($input instanceof CURLFile) { return $input->getFilename(); } elseif (is_resource($input)) { - $imagickHandle = new Imagick(); - $imagickHandle->readImageBlob($input); + $metaData = stream_get_meta_data($input); + if (isset($metaData['uri']) && is_file($metaData['uri'])) { + return $metaData['uri']; + } + rewind($input); + $tempPath = tempnam(sys_get_temp_dir(), 'mindee_ext_') . '.pdf'; + file_put_contents($tempPath, stream_get_contents($input)); + + return $tempPath; } else { throw new MindeePDFException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); } - $imagickHandle->setImageFormat('jpeg'); - return $imagickHandle; } catch (MindeePDFException $e) { throw $e; } catch (Exception $e) { @@ -79,8 +85,8 @@ public static function hasSourceText(string $pdfPath): bool * Extracts text elements with their properties from all pages in a PDF. * * @param string $pdfPath Path to the PDF file. - * @return array An array of arrays, each containing text elements for a page. - * Each text element includes text content, position, font, size, and color. + * @return array A page-indexed array of text elements. + * Each text element includes text content, position, font, size, and color. * @throws MindeePDFException Throws if the PDF can't be parsed or text elements can't be extracted. */ public static function extractPagesTextElements(string $pdfPath): array @@ -122,7 +128,7 @@ public static function downgradePDFVersion(string $inputPath): string try { $outputPath = tempnam(sys_get_temp_dir(), 'downgrade_pdf_') . '.pdf'; $command = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET" - . " -dBATCH -sOutputFile={$outputPath} \"{$inputPath}\""; + . " -dBATCH -sOutputFile=$outputPath \"$inputPath\""; exec($command, $output, $returnCode); @@ -146,14 +152,15 @@ public static function downgradePDFVersion(string $inputPath): string * Extracts text elements with their properties from a PDF page. * * @param Page $page Page object. - * @return array An array of text elements, each containing text content, position, font, size, and color. + * @return array> An array of text elements, each containing text content, + * position, font, size, and color. * @throws MindeePDFException Throws if the text elements can't be extracted. */ public static function extractTextElements(Page $page): array { try { $dataTm = $page->getDataTm(); - } catch (Exception|TypeError $e) { + } catch (Exception|TypeError) { return []; } try { @@ -183,9 +190,9 @@ public static function extractTextElements(Page $page): array /** * @param string $fontName Name of the font/subfont. - * @return array The standard font & possible style. + * @return array{family: string, style: string} The standard font & possible style. */ - private static function standardizeFontName(string $fontName): array + protected static function standardizeFontName(string $fontName): array { $cleanName = preg_replace('/^.*?\+/', '', $fontName); $parts = explode('-', $cleanName, 2); @@ -197,7 +204,7 @@ private static function standardizeFontName(string $fontName): array $fontStyle = ''; } $fontStyle = str_replace(['Bold', 'Italic', 'Oblique'], ['B', 'I', 'I'], $fontStyle); - if (strpos($fontStyle, 'B') !== false && strpos($fontStyle, 'I') !== false) { + if (str_contains($fontStyle, 'B') && str_contains($fontStyle, 'I')) { $fontStyle = 'BI'; } @@ -211,7 +218,7 @@ private static function standardizeFontName(string $fontName): array * Adds a text element to the output PDF. * * @param CustomFPDI $pdf The output PDF object. - * @param array $element Text element array containing text, position, font, size, and color. + * @param array $element Text element array containing text, position, font, size, and color. */ public static function addTextElement(CustomFPDI $pdf, array $element): void { @@ -219,8 +226,8 @@ public static function addTextElement(CustomFPDI $pdf, array $element): void $pageHeight = $pdf->GetPageHeight(); $size = $element['size'] * 3; - $x = $element['x'] - $size / 10; - $y = $pageHeight - $element['y'] - $size / 10; + $x = $element['x'] - $size / 10; + $y = $pageHeight - $element['y'] - $size / 10; $pdf->SetFont($fontInfo['family'], $fontInfo['style'], $size); $pdf->SetTextColor(0, 0, 0); // No currently reliable nor easy way of retrieving text color. diff --git a/src/Parsing/SummaryHelper.php b/src/Parsing/SummaryHelper.php index 76b43d38..2d551ada 100644 --- a/src/Parsing/SummaryHelper.php +++ b/src/Parsing/SummaryHelper.php @@ -20,7 +20,7 @@ class SummaryHelper */ public static function formatFloat(?float $number): string { - if ($number === null) { + if (null === $number) { return ''; } $formatted = number_format($number, 5, '.', ''); @@ -54,7 +54,7 @@ public static function cleanOutString(string $inputString): string */ protected static function escapeSpecialChars(?string $string): ?string { - if ($string === null) { + if (null === $string) { return null; } $find = ["\n", "\t", "\r"]; @@ -77,7 +77,7 @@ public static function formatForDisplay($inputString = null, ?int $maxColSize = return 'False'; } $inputString = self::escapeSpecialChars($inputString); - if (!$inputString || mb_strlen($inputString, "UTF-8") === 0) { + if (!$inputString) { return ""; } if (!isset($maxColSize)) { diff --git a/src/V1/Client.php b/src/V1/Client.php index 5452fad7..c07f9dc3 100644 --- a/src/V1/Client.php +++ b/src/V1/Client.php @@ -10,6 +10,7 @@ namespace Mindee\V1; +use CURLFile; use Exception; use Mindee\ClientOptions\PollingOptions; use Mindee\CustomSleepMixin; @@ -40,6 +41,7 @@ use Mindee\V1\Product\Generated\GeneratedV1; use ReflectionClass; use ReflectionException; +use SplFileObject; use function strlen; @@ -89,7 +91,7 @@ public function sourceFromPath(string $filePath, bool $fixPDF = false): PathInpu /** * Load a document from a normal PHP file object. * - * @param mixed $file File object as created from the file() function. + * @param SplFileObject|CURLFile|string|resource $file File object as created from the file() function. * @param boolean $fixPDF Whether the PDF should be fixed or not. */ public function sourceFromFile(mixed $file, bool $fixPDF = false): FileInput @@ -155,7 +157,7 @@ private function constructEndpoint( string $endpointOwner, string $endpointVersion ): Endpoint { - $endpointVersion = $endpointVersion !== null && strlen($endpointVersion) > 0 ? $endpointVersion : '1'; + $endpointVersion = $endpointVersion !== '' ? $endpointVersion : '1'; $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); @@ -193,7 +195,8 @@ private function constructOTSEndpoint(string $product): Endpoint } catch (ReflectionException $e) { throw new MindeeApiException( "Unable to create custom product " . $product, - ErrorCode::INTERNAL_LIBRARY_ERROR + ErrorCode::INTERNAL_LIBRARY_ERROR, + previous: $e ); } if ($endpointName === 'custom') { @@ -224,7 +227,7 @@ public function createEndpoint(string $endpointName, string $accountName, ?strin ); } $accountName = $this->cleanAccountName($accountName); - if (!$version || $version === '') { + if (empty($version)) { error_log("Notice: no version provided for a custom build, will attempt to poll version 1 by default."); $version = "1"; } @@ -348,7 +351,8 @@ private function makeWorkflowExecutionRequest( } catch (Exception $e) { throw new MindeeApiException( "Unable to create workflow response for $predictionType", - ErrorCode::API_UNPROCESSABLE_ENTITY + ErrorCode::API_UNPROCESSABLE_ENTITY, + previous: $e ); } } @@ -405,7 +409,7 @@ public function parse( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): PredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { @@ -435,10 +439,10 @@ public function enqueueAndParse( ?PollingOptions $asyncOptions = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } - if ($asyncOptions === null) { + if (null === $asyncOptions) { $asyncOptions = new PollingOptions(); } @@ -490,7 +494,7 @@ public function enqueue( ?PredictMethodOptions $options = null, ?PageOptions $pageOptions = null ): AsyncPredictResponse { - if ($options === null) { + if (null === $options) { $options = new PredictMethodOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { @@ -539,7 +543,8 @@ public function loadPrediction( } catch (Exception $e) { throw new MindeeException( "Local response is not a valid prediction.", - ErrorCode::USER_INPUT_ERROR + ErrorCode::USER_INPUT_ERROR, + previous: $e ); } } @@ -558,7 +563,7 @@ public function executeWorkflow( ?WorkflowOptions $options = null, ?PageOptions $pageOptions = null ): WorkflowResponse { - if ($options === null) { + if (null === $options) { $options = new WorkflowOptions(); } if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { diff --git a/src/V1/ClientOptions/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php index b4d6846b..531cbfbb 100644 --- a/src/V1/ClientOptions/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -27,9 +27,8 @@ public function __construct(bool $fullText = false) /** * @param boolean $fullText Whether to include the full text. - * @return $this */ - public function setFullText(bool $fullText): PredictOptions + public function setFullText(bool $fullText): static { $this->fullText = $fullText; return $this; diff --git a/src/V1/HTTP/BaseAPI.php b/src/V1/HTTP/BaseAPI.php index caf35150..457dca2e 100644 --- a/src/V1/HTTP/BaseAPI.php +++ b/src/V1/HTTP/BaseAPI.php @@ -90,15 +90,15 @@ protected function setBaseUrl(string $value): void /** * Sets the default timeout. * - * @param string $value Value for the CURL timeout. + * @param integer $value Value for the CURL timeout. */ - protected function setTimeout(string $value): void + protected function setTimeout(int $value): void { $this->requestTimeout = $value; } /** - * Sets values from environment, if needed. + * Sets values from the environment, if needed. * */ protected function setFromEnv(): void diff --git a/src/V1/HTTP/BaseEndpoint.php b/src/V1/HTTP/BaseEndpoint.php index 1c464083..1c360253 100644 --- a/src/V1/HTTP/BaseEndpoint.php +++ b/src/V1/HTTP/BaseEndpoint.php @@ -4,6 +4,8 @@ namespace Mindee\V1\HTTP; +use CurlHandle; + /** * Abstract class for endpoints. */ @@ -12,20 +14,21 @@ abstract class BaseEndpoint /** * @var MindeeAPI|MindeeWorkflowAPI Settings of the endpoint. */ - public $settings; + public MindeeAPI|MindeeWorkflowAPI $settings; /** * @param MindeeAPI|MindeeWorkflowAPI $settings Input settings. */ - public function __construct($settings) + public function __construct(MindeeAPI|MindeeWorkflowAPI $settings) { $this->settings = $settings; } /** - * Starts a CURL session, using GET. + * Starts a CURL session using GET. * * @param string $queueId ID of the queue to poll. + * @return array{data: string|bool, code: int} */ protected function initCurlSessionGet(string $queueId): array { @@ -56,13 +59,14 @@ protected function initCurlSessionGet(string $queueId): array } /** - * @param resource $ch Curl Channel. + * @param CurlHandle $ch Curl Channel. * @param string $suffix Optional suffix for the url call. - * @param array|null $postFields Post fields. + * @param array|boolean>|null $postFields Post fields. * @param string|null $workflowId Optional ID of the workflow. + * @return array{data: string|bool, code: int} Final response. */ public function setFinalCurlOpts( - $ch, + CurlHandle $ch, string $suffix, ?array $postFields, ?string $workflowId = null diff --git a/src/V1/HTTP/Endpoint.php b/src/V1/HTTP/Endpoint.php index 9c25913a..9b10b6fa 100644 --- a/src/V1/HTTP/Endpoint.php +++ b/src/V1/HTTP/Endpoint.php @@ -4,6 +4,7 @@ namespace Mindee\V1\HTTP; +use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\URLInputSource; @@ -49,6 +50,7 @@ public function __construct( * Retrieves a document from its queue ID. * * @param string $queueId ID of the queue to poll. + * @return array{data: string|bool, code: int} Final response. */ public function documentQueueReqGet(string $queueId): array { @@ -60,6 +62,7 @@ public function documentQueueReqGet(string $queueId): array * * @param InputSource $fileCurl File to upload. * @param PredictMethodOptions $options Prediction Options. + * @return array{data: string|bool, code: int} Final response. */ public function predictRequestPost( InputSource $fileCurl, @@ -73,6 +76,7 @@ public function predictRequestPost( * * @param InputSource $fileCurl File to upload. * @param PredictMethodOptions $options Prediction Options. + * @return array{data: string|bool, code: int} Final response. */ public function predictAsyncRequestPost( InputSource $fileCurl, @@ -87,11 +91,13 @@ public function predictAsyncRequestPost( /** - * Starts a CURL session, using POST. + * Starts a CURL session using POST. * * @param InputSource $inputSource File to upload. * @param PredictMethodOptions $options Prediction Options. * @param boolean $async Whether to use the async endpoint. + * @return array{data: string|bool, code: int} Final response. + * @throws MindeeException Throws if the CURL session couldn't be initialized. */ private function initCurlSessionPost( InputSource $inputSource, @@ -138,6 +144,10 @@ private function initCurlSessionPost( if (!empty($params)) { $suffix .= '?' . http_build_query($params); } + + if (!$ch) { + throw new MindeeException("Curl session initialization failed."); + } return $this->setFinalCurlOpts($ch, $suffix, $postFields, $options->workflowId); } } diff --git a/src/V1/HTTP/MindeeAPI.php b/src/V1/HTTP/MindeeAPI.php index 05ea91e2..89f14fa9 100644 --- a/src/V1/HTTP/MindeeAPI.php +++ b/src/V1/HTTP/MindeeAPI.php @@ -44,7 +44,7 @@ public function __construct( ?string $version = "1" ) { parent::__construct($apiKey); - if (!$this->apiKey || $this->apiKey === '') { + if (empty($this->apiKey)) { throw new MindeeException( "Missing API key for '$endpointName v$version' (belonging to $accountName)," . " check your Client configuration.You can set this using the " diff --git a/src/V1/HTTP/MindeeWorkflowAPI.php b/src/V1/HTTP/MindeeWorkflowAPI.php index 0603dd8e..3f5af199 100644 --- a/src/V1/HTTP/MindeeWorkflowAPI.php +++ b/src/V1/HTTP/MindeeWorkflowAPI.php @@ -30,7 +30,7 @@ public function __construct( string $workflowId ) { parent::__construct($apiKey); - if (!$this->apiKey || $this->apiKey === '') { + if (empty($this->apiKey)) { throw new MindeeException( "Missing API key. Please check your Client configuration.You can set this using the " . API_KEY_ENV_NAME . ' environment variable.', diff --git a/src/V1/HTTP/ResponseValidation.php b/src/V1/HTTP/ResponseValidation.php index 9d1838e7..bd8501c0 100644 --- a/src/V1/HTTP/ResponseValidation.php +++ b/src/V1/HTTP/ResponseValidation.php @@ -19,7 +19,7 @@ class ResponseValidation /** * Checks if the synchronous response is valid. Returns True if the response is valid. * - * @param array $response A response object. + * @param array> $response A response object. * @return boolean */ public static function isValidSyncResponse(array $response): bool @@ -40,7 +40,7 @@ public static function isValidSyncResponse(array $response): bool * Checks if the workflow response is valid. Also checks if it is a valid synchronous response. * Returns True if the response is valid. * - * @param array $response A response array. + * @param array> $response A response array. * @return boolean */ public static function isValidWorkflowResponse(array $response): bool @@ -65,7 +65,7 @@ public static function isValidWorkflowResponse(array $response): bool * Checks if the asynchronous response is valid. Also checks if it is a valid synchronous response. * Returns True if the response is valid. * - * @param array $response A response array. + * @param array> $response A response array. * @return boolean */ public static function isValidAsyncResponse(array $response): bool @@ -89,7 +89,8 @@ public static function isValidAsyncResponse(array $response): bool /** * Checks and corrects the response object depending on the possible kinds of returns. * - * @param array $response An endpoint response array. + * @param array> $response An endpoint response array. + * @return array> A cleaned response array. */ public static function cleanRequestData(array $response): array { diff --git a/src/V1/HTTP/WorkflowEndpoint.php b/src/V1/HTTP/WorkflowEndpoint.php index 71513783..87568786 100644 --- a/src/V1/HTTP/WorkflowEndpoint.php +++ b/src/V1/HTTP/WorkflowEndpoint.php @@ -4,6 +4,7 @@ namespace Mindee\V1\HTTP; +use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\URLInputSource; @@ -28,6 +29,7 @@ public function __construct( * * @param InputSource $fileCurl File to upload. * @param WorkflowOptions $workflowOptions Workflow options. + * @return array{data: string|bool, code: int} Final response. */ public function executeWorkflowRequestPost( InputSource $fileCurl, @@ -42,6 +44,7 @@ public function executeWorkflowRequestPost( * * @param InputSource $fileCurl File to upload. * @param WorkflowOptions $workflowOptions Workflow options. + * @return array{data: string|bool, code: int} Final response. */ private function initCurlSessionPost( InputSource $fileCurl, @@ -88,6 +91,9 @@ private function initCurlSessionPost( if (!empty($params)) { $suffix .= '?' . http_build_query($params); } + if (!$ch) { + throw new MindeeException("Curl session initialization failed."); + } return $this->setFinalCurlOpts($ch, $suffix, $postFields); } } diff --git a/src/V1/Parsing/Common/ApiRequest.php b/src/V1/Parsing/Common/ApiRequest.php index 44a5729e..de86e822 100644 --- a/src/V1/Parsing/Common/ApiRequest.php +++ b/src/V1/Parsing/Common/ApiRequest.php @@ -10,28 +10,28 @@ class ApiRequest { /** - * @var array|mixed Error content, if any. + * @var array>|string|null Error content, if any. */ - public array $error; + public array|string|null $error; /** - * @var array|mixed Information on the target resources + * @var array>|string|null Information on the target resources */ - public array $resources; + public array|string|null $resources; /** - * @var string|mixed Status as sent back by the API. + * @var array>|string Status as sent back by the API. */ - public string $status; + public array|string|null $status; /** - * @var integer|mixed HTTP status code. + * @var integer HTTP status code. */ public int $statusCode; /** - * @var string|mixed + * @var string|null URL of the request. */ - public string $url; + public ?string $url; /** - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/ApiResponse.php b/src/V1/Parsing/Common/ApiResponse.php index f5d12c66..71f5a8a6 100644 --- a/src/V1/Parsing/Common/ApiResponse.php +++ b/src/V1/Parsing/Common/ApiResponse.php @@ -14,12 +14,12 @@ abstract class ApiResponse */ public ApiRequest $apiRequest; /** - * @var array Raw http result. Used for debugging purposes. + * @var array> Raw http result. Used for debugging purposes. */ private array $rawHttp; /** - * @param array $rawResponse Raw prediction array. + * @param array> $rawResponse Raw prediction array. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/AsyncPredictResponse.php b/src/V1/Parsing/Common/AsyncPredictResponse.php index ec2e870e..68577d52 100644 --- a/src/V1/Parsing/Common/AsyncPredictResponse.php +++ b/src/V1/Parsing/Common/AsyncPredictResponse.php @@ -25,7 +25,7 @@ class AsyncPredictResponse extends ApiResponse /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/V1/Parsing/Common/Document.php b/src/V1/Parsing/Common/Document.php index e2a2da70..57b97bcf 100644 --- a/src/V1/Parsing/Common/Document.php +++ b/src/V1/Parsing/Common/Document.php @@ -19,19 +19,19 @@ class Document { /** - * @var string|mixed Name of the input document. + * @var string Name of the input document. */ public string $filename; /** - * @var Inference|object|string Result of the base inference. + * @var Inference|string Result of the base inference. */ - public Inference $inference; + public Inference|string $inference; /** - * @var string|mixed ID of the document as sent back by the server. + * @var string ID of the document as sent back by the server. */ public string $id; /** - * @var integer|mixed Amount of pages in the document + * @var integer Amount of pages in the document */ public int $nPages; /** @@ -45,7 +45,7 @@ class Document /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. * @throws MindeeApiException Throws if the prediction type isn't recognized. */ public function __construct(string $predictionType, array $rawResponse) @@ -69,7 +69,7 @@ public function __construct(string $predictionType, array $rawResponse) if (array_key_exists("extras", $rawResponse['inference']) && $rawResponse['inference']['extras']) { $this->extras = new Extras($rawResponse['inference']['extras']); } - $this->injectFullTextOcr($rawResponse); + $this->injectFullTextOCR($rawResponse); } /** @@ -89,9 +89,9 @@ public function __toString(): string /** * Injects the results from pages' "full_text_ocr", if present. * - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. */ - private function injectFullTextOcr(array $rawResponse): void + private function injectFullTextOCR(array $rawResponse): void { $pages = $rawResponse['inference']['pages'] ?? []; diff --git a/src/V1/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php index d90e7841..a7837197 100644 --- a/src/V1/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -85,7 +85,7 @@ class Execution /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw execution array. + * @param array> $rawResponse Raw execution array. * @throws Exception|MindeeApiException Throws if one of the objects can't properly be created. */ public function __construct(string $predictionType, array $rawResponse) diff --git a/src/V1/Parsing/Common/ExecutionFile.php b/src/V1/Parsing/Common/ExecutionFile.php index cccbf777..35eddf20 100644 --- a/src/V1/Parsing/Common/ExecutionFile.php +++ b/src/V1/Parsing/Common/ExecutionFile.php @@ -20,7 +20,7 @@ class ExecutionFile public ?string $alias; /** - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. */ public function __construct(array $rawResponse) { diff --git a/src/V1/Parsing/Common/Extras/CropperExtra.php b/src/V1/Parsing/Common/Extras/CropperExtra.php index bf674868..316c1aad 100644 --- a/src/V1/Parsing/Common/Extras/CropperExtra.php +++ b/src/V1/Parsing/Common/Extras/CropperExtra.php @@ -14,12 +14,12 @@ class CropperExtra { /** - * @var array List of all croppings coordiantes. + * @var array List of all croppings coordiantes. */ public array $croppings; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Parsing/Common/Extras/Extras.php b/src/V1/Parsing/Common/Extras/Extras.php index 2533115b..cd053a4b 100644 --- a/src/V1/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -4,7 +4,7 @@ namespace Mindee\V1\Parsing\Common\Extras; -use function PHPUnit\Framework\isEmpty; +use function is_scalar; /** * Extras collection wrapper class. @@ -18,15 +18,15 @@ class Extras */ public ?CropperExtra $cropper; /** - * @var FullTextOcrExtra|null Full text OCR extra. + * @var FullTextOCRExtra|null Full text OCR extra. */ - public ?FullTextOcrExtra $fullTextOcr; + public ?FullTextOCRExtra $fullTextOcr; /** - * @var RagExtra|null Rag Extra. + * @var RAGExtra|null Rag Extra. */ - public ?RagExtra $rag; + public ?RAGExtra $rag; /** - * @var array Other extras. + * @var array> Other extras. */ private array $data; @@ -34,15 +34,15 @@ class Extras * Sets a field. * * @param string $varName Name of the field to set. - * @param mixed $value Value to set the field with. + * @param integer|float|string|boolean|null|array $value Value to set the field with. */ - public function __set(string $varName, mixed $value): void + public function __set(string $varName, int|float|string|bool|array|null $value): void { $this->data[$varName] = $value; } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -50,8 +50,8 @@ public function __construct(array $rawPrediction) if ($key === 'cropper' && isset($rawPrediction['cropper'])) { $this->cropper = new CropperExtra($rawPrediction['cropper']); } elseif ($key === 'full_text_ocr' && isset($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); - } elseif ($key = 'rag' && isset($rawPrediction['rag'])) { + $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); + } elseif ($key === 'rag' && isset($rawPrediction['rag'])) { $this->rag = new RAGExtra($rawPrediction['rag']); } else { $this->__set($key, $extra); @@ -63,12 +63,12 @@ public function __construct(array $rawPrediction) * Adds artificial extra data for reconstructed extras. * Currently only used for full_text_ocr. * - * @param array $rawPrediction Raw HTTP response. + * @param array> $rawPrediction Raw HTTP response. */ public function addArtificialExtra(array $rawPrediction): void { - if (isset($rawPrediction["full_text_ocr"]) && !isEmpty($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); + if (!empty($rawPrediction['full_text_ocr'])) { + $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); } } @@ -79,8 +79,8 @@ public function __toString() { $resStr = ''; foreach ($this->data as $key => $extra) { - $resStr .= $key . ': ' . $extra; - $resStr .= "\n"; + $safeExtra = is_scalar($extra) ? $extra : json_encode($extra); + $resStr .= $key . ': ' . $safeExtra . "\n"; } if ($this->cropper) { $resStr .= ":cropper:" . $this->cropper . "\n"; diff --git a/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php b/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php similarity index 84% rename from src/V1/Parsing/Common/Extras/FullTextOcrExtra.php rename to src/V1/Parsing/Common/Extras/FullTextOCRExtra.php index 8ac7d292..869d8358 100644 --- a/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php @@ -7,7 +7,7 @@ /** * Full Text OCR result. */ -class FullTextOcrExtra +class FullTextOCRExtra { /** * @var string|null Text content of the full text ocr reading. @@ -21,7 +21,7 @@ class FullTextOcrExtra public ?string $language; /** - * @param array $rawPrediction Raw HTTP response. + * @param array> $rawPrediction Raw HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/Extras/RAGExtra.php b/src/V1/Parsing/Common/Extras/RAGExtra.php index 53b4dc7e..4d469c1b 100644 --- a/src/V1/Parsing/Common/Extras/RAGExtra.php +++ b/src/V1/Parsing/Common/Extras/RAGExtra.php @@ -15,7 +15,7 @@ class RAGExtra public ?string $matchingDocumentId; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/Inference.php b/src/V1/Parsing/Common/Inference.php index 768e8d8b..0875c344 100644 --- a/src/V1/Parsing/Common/Inference.php +++ b/src/V1/Parsing/Common/Inference.php @@ -31,7 +31,7 @@ abstract class Inference */ public Prediction $prediction; /** - * @var array A document's pages. + * @var array A document's pages. */ public array $pages; /** @@ -49,21 +49,21 @@ abstract class Inference /** - * @param array $rawInference Raw inference array. + * @param array> $rawResponse Raw inference array. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawInference, ?int $pageId = null) + public function __construct(array $rawResponse, ?int $pageId = null) { $this->isRotationApplied = null; - if (array_key_exists('is_rotation_applied', $rawInference)) { - $this->isRotationApplied = $rawInference['is_rotation_applied']; + if (array_key_exists('is_rotation_applied', $rawResponse)) { + $this->isRotationApplied = $rawResponse['is_rotation_applied']; } - $this->product = new Product($rawInference['product']); + $this->product = new Product($rawResponse['product']); if (isset($pageId)) { $this->pageId = $pageId; } - if (array_key_exists('extras', $rawInference)) { - $this->extras = new Extras($rawInference['extras']); + if (array_key_exists('extras', $rawResponse)) { + $this->extras = new Extras($rawResponse['extras']); } } diff --git a/src/V1/Parsing/Common/Job.php b/src/V1/Parsing/Common/Job.php index fbe468d5..e159e495 100644 --- a/src/V1/Parsing/Common/Job.php +++ b/src/V1/Parsing/Common/Job.php @@ -39,26 +39,30 @@ class Job */ public ?int $millisecsTaken; /** - * @var array|null Information about an error that occurred during the job processing. + * @var array>|null Information about an error that occurred during the job processing. */ public ?array $error; /** - * @param array $rawResponse Raw prediction array. + * @param array> $rawResponse Raw prediction array. * @throws MindeeApiException Throws if a date is faulty. */ public function __construct(array $rawResponse) { try { $this->issuedAt = new DateTimeImmutable($rawResponse['issued_at']); - } catch (Exception $e) { + } catch (Exception) { try { - $this->issuedAt = new DateTimeImmutable(strtotime($rawResponse['issued_at'])); - } catch (Exception $e2) { + $timestamp = strtotime($rawResponse['issued_at']); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->issuedAt = new DateTimeImmutable('@' . $timestamp); + } catch (Exception $e) { throw new MindeeApiException( "Could not create date from " . $rawResponse['issued_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, - $e2 + previous: $e ); } } @@ -72,7 +76,11 @@ public function __construct(array $rawResponse) $this->availableAt = new DateTimeImmutable($rawResponse['available_at']); } catch (Exception $e) { try { - $this->availableAt = new DateTimeImmutable(strtotime($rawResponse['available_at'])); + $timestamp = strtotime($rawResponse['available_at']); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->availableAt = new DateTimeImmutable('@' . $timestamp); } catch (Exception $e2) { throw new MindeeApiException( "Could not create date from " . $rawResponse['available_at'], diff --git a/src/V1/Parsing/Common/OCR/MVisionV1.php b/src/V1/Parsing/Common/OCR/MVisionV1.php index cab967ec..b31688b3 100644 --- a/src/V1/Parsing/Common/OCR/MVisionV1.php +++ b/src/V1/Parsing/Common/OCR/MVisionV1.php @@ -10,12 +10,12 @@ class MVisionV1 { /** - * @var array List of pages. + * @var array List of pages. */ public array $pages; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OCR/OCR.php b/src/V1/Parsing/Common/OCR/OCR.php index 12df313d..afc4746a 100644 --- a/src/V1/Parsing/Common/OCR/OCR.php +++ b/src/V1/Parsing/Common/OCR/OCR.php @@ -18,7 +18,7 @@ class OCR public MVisionV1 $mvisionV1; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { @@ -36,7 +36,7 @@ public function __toString(): string * Finds all lines matching the given regex in the OCR data, indexed by their page. * * @param string $regex The regular expression to match against. - * @return array All lines that match the regex, indexed by their page. + * @return array> All lines that match the regex, indexed by their page. */ public function findLineByRegex(string $regex): array { diff --git a/src/V1/Parsing/Common/OCR/OCRLine.php b/src/V1/Parsing/Common/OCR/OCRLine.php index 29873168..68480840 100644 --- a/src/V1/Parsing/Common/OCR/OCRLine.php +++ b/src/V1/Parsing/Common/OCR/OCRLine.php @@ -12,12 +12,12 @@ class OCRLine { /** - * @var array Words in the line. + * @var array Words in the line. */ private array $words; /** - * @param array $words Words to insert in the line. + * @param array $words Words to insert in the line. */ public function __construct(array $words = []) { diff --git a/src/V1/Parsing/Common/OCR/OCRPage.php b/src/V1/Parsing/Common/OCR/OCRPage.php index efaf492a..3cc1f80a 100644 --- a/src/V1/Parsing/Common/OCR/OCRPage.php +++ b/src/V1/Parsing/Common/OCR/OCRPage.php @@ -13,11 +13,11 @@ class OCRPage { /** - * @var array List of all words. + * @var array List of all words. */ private array $allWords; /** - * @var array List of lines. + * @var array List of lines. */ private array $lines; @@ -71,19 +71,19 @@ public static function getMinMaxY(OCRWord $word1, OCRWord $word2): int /** * Puts all words on the page into an array of lines. - * + * @return array */ private function toLines(): array { $current = null; $indexes = []; $lines = []; - foreach ($this->allWords as $w) { + foreach ($this->allWords as $_) { $line = new OCRLine(); for ($idx = 0; $idx < count($this->allWords); $idx++) { $word = $this->allWords[$idx]; if (!in_array($idx, $indexes, true)) { - if ($current === null) { + if (null === $current) { $current = $word; $indexes[] = $idx; $line = new OCRLine(); @@ -107,7 +107,7 @@ private function toLines(): array /** * Retrieves all lines on the page. - * + * @return array */ public function getAllLines(): array { @@ -119,7 +119,7 @@ public function getAllLines(): array /** * Retrieves all words on the page. - * + * @return array */ public function getAllWords(): array { @@ -127,7 +127,7 @@ public function getAllWords(): array } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OCR/OCRWord.php b/src/V1/Parsing/Common/OCR/OCRWord.php index 24cc03d4..62d8e634 100644 --- a/src/V1/Parsing/Common/OCR/OCRWord.php +++ b/src/V1/Parsing/Common/OCR/OCRWord.php @@ -14,18 +14,18 @@ class OCRWord use FieldPositionMixin; /** - * @var float|mixed The confidence score. + * @var float The confidence score. */ public float $confidence; /** - * @var string|mixed The extracted text. + * @var string The extracted text. */ public string $text; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/OrientationField.php b/src/V1/Parsing/Common/OrientationField.php index 9a8e5a55..c720702b 100644 --- a/src/V1/Parsing/Common/OrientationField.php +++ b/src/V1/Parsing/Common/OrientationField.php @@ -11,16 +11,12 @@ /** * The clockwise rotation to apply (in degrees) to make the image upright. + * @extends BaseField */ class OrientationField extends BaseField { /** - * @var integer Degrees as an integer. - */ - public $value; - - /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -34,7 +30,7 @@ public function __construct( parent::__construct($rawPrediction, $pageId, $reconstructed, $valueKey); $this->value = 0; if (array_key_exists($valueKey, $rawPrediction) && is_numeric($rawPrediction[$valueKey])) { - $this->value = (float) ($rawPrediction[$valueKey]); + $this->value = (int) ($rawPrediction[$valueKey]); if (!in_array($this->value, [0, 90, 180, 270], true)) { $this->value = 0; } diff --git a/src/V1/Parsing/Common/Page.php b/src/V1/Parsing/Common/Page.php index d2aa4626..1fefe6e6 100644 --- a/src/V1/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -6,11 +6,11 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; +use Mindee\Error\MindeeUnsetException; use Mindee\V1\Parsing\Common\Extras\Extras; -use ReflectionClass; -use ReflectionException; use function array_key_exists; +use function is_subclass_of; /** * Base Page object for predictions. @@ -18,7 +18,7 @@ class Page { /** - * @var integer|mixed ID of the current page. + * @var integer ID of the current page. */ public int $id; /** @@ -26,7 +26,7 @@ class Page */ public OrientationField $orientation; /** - * @var Prediction|object Type of Page prediction. + * @var Prediction Type of Page prediction. */ public Prediction $prediction; /** @@ -36,22 +36,21 @@ class Page /** * @param string $predictionType Type of prediction. - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @throws MindeeApiException Throws if the prediction type isn't recognized. + * @throws MindeeUnsetException Throws if a field doesn't appear in the response, through the reflected document + * class. */ public function __construct(string $predictionType, array $rawPrediction) { $this->id = $rawPrediction['id']; - try { - $reflection = new ReflectionClass($predictionType); - $this->prediction = $reflection->newInstance($rawPrediction['prediction'], $this->id); - } catch (ReflectionException $e) { + if (!is_subclass_of($predictionType, Prediction::class)) { throw new MindeeApiException( - "Unable to create custom product " . $predictionType, - ErrorCode::INTERNAL_LIBRARY_ERROR, - $e + "Invalid prediction type " . $predictionType . ", must extend " . Prediction::class, + ErrorCode::INTERNAL_LIBRARY_ERROR ); } + $this->prediction = self::createPrediction($predictionType, $rawPrediction['prediction'], $this->id); if (array_key_exists('orientation', $rawPrediction)) { $this->orientation = new OrientationField($rawPrediction['orientation'], $this->id, false, 'value'); } @@ -60,6 +59,15 @@ public function __construct(string $predictionType, array $rawPrediction) } } + /** + * @param class-string $predictionType Type of prediction. + * @param array> $rawPrediction Raw prediction array. + */ + private static function createPrediction(string $predictionType, array $rawPrediction, int $pageId): Prediction + { + return new $predictionType($rawPrediction, $pageId); + } + /** * @return string String representation. */ diff --git a/src/V1/Parsing/Common/PredictResponse.php b/src/V1/Parsing/Common/PredictResponse.php index a2459ba0..a6278d27 100644 --- a/src/V1/Parsing/Common/PredictResponse.php +++ b/src/V1/Parsing/Common/PredictResponse.php @@ -18,7 +18,7 @@ class PredictResponse extends ApiResponse /** * @param string $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. */ public function __construct(string $predictionType, array $rawResponse) { diff --git a/src/V1/Parsing/Common/Product.php b/src/V1/Parsing/Common/Product.php index 6c130246..f5b9fa90 100644 --- a/src/V1/Parsing/Common/Product.php +++ b/src/V1/Parsing/Common/Product.php @@ -10,16 +10,16 @@ class Product { /** - * @var string|mixed Product's name. + * @var string Product's name. */ public string $name; /** - * @var string|mixed Product's versions. + * @var string Product's versions. */ public string $version; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Parsing/Common/WorkflowResponse.php b/src/V1/Parsing/Common/WorkflowResponse.php index d48543b0..d2cbed59 100644 --- a/src/V1/Parsing/Common/WorkflowResponse.php +++ b/src/V1/Parsing/Common/WorkflowResponse.php @@ -19,7 +19,7 @@ class WorkflowResponse extends ApiResponse /** * @param string|null $predictionType Type of prediction. - * @param array $rawResponse Raw HTTP response. + * @param array> $rawResponse Raw HTTP response. * @throws Exception Throws if the prediction type isn't recognized or if a field can't be deserialized. */ public function __construct(?string $predictionType, array $rawResponse) diff --git a/src/V1/Parsing/Generated/GeneratedListField.php b/src/V1/Parsing/Generated/GeneratedListField.php index d86609b2..dfba11bf 100644 --- a/src/V1/Parsing/Generated/GeneratedListField.php +++ b/src/V1/Parsing/Generated/GeneratedListField.php @@ -17,13 +17,13 @@ class GeneratedListField /** @var integer|null ID of the page the object was found on */ public ?int $pageId; - /** @var array List of values */ + /** @var array List of values */ public array $values = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. + * @param list>> $rawPrediction Array containing the list elements. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -31,7 +31,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $this->pageId = $pageId; foreach ($rawPrediction as $value) { - if (isset($value['page_id'])) { + if (isset($value['page_id']) && is_int($value['page_id'])) { $this->pageId = $value['page_id']; } @@ -41,7 +41,10 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $valueStr = $value; if (isset($valueStr['value'])) { if ( - (is_int($valueStr['value']) || (is_float($value) && floor($value) === $value)) + ( + is_int($valueStr['value']) + || (is_float($valueStr['value']) && floor($valueStr['value']) === $valueStr['value']) + ) && (float) $value['value'] !== 0.0 ) { $valueStr['value'] = $value['value'] . ".0"; @@ -57,11 +60,11 @@ public function __construct(array $rawPrediction, ?int $pageId = null) /** * Get a list of contents. * - * @return array List of contents. + * @return array List of contents. */ public function getContentsList(): array { - return array_map(static fn($v) => (string) ($v ?: ""), $this->values); + return array_map(static fn($v) => (string) $v, $this->values); } /** diff --git a/src/V1/Parsing/Generated/GeneratedObjectField.php b/src/V1/Parsing/Generated/GeneratedObjectField.php index cdff6a03..17f6ff9b 100644 --- a/src/V1/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -4,6 +4,8 @@ namespace Mindee\V1\Parsing\Generated; +use Mindee\Geometry\Polygon; +use Mindee\V1\Parsing\Standard\BaseField; use Mindee\V1\Parsing\Standard\PositionField; use function in_array; @@ -13,6 +15,10 @@ /** * A JSON-like object, with miscellaneous values. + * @property PositionField|null $bounding_box + * @property PositionField|null $polygon + * @property PositionField|null $quadrangle + * @property PositionField|null $rectangle */ class GeneratedObjectField { @@ -25,13 +31,18 @@ class GeneratedObjectField /** @var string|null Raw unprocessed value, as it was sent by the server */ private ?string $rawValue; - /** @var array List of all printable field names */ + /** @var array List of all printable field names */ private array $printableValues; + /** + * @var array|integer|float|string|bool|null> + * Storage for dynamically generated properties. + */ + private array $dynamicProperties = []; /** * Constructor. * - * @param array $rawPrediction Raw prediction data. + * @param array> $rawPrediction Raw prediction data. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -69,6 +80,39 @@ public function __construct(array $rawPrediction, ?int $pageId = null) } } + /** + * Magic getter for dynamic properties. + * + * @param string $name Property name. + * @return mixed + */ + public function __get(string $name) + { + return $this->dynamicProperties[$name] ?? null; + } + + /** + * Magic setter for dynamic properties. + * + * @param string $name Property name. + * @param BaseField|string|integer|boolean|float|null $value Property value. + */ + public function __set(string $name, BaseField|string|int|bool|float|null $value): void + { + $this->dynamicProperties[$name] = $value; + } + + /** + * Magic isset for dynamic properties. + * + * @param string $name Property name. + * @return boolean + */ + public function __isset(string $name): bool + { + return isset($this->dynamicProperties[$name]); + } + /** * Get a string representation of the object. * @@ -94,7 +138,7 @@ public function strLevel(int $level = 0): string foreach ($this->printableValues as $attr) { $value = $this->{$attr}; $strValue = $value !== null ? (string) $value : ""; - $outStr .= "\n{$indent}:{$attr}: {$strValue}"; + $outStr .= "\n$indent:$attr: $strValue"; } return "\n" . $indent . trim($outStr); } @@ -102,7 +146,7 @@ public function strLevel(int $level = 0): string /** * Checks whether a field is a custom object or not. * - * @param array $strDict Input dictionary to check. + * @param array> $strDict Input dictionary to check. * @return boolean Whether the field is a custom object. */ public static function isGeneratedObject(array $strDict): bool diff --git a/src/V1/Parsing/Standard/AddressField.php b/src/V1/Parsing/Standard/AddressField.php index 1825ba4e..d57a5957 100644 --- a/src/V1/Parsing/Standard/AddressField.php +++ b/src/V1/Parsing/Standard/AddressField.php @@ -27,7 +27,7 @@ class AddressField extends StringField public ?string $country; /** - * @param array $rawPrediction Raw prediction array as returned by the Mindee API. + * @param array> $rawPrediction Raw prediction array as returned by the Mindee API. * @param integer|null $pageId Page number for multi-page documents. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the full address value. diff --git a/src/V1/Parsing/Standard/AmountField.php b/src/V1/Parsing/Standard/AmountField.php index 481f8655..ebdb830d 100644 --- a/src/V1/Parsing/Standard/AmountField.php +++ b/src/V1/Parsing/Standard/AmountField.php @@ -8,6 +8,7 @@ /** * A field containing an amount value. + * @extends BaseField */ class AmountField extends BaseField { @@ -15,13 +16,7 @@ class AmountField extends BaseField use FieldPositionMixin; /** - * @var float|null The amount value as a float. - */ - public $value; - - - /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. */ diff --git a/src/V1/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php index d8701c90..467f844a 100644 --- a/src/V1/Parsing/Standard/BaseField.php +++ b/src/V1/Parsing/Standard/BaseField.php @@ -4,30 +4,33 @@ namespace Mindee\V1\Parsing\Standard; +use Mindee\Geometry\Polygon; + use function array_key_exists; /** * Base class for most fields. + * @template T Generic typing for value type handling. */ abstract class BaseField { use FieldConfidenceMixin; /** - * @var mixed|null Raw field value. + * @var T|null Raw field value. */ - public $value; + public mixed $value; /** * @var boolean Whether the field was reconstructed from other fields. */ public bool $reconstructed; /** - * @var integer|mixed|null The document page on which the information was found. + * @var integer|null The document page on which the information was found. */ public ?int $pageId; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -55,7 +58,7 @@ public function __construct( /** * Compares with the value of another field. * - * @param BaseField $obj Field to compare. + * @param BaseField $obj Field to compare. * @return boolean */ public function __compare(self $obj): bool diff --git a/src/V1/Parsing/Standard/BooleanField.php b/src/V1/Parsing/Standard/BooleanField.php index 2784b79b..b353fabe 100644 --- a/src/V1/Parsing/Standard/BooleanField.php +++ b/src/V1/Parsing/Standard/BooleanField.php @@ -8,6 +8,7 @@ /** * A field containing a boolean value. + * @extends BaseField */ class BooleanField extends BaseField { @@ -15,13 +16,7 @@ class BooleanField extends BaseField use FieldPositionMixin; /** - * @var boolean|null Value as string. - */ - public $value; - - - /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/ClassificationField.php b/src/V1/Parsing/Standard/ClassificationField.php index 6b8c25bb..41e04227 100644 --- a/src/V1/Parsing/Standard/ClassificationField.php +++ b/src/V1/Parsing/Standard/ClassificationField.php @@ -6,20 +6,17 @@ /** * Represents a classifier value. + * @extends BaseField */ class ClassificationField extends BaseField { /** - * @var string|mixed|null The classification value. - */ - public $value; - /** - * @var float|mixed The confidence score. + * @var float The confidence score. */ public float $confidence; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/CompanyRegistrationField.php b/src/V1/Parsing/Standard/CompanyRegistrationField.php index 7ebacb0b..87116f31 100644 --- a/src/V1/Parsing/Standard/CompanyRegistrationField.php +++ b/src/V1/Parsing/Standard/CompanyRegistrationField.php @@ -10,19 +10,20 @@ /** * A company registration item. + * @extends BaseField */ class CompanyRegistrationField extends BaseField { use FieldPositionMixin; /** - * @var string|mixed The type of registration. + * @var string The type of registration. */ public string $type; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -60,7 +61,7 @@ public function __toString(): string /** * Returns an array of proper values for the formatting. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Parsing/Standard/DateField.php b/src/V1/Parsing/Standard/DateField.php index f44afa8b..d1b50cfd 100644 --- a/src/V1/Parsing/Standard/DateField.php +++ b/src/V1/Parsing/Standard/DateField.php @@ -12,6 +12,7 @@ /** * A field containing a date value. + * @extends BaseField */ class DateField extends BaseField { @@ -23,11 +24,6 @@ class DateField extends BaseField */ public ?DateTimeImmutable $dateObject; - /** - * @var string|null The raw field value. - */ - public $value; - /** * @var boolean|null Whether the field was computed or retrieved directly from the document. */ @@ -35,7 +31,7 @@ class DateField extends BaseField /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. @@ -57,10 +53,14 @@ public function __construct( if ($this->value) { try { $this->dateObject = new DateTimeImmutable($this->value, new DateTimeZone('UTC')); - } catch (Exception $e) { + } catch (Exception) { try { - $this->dateObject = new DateTimeImmutable(strtotime($this->value), new DateTimeZone('UTC')); - } catch (Exception $e2) { + $timestamp = strtotime($this->value); + if ($timestamp === false) { + throw new Exception("Invalid date format"); + } + $this->dateObject = new DateTimeImmutable('@' . $timestamp); + } catch (Exception $e) { throw new MindeeApiException( "Couldn't create date field from value '" . $this->value . "'", ErrorCode::API_UNPROCESSABLE_ENTITY, diff --git a/src/V1/Parsing/Standard/FieldConfidenceMixin.php b/src/V1/Parsing/Standard/FieldConfidenceMixin.php index 1c8f465a..91d742da 100644 --- a/src/V1/Parsing/Standard/FieldConfidenceMixin.php +++ b/src/V1/Parsing/Standard/FieldConfidenceMixin.php @@ -19,7 +19,7 @@ trait FieldConfidenceMixin /** * Sets the confidence score. * - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ protected function setConfidence(array $rawPrediction): void { diff --git a/src/V1/Parsing/Standard/FieldPositionMixin.php b/src/V1/Parsing/Standard/FieldPositionMixin.php index 5105cbbe..5397eacd 100644 --- a/src/V1/Parsing/Standard/FieldPositionMixin.php +++ b/src/V1/Parsing/Standard/FieldPositionMixin.php @@ -26,7 +26,7 @@ trait FieldPositionMixin /** * Sets the position of a field. * - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ protected function setPosition(array $rawPrediction): void { diff --git a/src/V1/Parsing/Standard/LocaleField.php b/src/V1/Parsing/Standard/LocaleField.php index eddd61db..60919abd 100644 --- a/src/V1/Parsing/Standard/LocaleField.php +++ b/src/V1/Parsing/Standard/LocaleField.php @@ -8,6 +8,7 @@ /** * The locale detected on the document. + * @extends BaseField */ class LocaleField extends BaseField { @@ -25,7 +26,7 @@ class LocaleField extends BaseField public ?string $currency; /** - * @param array $localePrediction Raw locale prediction. + * @param array> $localePrediction Raw locale prediction. * @param string $key Name of the prediction key. */ private static function getValue(array $localePrediction, string $key): ?string @@ -38,7 +39,7 @@ private static function getValue(array $localePrediction, string $key): ?string } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. */ diff --git a/src/V1/Parsing/Standard/PaymentDetailsField.php b/src/V1/Parsing/Standard/PaymentDetailsField.php index d8be70aa..d584a587 100644 --- a/src/V1/Parsing/Standard/PaymentDetailsField.php +++ b/src/V1/Parsing/Standard/PaymentDetailsField.php @@ -9,6 +9,7 @@ /** * Information on a single payment. + * @extends BaseField */ class PaymentDetailsField extends BaseField { @@ -34,7 +35,7 @@ class PaymentDetailsField extends BaseField /** * Gets the value of any given key. * - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param string $key Key to get the value of. */ private function getValue(array $rawPrediction, string $key): ?string @@ -55,7 +56,7 @@ private function getValue(array $rawPrediction, string $key): ?string } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/PositionField.php b/src/V1/Parsing/Standard/PositionField.php index 22998b46..61453cfc 100644 --- a/src/V1/Parsing/Standard/PositionField.php +++ b/src/V1/Parsing/Standard/PositionField.php @@ -12,13 +12,10 @@ /** * A field indicating a position or area on the document. + * @extends BaseField */ class PositionField extends BaseField { - /** - * @var Polygon|null Polygon of cropped area, identical to the `polygon` property. - */ - public $value; /** * @var Polygon|null Polygon of cropped area. */ @@ -39,16 +36,12 @@ class PositionField extends BaseField /** * Retrieves the quadrilateral of a prediction. * - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param string $key Key to use for the value. */ private static function getQuadrilateral(array $rawPrediction, string $key): ?Polygon { - if ( - !array_key_exists($key, $rawPrediction) - || $rawPrediction[$key] === null - || $rawPrediction[$key] === [] - ) { + if (empty($rawPrediction[$key])) { return null; } @@ -58,20 +51,20 @@ private static function getQuadrilateral(array $rawPrediction, string $key): ?Po /** * Retrieves the polygon of a prediction. * - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param string $key Key to use for the value. */ private static function getPolygon(array $rawPrediction, string $key): ?Polygon { - if (array_key_exists($key, $rawPrediction)) { - return new Polygon($rawPrediction[$key]); + if (!array_key_exists($key, $rawPrediction)) { + return null; } - return null; + return new Polygon($rawPrediction[$key]); } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page id. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/StringField.php b/src/V1/Parsing/Standard/StringField.php index e16b872f..e4463011 100644 --- a/src/V1/Parsing/Standard/StringField.php +++ b/src/V1/Parsing/Standard/StringField.php @@ -8,16 +8,13 @@ /** * A field containing a text value. + * @extends BaseField */ class StringField extends BaseField { use FieldConfidenceMixin; use FieldPositionMixin; - /** - * @var string|null Value as string. - */ - public $value; /** * @var string|null The value as it appears on the document. */ @@ -25,7 +22,7 @@ class StringField extends BaseField /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field was reconstructed. * @param string $valueKey Key to use for the value. diff --git a/src/V1/Parsing/Standard/TaxField.php b/src/V1/Parsing/Standard/TaxField.php index 00aa323e..8225131e 100644 --- a/src/V1/Parsing/Standard/TaxField.php +++ b/src/V1/Parsing/Standard/TaxField.php @@ -9,15 +9,11 @@ /** * Tax line information. + * @extends BaseField */ class TaxField extends BaseField { use FieldPositionMixin; - - /** - * @var float|null The amount of the tax line. - */ - public $value; /** * @var float|null The tax rate. */ @@ -32,7 +28,7 @@ class TaxField extends BaseField public ?float $basis; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. * @param boolean $reconstructed Whether the field has been reconstructed. * @param string $valueKey Key to use for the value. @@ -75,7 +71,7 @@ public function __construct( /** * Returns an array of immediately printable values. * - * @return array Array of printable values. + * @return array Array of printable values. */ private function printableValues(): array { diff --git a/src/V1/Parsing/Standard/Taxes.php b/src/V1/Parsing/Standard/Taxes.php index 935bff89..60479542 100644 --- a/src/V1/Parsing/Standard/Taxes.php +++ b/src/V1/Parsing/Standard/Taxes.php @@ -8,11 +8,12 @@ /** * List of tax lines information. + * @extends ArrayObject */ class Taxes extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) diff --git a/src/V1/Product/BarcodeReader/BarcodeReaderV1.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php index d1fbf6ab..15dc1256 100644 --- a/src/V1/Product/BarcodeReader/BarcodeReaderV1.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1.php @@ -25,7 +25,7 @@ class BarcodeReaderV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php index dfe635b7..22ce3d83 100644 --- a/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php +++ b/src/V1/Product/BarcodeReader/BarcodeReaderV1Document.php @@ -22,8 +22,9 @@ class BarcodeReaderV1Document extends Prediction * @var StringField[] List of decoded 2D barcodes. */ public array $codes2D; + /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -32,14 +33,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["codes_1d"])) { throw new MindeeUnsetException(); } - $this->codes1D = $rawPrediction["codes_1d"] === null ? [] : array_map( + $this->codes1D = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_1d"] ); if (!isset($rawPrediction["codes_2d"])) { throw new MindeeUnsetException(); } - $this->codes2D = $rawPrediction["codes_2d"] === null ? [] : array_map( + $this->codes2D = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["codes_2d"] ); diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1.php b/src/V1/Product/BillOfLading/BillOfLadingV1.php index f5c5ce7c..aadf37d8 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1.php @@ -25,7 +25,7 @@ class BillOfLadingV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php index 41e6fb38..c420113d 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php @@ -28,9 +28,13 @@ class BillOfLadingV1Carrier * @var string|null The Standard Carrier Alpha Code (SCAC) of the carrier. */ public ?string $scac; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->name = $rawPrediction["name"] ?? null; $this->professionalNumber = $rawPrediction["professional_number"] ?? null; $this->scac = $rawPrediction["scac"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php index 6cb3fe62..484a287a 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php @@ -40,9 +40,13 @@ class BillOfLadingV1CarrierItem * @var string|null The unit of measurement for weights. */ public ?string $weightUnit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -58,11 +62,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; $this->weightUnit = $rawPrediction["weight_unit"] ?? null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index fdaeb392..25b1d410 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -8,11 +8,12 @@ /** * The goods being shipped. + * @extends ArrayObject */ class BillOfLadingV1CarrierItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php index 1f9cac83..e3e1c70b 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php @@ -32,9 +32,13 @@ class BillOfLadingV1Consignee * @var string|null The phone number of the consignee. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { @@ -76,7 +67,6 @@ private function printableValues(): array } /** * Output in a format suitable for inclusion in a field list. - * */ public function toFieldList(): string { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php index 591e0709..89cbed52 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php @@ -60,7 +60,7 @@ class BillOfLadingV1Document extends Prediction */ public BillOfLadingV1Shipper $shipper; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -150,10 +150,10 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $shipperToFieldList = $this->shipper !== null ? $this->shipper->toFieldList() : ""; - $consigneeToFieldList = $this->consignee !== null ? $this->consignee->toFieldList() : ""; - $notifyPartyToFieldList = $this->notifyParty !== null ? $this->notifyParty->toFieldList() : ""; - $carrierToFieldList = $this->carrier !== null ? $this->carrier->toFieldList() : ""; + $shipperToFieldList = $this->shipper->toFieldList(); + $consigneeToFieldList = $this->consignee->toFieldList(); + $notifyPartyToFieldList = $this->notifyParty->toFieldList(); + $carrierToFieldList = $this->carrier->toFieldList(); $carrierItemsSummary = (string) ($this->carrierItems); $outStr = ":Bill of Lading Number: $this->billOfLadingNumber diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index 0ad3fd4b..d1ae412d 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -32,9 +32,13 @@ class BillOfLadingV1NotifyParty * @var string|null The phone number of the notify party. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php index bd1aa623..9b0f7b0b 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php @@ -32,9 +32,13 @@ class BillOfLadingV1Shipper * @var string|null The phone number of the shipper. */ public ?string $phone; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/BusinessCard/BusinessCardV1.php b/src/V1/Product/BusinessCard/BusinessCardV1.php index ece609a6..d892d12f 100644 --- a/src/V1/Product/BusinessCard/BusinessCardV1.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1.php @@ -25,7 +25,7 @@ class BusinessCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/BusinessCard/BusinessCardV1Document.php b/src/V1/Product/BusinessCard/BusinessCardV1Document.php index 605a7556..7b273910 100644 --- a/src/V1/Product/BusinessCard/BusinessCardV1Document.php +++ b/src/V1/Product/BusinessCard/BusinessCardV1Document.php @@ -59,7 +59,7 @@ class BusinessCardV1Document extends Prediction */ public StringField $website; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -131,7 +131,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["social_media"])) { throw new MindeeUnsetException(); } - $this->socialMedia = $rawPrediction["social_media"] === null ? [] : array_map( + $this->socialMedia = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["social_media"] ); diff --git a/src/V1/Product/Cropper/CropperV1.php b/src/V1/Product/Cropper/CropperV1.php index 536e8032..5cccfdc3 100644 --- a/src/V1/Product/Cropper/CropperV1.php +++ b/src/V1/Product/Cropper/CropperV1.php @@ -25,12 +25,12 @@ class CropperV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { parent::__construct($rawPrediction); - $this->prediction = new CropperV1Document($rawPrediction['prediction']); + $this->prediction = new CropperV1Document(); $this->pages = []; foreach ($rawPrediction['pages'] as $page) { try { diff --git a/src/V1/Product/Cropper/CropperV1Document.php b/src/V1/Product/Cropper/CropperV1Document.php index d59ac678..684c422e 100644 --- a/src/V1/Product/Cropper/CropperV1Document.php +++ b/src/V1/Product/Cropper/CropperV1Document.php @@ -11,6 +11,11 @@ */ class CropperV1Document extends Prediction { + /** + * Constructor for CropperV1Document. + */ + public function __construct() {} + /** * @return string String representation. */ diff --git a/src/V1/Product/Cropper/CropperV1Page.php b/src/V1/Product/Cropper/CropperV1Page.php index 6fd3297a..bab70808 100644 --- a/src/V1/Product/Cropper/CropperV1Page.php +++ b/src/V1/Product/Cropper/CropperV1Page.php @@ -17,12 +17,12 @@ class CropperV1Page extends CropperV1Document */ public array $cropping; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) { - $this->cropping = $rawPrediction["cropping"] === null ? [] : array_map( + $this->cropping = null === $rawPrediction["cropping"] ? [] : array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["cropping"] ); diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php index cde32f1b..a25d325a 100644 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php @@ -25,7 +25,7 @@ class DeliveryNoteV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php index be6e9440..f8c8d78c 100644 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php +++ b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php @@ -45,7 +45,7 @@ class DeliveryNoteV1Document extends Prediction */ public AmountField $totalAmount; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/DriverLicense/DriverLicenseV1.php b/src/V1/Product/DriverLicense/DriverLicenseV1.php index d78cc2f7..0963c0d8 100644 --- a/src/V1/Product/DriverLicense/DriverLicenseV1.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1.php @@ -25,7 +25,7 @@ class DriverLicenseV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/DriverLicense/DriverLicenseV1Document.php b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php index b0a40d36..bbcb3013 100644 --- a/src/V1/Product/DriverLicense/DriverLicenseV1Document.php +++ b/src/V1/Product/DriverLicense/DriverLicenseV1Document.php @@ -68,7 +68,7 @@ class DriverLicenseV1Document extends Prediction */ public StringField $state; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php index 8290f702..f82c4ea6 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1.php @@ -25,7 +25,7 @@ class FinancialDocumentV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php index 1a153aad..7ce6dc94 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1Document.php @@ -156,7 +156,7 @@ class FinancialDocumentV1Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -186,7 +186,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["customer_company_registrations"])) { throw new MindeeUnsetException(); } - $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : array_map( + $this->customerCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); @@ -284,7 +284,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] === null ? [] : array_map( + $this->referenceNumbers = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); @@ -312,7 +312,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); @@ -333,7 +333,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_payment_details"])) { throw new MindeeUnsetException(); } - $this->supplierPaymentDetails = $rawPrediction["supplier_payment_details"] === null ? [] : array_map( + $this->supplierPaymentDetails = array_map( static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php index 04377842..08822185 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -48,9 +48,13 @@ class FinancialDocumentV1LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -70,11 +74,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -90,23 +95,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index cdfb1ce1..ef29c697 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -8,11 +8,12 @@ /** * List of line item present on the document. + * @extends ArrayObject */ class FinancialDocumentV1LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php index 38a02046..291f4bfd 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1.php @@ -25,7 +25,7 @@ class BankAccountDetailsV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php index ca8e3105..dfc4666e 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV1Document.php @@ -27,7 +27,7 @@ class BankAccountDetailsV1Document extends Prediction */ public StringField $swift; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php index 7fa92f54..ab9dca19 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2.php @@ -25,7 +25,7 @@ class BankAccountDetailsV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index a94f77c0..3b54ac2a 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -32,9 +32,13 @@ class BankAccountDetailsV2Bban * @var string|null The BBAN Account number outputted as a string. */ public ?string $bbanNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -45,25 +49,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bbanBranchCode = $rawPrediction["bban_branch_code"] ?? null; $this->bbanKey = $rawPrediction["bban_key"] ?? null; $this->bbanNumber = $rawPrediction["bban_number"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bbanBankCode"] = SummaryHelperV1::formatForDisplay($this->bbanBankCode); - $outArr["bbanBranchCode"] = SummaryHelperV1::formatForDisplay($this->bbanBranchCode); - $outArr["bbanKey"] = SummaryHelperV1::formatForDisplay($this->bbanKey); - $outArr["bbanNumber"] = SummaryHelperV1::formatForDisplay($this->bbanNumber); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php index 056a1bab..7b951977 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Document.php @@ -31,7 +31,7 @@ class BankAccountDetailsV2Document extends Prediction */ public StringField $swiftCode; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -72,7 +72,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $bbanToFieldList = $this->bban !== null ? $this->bban->toFieldList() : ""; + $bbanToFieldList = $this->bban->toFieldList(); $outStr = ":Account Holder's Names: $this->accountHoldersNames :Basic Bank Account Number: $bbanToFieldList diff --git a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php index 0715991a..8b9a2ed7 100644 --- a/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1.php @@ -25,7 +25,7 @@ class CarteGriseV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php index e3e204a6..7fcd3fad 100644 --- a/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php +++ b/src/V1/Product/Fr/CarteGrise/CarteGriseV1Document.php @@ -180,7 +180,7 @@ class CarteGriseV1Document extends Prediction */ public StringField $y6; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php index deffd538..dce12ef9 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php @@ -25,7 +25,7 @@ class EnergyBillV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php index 64cd5e06..d1c7cbd2 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php @@ -74,7 +74,7 @@ class EnergyBillV1Document extends Prediction */ public AmountField $totalTaxes; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -185,12 +185,12 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $energySupplierToFieldList = $this->energySupplier !== null ? $this->energySupplier->toFieldList() : ""; - $energyConsumerToFieldList = $this->energyConsumer !== null ? $this->energyConsumer->toFieldList() : ""; + $energySupplierToFieldList = $this->energySupplier->toFieldList(); + $energyConsumerToFieldList = $this->energyConsumer->toFieldList(); $subscriptionSummary = (string) ($this->subscription); $energyUsageSummary = (string) ($this->energyUsage); $taxesAndContributionsSummary = (string) ($this->taxesAndContributions); - $meterDetailsToFieldList = $this->meterDetails !== null ? $this->meterDetails->toFieldList() : ""; + $meterDetailsToFieldList = $this->meterDetails->toFieldList(); $outStr = ":Invoice Number: $this->invoiceNumber :Contract ID: $this->contractId diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php index b7bc5164..ea53b24b 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php @@ -24,9 +24,13 @@ class EnergyBillV1EnergyConsumer * @var string|null The name of the energy consumer. */ public ?string $name; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -35,23 +39,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php index 67c60e04..cd0c1df5 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php @@ -24,9 +24,13 @@ class EnergyBillV1EnergySupplier * @var string|null The name of the energy supplier. */ public ?string $name; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -35,23 +39,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php index cce84b0c..d0d6a1c1 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php @@ -48,9 +48,13 @@ class EnergyBillV1EnergyUsage * @var float|null The price per unit of energy consumed. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -62,6 +66,7 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; + $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) @@ -73,7 +78,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -89,23 +94,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 9c782786..889ffbd1 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -8,11 +8,12 @@ /** * Details of energy consumption. + * @extends ArrayObject */ class EnergyBillV1EnergyUsages extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php index 8fcf7d01..2946189f 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php @@ -28,9 +28,13 @@ class EnergyBillV1MeterDetail * @var string|null The unit of power for energy consumption. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->meterNumber = $rawPrediction["meter_number"] ?? null; $this->meterType = $rawPrediction["meter_type"] ?? null; $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php index eb5e4839..9ce540ba 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php @@ -40,9 +40,13 @@ class EnergyBillV1Subscription * @var float|null The price per unit of subscription. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -58,11 +62,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total"]) : null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index 1f2c2416..f9500b5e 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -8,11 +8,12 @@ /** * The subscription details fee for the energy service. + * @extends ArrayObject */ class EnergyBillV1Subscriptions extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php index bbd02fc9..9a3c0daf 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php @@ -40,9 +40,13 @@ class EnergyBillV1TaxesAndContribution * @var float|null The price per unit of Taxes and Contributions. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -52,6 +56,7 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; + $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) @@ -62,7 +67,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -76,21 +81,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 2a0a3e95..207029ed 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php @@ -8,11 +8,12 @@ /** * Details of Taxes and Contributions. + * @extends ArrayObject */ class EnergyBillV1TaxesAndContributions extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1.php b/src/V1/Product/Fr/HealthCard/HealthCardV1.php index c691a051..c4cfa24d 100644 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1.php @@ -25,7 +25,7 @@ class HealthCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php index 92cfc1c6..94fbb8e2 100644 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php +++ b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php @@ -32,7 +32,7 @@ class HealthCardV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -41,7 +41,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV1.php b/src/V1/Product/Fr/IdCard/IdCardV1.php index 9d53b4e3..c992ed76 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1.php @@ -25,7 +25,7 @@ class IdCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV1Document.php b/src/V1/Product/Fr/IdCard/IdCardV1Document.php index 928097a0..d2a59608 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Document.php @@ -55,8 +55,9 @@ class IdCardV1Document extends Prediction * @var StringField The surname of the card holder. */ public StringField $surname; + /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -100,7 +101,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV1Page.php b/src/V1/Product/Fr/IdCard/IdCardV1Page.php index 96024e7b..0b86f4f9 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV1Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV1Page.php @@ -17,7 +17,7 @@ class IdCardV1Page extends IdCardV1Document */ public ClassificationField $documentSide; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/IdCard/IdCardV2.php b/src/V1/Product/Fr/IdCard/IdCardV2.php index 690dfa37..42bf9428 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2.php @@ -25,7 +25,7 @@ class IdCardV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/IdCard/IdCardV2Document.php b/src/V1/Product/Fr/IdCard/IdCardV2Document.php index 32c60cea..3e5582d8 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2Document.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Document.php @@ -76,7 +76,7 @@ class IdCardV2Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -141,7 +141,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Fr/IdCard/IdCardV2Page.php b/src/V1/Product/Fr/IdCard/IdCardV2Page.php index 92824cab..0cb60a67 100644 --- a/src/V1/Product/Fr/IdCard/IdCardV2Page.php +++ b/src/V1/Product/Fr/IdCard/IdCardV2Page.php @@ -21,7 +21,7 @@ class IdCardV2Page extends IdCardV2Document */ public ClassificationField $documentType; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/Payslip/PayslipV3.php b/src/V1/Product/Fr/Payslip/PayslipV3.php index ea597350..643cd7b2 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3.php @@ -25,7 +25,7 @@ class PayslipV3 extends Inference public static string $endpointVersion = "3"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php index 6532cb1a..60abe46b 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php @@ -28,9 +28,13 @@ class PayslipV3BankAccountDetail * @var string|null The SWIFT code of the bank. */ public ?string $swift; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -40,24 +44,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bankName = $rawPrediction["bank_name"] ?? null; $this->iban = $rawPrediction["iban"] ?? null; $this->swift = $rawPrediction["swift"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Document.php b/src/V1/Product/Fr/Payslip/PayslipV3Document.php index 5ad88e01..aee6b047 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Document.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Document.php @@ -46,7 +46,7 @@ class PayslipV3Document extends Prediction */ public PayslipV3SalaryDetails $salaryDetails; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -115,14 +115,13 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $payPeriodToFieldList = $this->payPeriod !== null ? $this->payPeriod->toFieldList() : ""; - $employeeToFieldList = $this->employee !== null ? $this->employee->toFieldList() : ""; - $employerToFieldList = $this->employer !== null ? $this->employer->toFieldList() : ""; - $bankAccountDetailsToFieldList = $this->bankAccountDetails !== null - ? $this->bankAccountDetails->toFieldList() : ""; - $employmentToFieldList = $this->employment !== null ? $this->employment->toFieldList() : ""; + $payPeriodToFieldList = $this->payPeriod->toFieldList(); + $employeeToFieldList = $this->employee->toFieldList(); + $employerToFieldList = $this->employer->toFieldList(); + $bankAccountDetailsToFieldList = $this->bankAccountDetails->toFieldList(); + $employmentToFieldList = $this->employment->toFieldList(); $salaryDetailsSummary = (string) ($this->salaryDetails); - $payDetailToFieldList = $this->payDetail !== null ? $this->payDetail->toFieldList() : ""; + $payDetailToFieldList = $this->payDetail->toFieldList(); $paidTimeOffSummary = (string) ($this->paidTimeOff); $outStr = ":Pay Period: $payPeriodToFieldList diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php index c1d0d17a..cf1a2059 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php @@ -44,9 +44,13 @@ class PayslipV3Employee * @var string|null The social security number of the employee. */ public ?string $socialSecurityNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -57,31 +61,15 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->dateOfBirth = $rawPrediction["date_of_birth"] ?? null; $this->firstName = $rawPrediction["first_name"] ?? null; $this->lastName = $rawPrediction["last_name"] ?? null; + $this->pageId = $pageId; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->registrationNumber = $rawPrediction["registration_number"] ?? null; $this->socialSecurityNumber = $rawPrediction["social_security_number"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php index d3fb3b48..81fbed17 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php @@ -44,9 +44,13 @@ class PayslipV3Employer * @var string|null The URSSAF number of the employer. */ public ?string $urssafNumber; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -60,28 +64,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->name = $rawPrediction["name"] ?? null; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->urssafNumber = $rawPrediction["urssaf_number"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php index 975ffed6..7dd5ce1d 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php @@ -44,9 +44,13 @@ class PayslipV3Employment * @var string|null The start date of the employment. */ public ?string $startDate; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -60,28 +64,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->positionLevel = $rawPrediction["position_level"] ?? null; $this->seniorityDate = $rawPrediction["seniority_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php index 33af14ac..364a9043 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php @@ -36,9 +36,13 @@ class PayslipV3PaidTimeOff * @var float|null The amount of paid time off used in the period. */ public ?float $used; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -53,11 +57,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["remaining"]) : null; $this->used = isset($rawPrediction["used"]) ? (float) ($rawPrediction["used"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -70,20 +75,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); - $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period); - $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType); - $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); - $outArr["used"] = SummaryHelperV1::formatFloat($this->used); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index c6ae3cfe..a7bbbe48 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php @@ -8,11 +8,12 @@ /** * Information about paid time off. + * @extends ArrayObject */ class PayslipV3PaidTimeOffs extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php index ef3f8f45..293191a1 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php @@ -56,9 +56,13 @@ class PayslipV3PayDetail * @var float|null The total taxes and deductions of the employee. */ public ?float $totalTaxesAndDeductions; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -85,31 +89,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total_cost_employer"]) : null; $this->totalTaxesAndDeductions = isset($rawPrediction["total_taxes_and_deductions"]) ? (float) ($rawPrediction["total_taxes_and_deductions"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index bb824668..5b498b84 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -36,9 +36,13 @@ class PayslipV3PayPeriod * @var string|null The year of the pay period. */ public ?string $year; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -50,26 +54,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->paymentDate = $rawPrediction["payment_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; $this->year = $rawPrediction["year"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php index a3c1ec22..06d1bc95 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php @@ -36,9 +36,13 @@ class PayslipV3SalaryDetail * @var float|null The rate of the earning. */ public ?float $rate; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -54,11 +58,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["number"]) : null; $this->rate = isset($rawPrediction["rate"]) ? (float) ($rawPrediction["rate"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -71,20 +76,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["base"] = SummaryHelperV1::formatFloat($this->base); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["number"] = SummaryHelperV1::formatFloat($this->number); - $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index b8534e43..e36b6814 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php @@ -8,11 +8,12 @@ /** * Detailed information about the earnings. + * @extends ArrayObject */ class PayslipV3SalaryDetails extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Generated/GeneratedV1.php b/src/V1/Product/Generated/GeneratedV1.php index 66c8492e..c5bd5fff 100644 --- a/src/V1/Product/Generated/GeneratedV1.php +++ b/src/V1/Product/Generated/GeneratedV1.php @@ -26,7 +26,7 @@ class GeneratedV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Generated/GeneratedV1Document.php b/src/V1/Product/Generated/GeneratedV1Document.php index 93804e73..75711f43 100644 --- a/src/V1/Product/Generated/GeneratedV1Document.php +++ b/src/V1/Product/Generated/GeneratedV1Document.php @@ -17,19 +17,19 @@ */ class GeneratedV1Document extends GeneratedV1Prediction { - /** @var array Dictionary of all fields in the document. */ + /** @var array Dictionary of all fields in the document. */ public array $fields; /** * GeneratedV1Document constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. + * @param array> $rawPrediction Dictionary containing the JSON document response. */ public function __construct(array $rawPrediction) { - parent::__construct($rawPrediction); - $this->fields = []; + parent::__construct(); foreach ($rawPrediction as $fieldName => $fieldContents) { if (is_array($fieldContents) && array_values($fieldContents) === $fieldContents) { + /** @var list>> $fieldContents */ $this->fields[$fieldName] = new GeneratedListField($fieldContents); } elseif (is_array($fieldContents) && GeneratedObjectField::isGeneratedObject($fieldContents)) { $this->fields[$fieldName] = new GeneratedObjectField($fieldContents); diff --git a/src/V1/Product/Generated/GeneratedV1Page.php b/src/V1/Product/Generated/GeneratedV1Page.php index a5ec62e1..fecb23bd 100644 --- a/src/V1/Product/Generated/GeneratedV1Page.php +++ b/src/V1/Product/Generated/GeneratedV1Page.php @@ -17,20 +17,23 @@ */ class GeneratedV1Page extends GeneratedV1Prediction { - /** @var array Dictionary of all fields in the document */ + /** + * @var array Dictionary of all fields in the document. + */ public array $fields; /** * GeneratedV1Page constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. + * @param array> $rawPrediction Dictionary containing the JSON document response. * @param integer|null $pageId ID of the page. */ public function __construct(array $rawPrediction, ?int $pageId = null) { - parent::__construct($rawPrediction); + parent::__construct(); $this->fields = []; foreach ($rawPrediction as $fieldName => $fieldContents) { if (is_array($fieldContents) && array_values($fieldContents) === $fieldContents) { + /** @var list>> $fieldContents */ $this->fields[$fieldName] = new GeneratedListField($fieldContents, $pageId); } elseif (is_array($fieldContents) && GeneratedObjectField::isGeneratedObject($fieldContents)) { $this->fields[$fieldName] = new GeneratedObjectField($fieldContents, $pageId); diff --git a/src/V1/Product/Generated/GeneratedV1Prediction.php b/src/V1/Product/Generated/GeneratedV1Prediction.php index 36381bfd..5b4680bf 100644 --- a/src/V1/Product/Generated/GeneratedV1Prediction.php +++ b/src/V1/Product/Generated/GeneratedV1Prediction.php @@ -26,9 +26,8 @@ class GeneratedV1Prediction extends Prediction /** * GeneratedV1Prediction constructor. - * @param array $rawPrediction Dictionary containing the JSON document response. */ - public function __construct(array $rawPrediction) + public function __construct() { $this->fields = []; } diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php index b28bbcfd..e6672a1c 100644 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php @@ -25,7 +25,7 @@ class IndianPassportV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php index bee6ada5..b23024a6 100644 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php @@ -109,7 +109,7 @@ class IndianPassportV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/InternationalId/InternationalIdV2.php b/src/V1/Product/InternationalId/InternationalIdV2.php index faf9401b..2f000d33 100644 --- a/src/V1/Product/InternationalId/InternationalIdV2.php +++ b/src/V1/Product/InternationalId/InternationalIdV2.php @@ -25,7 +25,7 @@ class InternationalIdV2 extends Inference public static string $endpointVersion = "2"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/InternationalId/InternationalIdV2Document.php b/src/V1/Product/InternationalId/InternationalIdV2Document.php index 9286248c..4c2b607d 100644 --- a/src/V1/Product/InternationalId/InternationalIdV2Document.php +++ b/src/V1/Product/InternationalId/InternationalIdV2Document.php @@ -85,7 +85,7 @@ class InternationalIdV2Document extends Prediction */ public array $surnames; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -143,7 +143,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); @@ -206,7 +206,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["surnames"])) { throw new MindeeUnsetException(); } - $this->surnames = $rawPrediction["surnames"] === null ? [] : array_map( + $this->surnames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); diff --git a/src/V1/Product/Invoice/InvoiceV4.php b/src/V1/Product/Invoice/InvoiceV4.php index 52d05382..7368ef5b 100644 --- a/src/V1/Product/Invoice/InvoiceV4.php +++ b/src/V1/Product/Invoice/InvoiceV4.php @@ -25,7 +25,7 @@ class InvoiceV4 extends Inference public static string $endpointVersion = "4"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Invoice/InvoiceV4Document.php b/src/V1/Product/Invoice/InvoiceV4Document.php index 6e6ef5b3..201f0a6d 100644 --- a/src/V1/Product/Invoice/InvoiceV4Document.php +++ b/src/V1/Product/Invoice/InvoiceV4Document.php @@ -139,7 +139,7 @@ class InvoiceV4Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -169,7 +169,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["customer_company_registrations"])) { throw new MindeeUnsetException(); } - $this->customerCompanyRegistrations = $rawPrediction["customer_company_registrations"] === null ? [] : array_map( + $this->customerCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["customer_company_registrations"] ); @@ -253,7 +253,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["reference_numbers"])) { throw new MindeeUnsetException(); } - $this->referenceNumbers = $rawPrediction["reference_numbers"] === null ? [] : array_map( + $this->referenceNumbers = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["reference_numbers"] ); @@ -281,7 +281,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); @@ -302,7 +302,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_payment_details"])) { throw new MindeeUnsetException(); } - $this->supplierPaymentDetails = $rawPrediction["supplier_payment_details"] === null ? [] : array_map( + $this->supplierPaymentDetails = array_map( static fn($prediction) => new PaymentDetailsField($prediction, $pageId), $rawPrediction["supplier_payment_details"] ); diff --git a/src/V1/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php index 016a73e3..b2e0be1a 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItem.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -48,9 +48,13 @@ class InvoiceV4LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -70,11 +74,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -90,23 +95,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["productCode"] = SummaryHelperV1::formatForDisplay($this->productCode); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["taxAmount"] = SummaryHelperV1::formatFloat($this->taxAmount); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitMeasure"] = SummaryHelperV1::formatForDisplay($this->unitMeasure); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php index 2cd8f84e..2fbbde2c 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -8,11 +8,12 @@ /** * List of all the line items present on the invoice. + * @extends ArrayObject */ class InvoiceV4LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php index aa16bfb9..8f9a4d5d 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1.php @@ -25,7 +25,7 @@ class InvoiceSplitterV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php index 9b4b8e36..d71e14c7 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1Document.php @@ -19,7 +19,7 @@ class InvoiceSplitterV1Document extends Prediction */ public InvoiceSplitterV1InvoicePageGroups $invoicePageGroups; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index 58ca99fe..4ff4da1f 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -20,9 +20,13 @@ class InvoiceSplitterV1InvoicePageGroup * @var int[] List of page indexes that belong to the same invoice (group). */ public array $pageIndexes; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -30,11 +34,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->pageIndexes = $rawPrediction["page_indexes"] ?? []; + $this->pageId = $pageId; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -43,16 +48,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["pageIndexes"] = implode(", ", $this->pageIndexes); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index e45521c7..2b94383e 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -8,11 +8,12 @@ /** * List of page groups. Each group represents a single invoice within a multi-invoice document. + * @extends ArrayObject */ class InvoiceSplitterV1InvoicePageGroups extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php index 5a6c6180..11baf635 100644 --- a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1.php @@ -25,7 +25,7 @@ class MultiReceiptsDetectorV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php index 3ecb87d6..208cc23c 100644 --- a/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php +++ b/src/V1/Product/MultiReceiptsDetector/MultiReceiptsDetectorV1Document.php @@ -19,7 +19,7 @@ class MultiReceiptsDetectorV1Document extends Prediction */ public array $receipts; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -28,7 +28,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["receipts"])) { throw new MindeeUnsetException(); } - $this->receipts = $rawPrediction["receipts"] === null ? [] : array_map( + $this->receipts = array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["receipts"] ); diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php index f966c8cc..067048f5 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php @@ -25,7 +25,7 @@ class NutritionFactsLabelV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php index ebd7881d..be259d4a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php @@ -28,9 +28,13 @@ class NutritionFactsLabelV1AddedSugar * @var float|null The amount of added sugars per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -43,24 +47,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index 25e3f0f5..38c0f12a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -28,9 +28,13 @@ class NutritionFactsLabelV1Calorie * @var float|null The amount of calories per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -43,24 +47,12 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 65d6f30f..001b1eaa 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1Cholesterol * @var float|null The amount of cholesterol per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index 89cfbe7b..a43d850c 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1DietaryFiber * @var float|null The amount of dietary fiber per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php index 27f8f65b..66176a71 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php @@ -71,7 +71,7 @@ class NutritionFactsLabelV1Document extends Prediction */ public NutritionFactsLabelV1TransFat $transFat; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -182,18 +182,18 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $servingSizeToFieldList = $this->servingSize !== null ? $this->servingSize->toFieldList() : ""; - $caloriesToFieldList = $this->calories !== null ? $this->calories->toFieldList() : ""; - $totalFatToFieldList = $this->totalFat !== null ? $this->totalFat->toFieldList() : ""; - $saturatedFatToFieldList = $this->saturatedFat !== null ? $this->saturatedFat->toFieldList() : ""; - $transFatToFieldList = $this->transFat !== null ? $this->transFat->toFieldList() : ""; - $cholesterolToFieldList = $this->cholesterol !== null ? $this->cholesterol->toFieldList() : ""; - $totalCarbohydrateToFieldList = $this->totalCarbohydrate !== null ? $this->totalCarbohydrate->toFieldList() : ""; - $dietaryFiberToFieldList = $this->dietaryFiber !== null ? $this->dietaryFiber->toFieldList() : ""; - $totalSugarsToFieldList = $this->totalSugars !== null ? $this->totalSugars->toFieldList() : ""; - $addedSugarsToFieldList = $this->addedSugars !== null ? $this->addedSugars->toFieldList() : ""; - $proteinToFieldList = $this->protein !== null ? $this->protein->toFieldList() : ""; - $sodiumToFieldList = $this->sodium !== null ? $this->sodium->toFieldList() : ""; + $servingSizeToFieldList = $this->servingSize->toFieldList(); + $caloriesToFieldList = $this->calories->toFieldList(); + $totalFatToFieldList = $this->totalFat->toFieldList(); + $saturatedFatToFieldList = $this->saturatedFat->toFieldList(); + $transFatToFieldList = $this->transFat->toFieldList(); + $cholesterolToFieldList = $this->cholesterol->toFieldList(); + $totalCarbohydrateToFieldList = $this->totalCarbohydrate->toFieldList(); + $dietaryFiberToFieldList = $this->dietaryFiber->toFieldList(); + $totalSugarsToFieldList = $this->totalSugars->toFieldList(); + $addedSugarsToFieldList = $this->addedSugars->toFieldList(); + $proteinToFieldList = $this->protein->toFieldList(); + $sodiumToFieldList = $this->sodium->toFieldList(); $nutrientsSummary = (string) ($this->nutrients); $outStr = ":Serving per Box: $this->servingPerBox diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php index 4eee0bf5..12ce0a9b 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php @@ -36,15 +36,20 @@ class NutritionFactsLabelV1Nutrient * @var string|null The unit of measurement for the amount of nutrients. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->name = $rawPrediction["name"] ?? null; @@ -57,7 +62,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -70,20 +75,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 17cf7bb1..52560227 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php @@ -8,11 +8,12 @@ /** * The amount of nutrients in the product. + * @extends ArrayObject */ class NutritionFactsLabelV1Nutrients extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php index 0bb17e53..ee911866 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1Protein * @var float|null The amount of protein per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index e2b4411c..f35b9369 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1SaturatedFat * @var float|null The amount of saturated fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index a3330f4d..430b015a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -24,9 +24,13 @@ class NutritionFactsLabelV1ServingSize * @var string|null The unit for the amount of a single serving. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) @@ -36,23 +40,12 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->amount = isset($rawPrediction["amount"]) ? (float) ($rawPrediction["amount"]) : null; $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; + $this->pageId = $pageId; } /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index 9a3732d6..95835782 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -32,15 +32,20 @@ class NutritionFactsLabelV1Sodium * @var string|null The unit of measurement for the amount of sodium. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -50,23 +55,9 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unit = $rawPrediction["unit"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index 3f19e755..c08cdbeb 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalCarbohydrate * @var float|null The amount of total carbohydrates per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index d6a9722b..15e37df0 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalFat * @var float|null The amount of total fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index 12efdc4d..e0d18e01 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TotalSugar * @var float|null The amount of total sugars per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { @@ -70,6 +62,7 @@ private function printableValues(): array $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); return $outArr; } + /** * Output in a format suitable for inclusion in a field list. * diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index a62150fa..dbdfbcd0 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -28,15 +28,20 @@ class NutritionFactsLabelV1TransFat * @var float|null The amount of trans fat per serving of the product. */ public ?float $perServing; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) @@ -45,22 +50,9 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_serving"]) : null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V1/Product/Passport/PassportV1.php b/src/V1/Product/Passport/PassportV1.php index a0341058..186113fe 100644 --- a/src/V1/Product/Passport/PassportV1.php +++ b/src/V1/Product/Passport/PassportV1.php @@ -25,7 +25,7 @@ class PassportV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Passport/PassportV1Document.php b/src/V1/Product/Passport/PassportV1Document.php index 455a9b65..a7646bf9 100644 --- a/src/V1/Product/Passport/PassportV1Document.php +++ b/src/V1/Product/Passport/PassportV1Document.php @@ -60,7 +60,7 @@ class PassportV1Document extends Prediction */ public StringField $surname; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -104,7 +104,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); diff --git a/src/V1/Product/Receipt/ReceiptV5.php b/src/V1/Product/Receipt/ReceiptV5.php index 9eb95949..e15354a1 100644 --- a/src/V1/Product/Receipt/ReceiptV5.php +++ b/src/V1/Product/Receipt/ReceiptV5.php @@ -25,7 +25,7 @@ class ReceiptV5 extends Inference public static string $endpointVersion = "5"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Receipt/ReceiptV5Document.php b/src/V1/Product/Receipt/ReceiptV5Document.php index 475fac30..318ac14d 100644 --- a/src/V1/Product/Receipt/ReceiptV5Document.php +++ b/src/V1/Product/Receipt/ReceiptV5Document.php @@ -89,7 +89,7 @@ class ReceiptV5Document extends Prediction */ public AmountField $totalTax; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -154,7 +154,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["supplier_company_registrations"])) { throw new MindeeUnsetException(); } - $this->supplierCompanyRegistrations = $rawPrediction["supplier_company_registrations"] === null ? [] : array_map( + $this->supplierCompanyRegistrations = array_map( static fn($prediction) => new CompanyRegistrationField($prediction, $pageId), $rawPrediction["supplier_company_registrations"] ); diff --git a/src/V1/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php index c20758fc..fbd7e649 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItem.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -32,15 +32,20 @@ class ReceiptV5LineItem * @var float|null The item unit price. */ public ?float $unitPrice; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->description = $rawPrediction["description"] ?? null; $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; @@ -52,7 +57,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -64,19 +69,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["totalAmount"] = SummaryHelperV1::formatFloat($this->totalAmount); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php index 0f2a2ecc..cfc4ceb9 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -8,11 +8,12 @@ /** * List of all line items on the receipt. + * @extends ArrayObject */ class ReceiptV5LineItems extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1.php b/src/V1/Product/Resume/ResumeV1.php index 7d13f62f..69036333 100644 --- a/src/V1/Product/Resume/ResumeV1.php +++ b/src/V1/Product/Resume/ResumeV1.php @@ -25,7 +25,7 @@ class ResumeV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php index e581be91..455398e5 100644 --- a/src/V1/Product/Resume/ResumeV1Certificate.php +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -32,15 +32,20 @@ class ResumeV1Certificate * @var string|null The year when a certificate was issued or received. */ public ?string $year; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->grade = $rawPrediction["grade"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->provider = $rawPrediction["provider"] ?? null; @@ -49,7 +54,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -61,19 +66,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["grade"] = SummaryHelperV1::formatForDisplay($this->grade); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["provider"] = SummaryHelperV1::formatForDisplay($this->provider); - $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php index 07c2c7c3..ca799c88 100644 --- a/src/V1/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -8,11 +8,12 @@ /** * The list of certificates obtained by the candidate. + * @extends ArrayObject */ class ResumeV1Certificates extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1Document.php b/src/V1/Product/Resume/ResumeV1Document.php index 5ae78d24..7eee91e7 100644 --- a/src/V1/Product/Resume/ResumeV1Document.php +++ b/src/V1/Product/Resume/ResumeV1Document.php @@ -84,7 +84,7 @@ class ResumeV1Document extends Prediction */ public array $surnames; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -135,14 +135,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["given_names"])) { throw new MindeeUnsetException(); } - $this->givenNames = $rawPrediction["given_names"] === null ? [] : array_map( + $this->givenNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["given_names"] ); if (!isset($rawPrediction["hard_skills"])) { throw new MindeeUnsetException(); } - $this->hardSkills = $rawPrediction["hard_skills"] === null ? [] : array_map( + $this->hardSkills = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["hard_skills"] ); @@ -198,14 +198,14 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["soft_skills"])) { throw new MindeeUnsetException(); } - $this->softSkills = $rawPrediction["soft_skills"] === null ? [] : array_map( + $this->softSkills = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["soft_skills"] ); if (!isset($rawPrediction["surnames"])) { throw new MindeeUnsetException(); } - $this->surnames = $rawPrediction["surnames"] === null ? [] : array_map( + $this->surnames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["surnames"] ); diff --git a/src/V1/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php index 811f24ed..3b87ff07 100644 --- a/src/V1/Product/Resume/ResumeV1Education.php +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -44,15 +44,20 @@ class ResumeV1Education * @var string|null The year when the education program or course began. */ public ?string $startYear; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->degreeDomain = $rawPrediction["degree_domain"] ?? null; $this->degreeType = $rawPrediction["degree_type"] ?? null; $this->endMonth = $rawPrediction["end_month"] ?? null; @@ -64,7 +69,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -79,22 +84,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["degreeDomain"] = SummaryHelperV1::formatForDisplay($this->degreeDomain); - $outArr["degreeType"] = SummaryHelperV1::formatForDisplay($this->degreeType); - $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); - $outArr["school"] = SummaryHelperV1::formatForDisplay($this->school); - $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php index 7848a327..b4306901 100644 --- a/src/V1/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -8,11 +8,12 @@ /** * The list of the candidate's educational background. + * @extends ArrayObject */ class ResumeV1Educations extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1Language.php b/src/V1/Product/Resume/ResumeV1Language.php index 4a603d66..955085cc 100644 --- a/src/V1/Product/Resume/ResumeV1Language.php +++ b/src/V1/Product/Resume/ResumeV1Language.php @@ -24,22 +24,27 @@ class ResumeV1Language * @var string|null The candidate's level for the language. */ public ?string $level; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->language = $rawPrediction["language"] ?? null; $this->level = $rawPrediction["level"] ?? null; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -49,17 +54,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["language"] = SummaryHelperV1::formatForDisplay($this->language); - $outArr["level"] = SummaryHelperV1::formatForDisplay($this->level); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php index 8587e2b4..f8edf407 100644 --- a/src/V1/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -8,11 +8,12 @@ /** * The list of languages that the candidate is proficient in. + * @extends ArrayObject */ class ResumeV1Languages extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php index 62f3b232..b4941df7 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php @@ -52,15 +52,20 @@ class ResumeV1ProfessionalExperience * @var string|null The year when the professional experience began. */ public ?string $startYear; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->contractType = $rawPrediction["contract_type"] ?? null; $this->department = $rawPrediction["department"] ?? null; $this->description = $rawPrediction["description"] ?? null; @@ -74,7 +79,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -91,24 +96,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["contractType"] = SummaryHelperV1::formatForDisplay($this->contractType); - $outArr["department"] = SummaryHelperV1::formatForDisplay($this->department); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description); - $outArr["employer"] = SummaryHelperV1::formatForDisplay($this->employer); - $outArr["endMonth"] = SummaryHelperV1::formatForDisplay($this->endMonth); - $outArr["endYear"] = SummaryHelperV1::formatForDisplay($this->endYear); - $outArr["role"] = SummaryHelperV1::formatForDisplay($this->role); - $outArr["startMonth"] = SummaryHelperV1::formatForDisplay($this->startMonth); - $outArr["startYear"] = SummaryHelperV1::formatForDisplay($this->startYear); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index c1509b4c..29c3e1af 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -8,11 +8,12 @@ /** * The list of the candidate's professional experiences. + * @extends ArrayObject */ class ResumeV1ProfessionalExperiences extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php index 57c91536..1972668c 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php @@ -24,22 +24,27 @@ class ResumeV1SocialNetworksUrl * @var string|null The URL of the social network. */ public ?string $url; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->name = $rawPrediction["name"] ?? null; $this->url = $rawPrediction["url"] ?? null; } /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -49,17 +54,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["url"] = SummaryHelperV1::formatForDisplay($this->url); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index 162c7eb1..c1d4cc70 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -8,11 +8,12 @@ /** * The list of social network profiles of the candidate. + * @extends ArrayObject */ class ResumeV1SocialNetworksUrls extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1.php b/src/V1/Product/Us/BankCheck/BankCheckV1.php index 6cc17656..3bbdd107 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1.php @@ -25,7 +25,7 @@ class BankCheckV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1Document.php b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php index cfbae322..d8e73b8c 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1Document.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Document.php @@ -41,7 +41,7 @@ class BankCheckV1Document extends Prediction */ public StringField $routingNumber; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -78,7 +78,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["payees"])) { throw new MindeeUnsetException(); } - $this->payees = $rawPrediction["payees"] === null ? [] : array_map( + $this->payees = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["payees"] ); diff --git a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php index 32a80475..b70a8ac0 100644 --- a/src/V1/Product/Us/BankCheck/BankCheckV1Page.php +++ b/src/V1/Product/Us/BankCheck/BankCheckV1Page.php @@ -21,7 +21,7 @@ class BankCheckV1Page extends BankCheckV1Document */ public array $signaturesPositions; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) @@ -31,7 +31,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) $rawPrediction["check_position"], $pageId ); - $this->signaturesPositions = $rawPrediction["signatures_positions"] === null ? [] : array_map( + $this->signaturesPositions = array_map( static fn($prediction) => new PositionField($prediction, $pageId), $rawPrediction["signatures_positions"] ); diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php index 16f992b8..56e67941 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php @@ -25,7 +25,7 @@ class HealthcareCardV1 extends Inference public static string $endpointVersion = "1"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php index 8d451fb0..f1c9d35b 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php @@ -24,15 +24,20 @@ class HealthcareCardV1Copay * @var string|null The name of the service. */ public ?string $serviceName; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->serviceFees = isset($rawPrediction["service_fees"]) ? (float) ($rawPrediction["service_fees"]) : null; $this->serviceName = $rawPrediction["service_name"] ?? null; @@ -40,7 +45,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -50,17 +55,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index 880a53e5..ea4d939f 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php @@ -8,11 +8,12 @@ /** * Copayments for covered services. + * @extends ArrayObject */ class HealthcareCardV1Copays extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php index 20fb58bd..ca70c8ce 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php @@ -72,7 +72,7 @@ class HealthcareCardV1Document extends Prediction */ public StringField $rxPcn; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -95,7 +95,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["dependents"])) { throw new MindeeUnsetException(); } - $this->dependents = $rawPrediction["dependents"] === null ? [] : array_map( + $this->dependents = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["dependents"] ); diff --git a/src/V1/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php index 2a151540..b95325b7 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3.php +++ b/src/V1/Product/Us/UsMail/UsMailV3.php @@ -25,7 +25,7 @@ class UsMailV3 extends Inference public static string $endpointVersion = "3"; /** - * @param array $rawPrediction Raw prediction from the HTTP response. + * @param array> $rawPrediction Raw prediction from the HTTP response. */ public function __construct(array $rawPrediction) { diff --git a/src/V1/Product/Us/UsMail/UsMailV3Document.php b/src/V1/Product/Us/UsMail/UsMailV3Document.php index 58095f7d..276893a4 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3Document.php +++ b/src/V1/Product/Us/UsMail/UsMailV3Document.php @@ -36,7 +36,7 @@ class UsMailV3Document extends Prediction */ public StringField $senderName; /** - * @param array $rawPrediction Raw prediction from HTTP response. + * @param array> $rawPrediction Raw prediction from HTTP response. * @param integer|null $pageId Page number for multi pages document. * @throws MindeeUnsetException Throws if a field doesn't appear in the response. */ @@ -59,7 +59,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) if (!isset($rawPrediction["recipient_names"])) { throw new MindeeUnsetException(); } - $this->recipientNames = $rawPrediction["recipient_names"] === null ? [] : array_map( + $this->recipientNames = array_map( static fn($prediction) => new StringField($prediction, $pageId), $rawPrediction["recipient_names"] ); @@ -84,7 +84,7 @@ public function __construct(array $rawPrediction, ?int $pageId = null) */ public function __toString(): string { - $senderAddressToFieldList = $this->senderAddress !== null ? $this->senderAddress->toFieldList() : ""; + $senderAddressToFieldList = $this->senderAddress->toFieldList(); $recipientNames = implode( "\n ", $this->recipientNames diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index ccfcbf6c..e938d7f6 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -48,15 +48,20 @@ class UsMailV3RecipientAddress * @var string|null The unit number of the recipient's address. */ public ?string $unit; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->isAddressChange = $rawPrediction["is_address_change"] ?? null; @@ -69,7 +74,7 @@ public function __construct(array $rawPrediction, ?int $pageId) /** * Return values for printing inside an RST table. - * + * @return array */ private function tablePrintableValues(): array { @@ -85,23 +90,6 @@ private function tablePrintableValues(): array return $outArr; } - /** - * Return values for printing as an array. - * - */ - private function printableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); - $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } /** * Output in a format suitable for inclusion in an rST table. * diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php index 28362408..03b6a97d 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php @@ -8,11 +8,12 @@ /** * The addresses of the recipients. + * @extends ArrayObject */ class UsMailV3RecipientAddresses extends ArrayObject { /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId = null) diff --git a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php index deba2f0c..ecbde5a3 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php @@ -36,15 +36,20 @@ class UsMailV3SenderAddress * @var string|null The street of the sender's address. */ public ?string $street; + /** + * @var integer|null Page ID. + */ + public ?int $pageId; /** - * @param array $rawPrediction Array containing the JSON document response. + * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ public function __construct(array $rawPrediction, ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); + $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->postalCode = $rawPrediction["postal_code"] ?? null; @@ -52,24 +57,9 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->street = $rawPrediction["street"] ?? null; } - /** - * Return values for printing inside an RST table. - * - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); - return $outArr; - } - /** * Return values for printing as an array. - * + * @return array */ private function printableValues(): array { diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index c54c6b33..796a19d1 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -26,6 +26,11 @@ abstract class BaseParameters */ public array $webhooksIds; + /** + * @var string Slug of the endpoint. + */ + public static string $slug; + /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. @@ -46,7 +51,7 @@ public function __construct(string $modelId, ?string $alias, ?array $webhooksIds } /** - * @return array Hash representation. + * @return array Hash representation. */ public function asHash(): array { @@ -56,7 +61,7 @@ public function asHash(): array } - if (isset($this->webhooksIds) && count($this->webhooksIds) > 0) { + if (!empty($this->webhooksIds)) { $outHash['webhook_ids'] = implode(',', $this->webhooksIds); } return $outHash; diff --git a/src/V2/FileOperations/CropFiles.php b/src/V2/FileOperations/CropFiles.php index 01ad0eee..9f522535 100644 --- a/src/V2/FileOperations/CropFiles.php +++ b/src/V2/FileOperations/CropFiles.php @@ -13,8 +13,7 @@ /** * Cropped files collection wrapper. - * - * * @extends ArrayObject + * @extends ArrayObject */ class CropFiles extends ArrayObject { @@ -44,7 +43,6 @@ public function saveAllToDisk( ?string $fileFormat = null, int $quality = 100 ): void { - $format ??= $fileFormat; $idx = 1; foreach ($this as $crop) { @@ -53,7 +51,7 @@ public function saveAllToDisk( $crop->filename = $filename; try { - $crop->writeToFile($path, $format, $quality); + $crop->writeToFile($path, $fileFormat, $quality); } catch (ImagickException $e) { throw new MindeeException('Failed to save crop to disk.', 0, $e); } diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index 50b11f49..9b9fd0cf 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -16,7 +16,7 @@ /** * Split files collection wrapper. * - * * @extends ArrayObject + * @extends ArrayObject */ class SplitFiles extends ArrayObject { @@ -56,7 +56,7 @@ public function saveAllToDisk(string $path, string $prefix = 'split'): void try { $split->writeToFile($filePath); } catch (Exception $e) { - throw new MindeeException('Failed to save split to disk.', 0, $e->getMessage()); + throw new MindeeException('Failed to save split to disk.', 0, previous: $e); } ++$idx; diff --git a/src/V2/HTTP/MindeeAPIV2.php b/src/V2/HTTP/MindeeAPIV2.php index eba9adf8..28eadd49 100644 --- a/src/V2/HTTP/MindeeAPIV2.php +++ b/src/V2/HTTP/MindeeAPIV2.php @@ -22,7 +22,6 @@ use Mindee\V2\Parsing\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\JobResponse; -use Mindee\V2\Product\Extraction\ExtractionResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; @@ -103,7 +102,7 @@ public function __construct(?string $apiKey) $this->baseUrl = API_V2_BASE_URL_DEFAULT; $this->requestTimeout = API_V2_TIMEOUT_DEFAULT; $this->setFromEnv(); - if (!$this->apiKey || $this->apiKey === '') { + if ($this->apiKey === '') { throw new MindeeException( "Missing API key for call," . " check your Client configuration.You can set this using the " @@ -181,7 +180,7 @@ public function reqPostEnqueue(InputSource $inputDoc, BaseParameters $params): J * @template T of BaseResponse * @param string $responseClass The response class to construct. * @phpstan-param class-string $responseClass - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array> $result Raw HTTP response array with 'data' and 'code' keys. * @return T A response containing parsing results. * @throws MindeeException Throws if HTTP status indicates an error or deserialization fails. */ @@ -210,7 +209,7 @@ private function processResponse( /** * Process the HTTP response and return the appropriate response object. * - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array> $result Raw HTTP response array with 'data' and 'code' keys. * @return JobResponse The processed response object. * @throws MindeeException Throws if HTTP status indicates an error or deserialization fails. * @throws MindeeApiException Throws if the response type is not recognized. @@ -242,11 +241,8 @@ private function processJobResponse(array $result): JobResponse */ public function reqGetJob(string $jobId): JobResponse { - if (!isset($jobId)) { - throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } $response = $this->sendGetRequest($this->baseUrl . "/jobs/$jobId"); - return $this->processJobResponse($response, JobResponse::class); + return $this->processJobResponse($response); } @@ -263,10 +259,6 @@ public function reqGetResult( string $responseClass, string $resultId ): BaseResponse { - if (!isset($responseClass) || !isset($resultId)) { - throw new MindeeException("Response class and job ID must be provided.", ErrorCode::USER_INPUT_ERROR); - } - try { $slugProperty = new ReflectionProperty($responseClass, 'slug'); } catch (ReflectionException $e) { @@ -293,18 +285,15 @@ public function reqGetResultFromUrl( string $responseClass, string $resultUrl ): BaseResponse { - if (!isset($responseClass) || !isset($resultUrl)) { - throw new MindeeException("Response class and result URL must be provided.", ErrorCode::USER_INPUT_ERROR); - } $response = $this->sendGetRequest($resultUrl); return $this->processResponse($responseClass, $response); } /** * Init a CURL channel with common params. - * @return false|resource Returns a valid CURL channel. + * @return boolean|CurlHandle Returns a valid CURL channel. */ - private function initChannel() + private function initChannel(): bool|CurlHandle { $ch = curl_init(); curl_setopt( @@ -326,7 +315,7 @@ private function initChannel() /** * Makes a GET call to retrieve a job. * @param string $url URL of the job. - * @return array Server response. + * @return array> Server response. */ private function sendGetRequest(string $url): array { @@ -347,13 +336,13 @@ private function sendGetRequest(string $url): array * * @param InputSource $inputSource File to upload. * @param BaseParameters $params Parameters. + * @return array> Server response. * @throws MindeeException Throws if the cURL operation doesn't go succeed. */ private function documentEnqueuePost( InputSource $inputSource, BaseParameters $params ): array { - /** @var CurlHandle $ch */ $ch = $this->initChannel(); $postFields = $params->asHash(); @@ -380,7 +369,7 @@ private function documentEnqueuePost( } /** - * @param array $result Raw HTTP response array with 'data' and 'code' keys. + * @param array> $result Raw HTTP response array with 'data' and 'code' keys. * @throws MindeeV2HttpException Throws if the HTTP status indicates an error. * @throws MindeeV2HttpUnknownException Throws if the server sends an unexpected reply. */ diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/BaseInference.php index d25df119..81b2a855 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -35,7 +35,7 @@ abstract class BaseInference public InferenceJob $job; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/ErrorItem.php b/src/V2/Parsing/ErrorItem.php index 75bc17d8..13e0fe52 100644 --- a/src/V2/Parsing/ErrorItem.php +++ b/src/V2/Parsing/ErrorItem.php @@ -19,7 +19,7 @@ class ErrorItem public string $detail; /** - * @param array $rawResponse Raw error response from the API. + * @param array> $rawResponse Raw error response from the API. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/ErrorResponse.php b/src/V2/Parsing/ErrorResponse.php index a4be31a1..fd1236f1 100644 --- a/src/V2/Parsing/ErrorResponse.php +++ b/src/V2/Parsing/ErrorResponse.php @@ -30,21 +30,21 @@ class ErrorResponse */ public ?string $code; /** - * @var array|mixed|null A list of explicit error details. + * @var array|null A list of explicit error details. */ public ?array $errors; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->status = $serverResponse['status']; - $this->detail = $serverResponse['detail']; - $this->title = $serverResponse['title'] ?? null; - $this->code = $serverResponse['code'] ?? null; - if (isset($serverResponse['errors']) && is_array($serverResponse['errors'])) { - $this->errors = array_map(static fn($error) => new ErrorItem($error), $serverResponse['errors']); + $this->status = $rawResponse['status']; + $this->detail = $rawResponse['detail']; + $this->title = $rawResponse['title'] ?? null; + $this->code = $rawResponse['code'] ?? null; + if (isset($rawResponse['errors']) && is_array($rawResponse['errors'])) { + $this->errors = array_map(static fn($error) => new ErrorItem($error), $rawResponse['errors']); } else { $this->errors = []; } diff --git a/src/V2/Parsing/Inference/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php index 5ec3ab3e..341d85ed 100644 --- a/src/V2/Parsing/Inference/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -10,12 +10,12 @@ abstract class BaseResponse { /** - * @var array Raw HTTP response from the server. + * @var array> Raw HTTP response from the server. */ private array $rawHttp; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ protected function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/Inference/Field/BaseField.php b/src/V2/Parsing/Inference/Field/BaseField.php index 39e7a5a4..02d64559 100644 --- a/src/V2/Parsing/Inference/Field/BaseField.php +++ b/src/V2/Parsing/Inference/Field/BaseField.php @@ -29,7 +29,7 @@ abstract class BaseField public ?FieldConfidence $confidence; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer $indentLevel Level of indentation for rst display. */ public function __construct(array $rawPrediction, int $indentLevel = 0) @@ -47,7 +47,7 @@ public function __construct(array $rawPrediction, int $indentLevel = 0) } /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. * @param integer $indentLevel Level of indentation for rst display. * @throws MindeeApiException Throws if the field type isn't recognized. */ @@ -66,4 +66,13 @@ public static function createField(array $rawPrediction, int $indentLevel = 0): sprintf('Unrecognized field format in %s.', json_encode($rawPrediction)) ); } + + /** + * Base str-rep. Do not use. + * @throws MindeeApiException + */ + public function __toString(): string + { + throw new MindeeApiException('Not implemented'); + } } diff --git a/src/V2/Parsing/Inference/Field/FieldLocation.php b/src/V2/Parsing/Inference/Field/FieldLocation.php index ea39cda2..6699af10 100644 --- a/src/V2/Parsing/Inference/Field/FieldLocation.php +++ b/src/V2/Parsing/Inference/Field/FieldLocation.php @@ -27,13 +27,13 @@ class FieldLocation public ?int $page; /** - * @param array $serverResponse Raw server response. + * @param array> $rawResponse Raw server response. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->polygon = isset($serverResponse['polygon']) ? new Polygon($serverResponse['polygon']) : null; - $this->page = isset($serverResponse['page']) && is_int($serverResponse['page']) - ? $serverResponse['page'] + $this->polygon = isset($rawResponse['polygon']) ? new Polygon($rawResponse['polygon']) : null; + $this->page = isset($rawResponse['page']) && is_int($rawResponse['page']) + ? $rawResponse['page'] : null; } diff --git a/src/V2/Parsing/Inference/Field/InferenceFields.php b/src/V2/Parsing/Inference/Field/InferenceFields.php index 871d25ef..7a041273 100644 --- a/src/V2/Parsing/Inference/Field/InferenceFields.php +++ b/src/V2/Parsing/Inference/Field/InferenceFields.php @@ -11,6 +11,7 @@ /** * Collection of inference fields. + * @extends ArrayObject */ class InferenceFields extends ArrayObject { @@ -25,14 +26,14 @@ class InferenceFields extends ArrayObject private int $indentLevel; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { $this->indentLevel = $indentLevel; - foreach ($serverResponse as $key => $value) { + foreach ($rawResponse as $key => $value) { $this->fields[$key] = BaseField::createField($value, 1); } parent::__construct($this->fields); @@ -42,16 +43,11 @@ public function __construct(array $serverResponse, int $indentLevel = 0) * Get a field by key. * * @param string $fieldName Field key to retrieve. - * @return SimpleField|ObjectField|ListField * @throws InvalidArgumentException When the field does not exist. */ - public function get(string $fieldName) + public function get(string $fieldName): SimpleField|ObjectField|ListField { - $field = $this->fields[$fieldName]; - if ($field === null) { - throw new InvalidArgumentException("Field $fieldName does not exist."); - } - return $field; + return $this->fields[$fieldName] ?? throw new InvalidArgumentException("Field $fieldName does not exist."); } /** diff --git a/src/V2/Parsing/Inference/Field/ListField.php b/src/V2/Parsing/Inference/Field/ListField.php index 5fb69016..c92034a5 100644 --- a/src/V2/Parsing/Inference/Field/ListField.php +++ b/src/V2/Parsing/Inference/Field/ListField.php @@ -16,29 +16,27 @@ class ListField extends BaseField { /** - * Items contained in the list. - * - * @var ObjectField + * @var array Items contained in the list. */ public array $items; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. * @throws MindeeApiException Throws if deserialization fails. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); + parent::__construct($rawResponse, $indentLevel); - if (!array_key_exists('items', $serverResponse) || !is_array($serverResponse['items'])) { + if (!array_key_exists('items', $rawResponse) || !is_array($rawResponse['items'])) { throw new MindeeApiException( - sprintf('Expected "items" to be an array in %s.', json_encode($serverResponse)) + sprintf('Expected "items" to be an array in %s.', json_encode($rawResponse)) ); } $this->items = []; - foreach ($serverResponse['items'] as $item) { + foreach ($rawResponse['items'] as $item) { $this->items[] = BaseField::createField($item, $indentLevel + 1); } } @@ -53,7 +51,7 @@ public function __toString(): string $parts = ['']; foreach ($this->items as $item) { - if ($item === null) { + if (null === $item) { continue; } diff --git a/src/V2/Parsing/Inference/Field/ObjectField.php b/src/V2/Parsing/Inference/Field/ObjectField.php index 48425d68..3a156b39 100644 --- a/src/V2/Parsing/Inference/Field/ObjectField.php +++ b/src/V2/Parsing/Inference/Field/ObjectField.php @@ -16,15 +16,15 @@ class ObjectField extends BaseField public InferenceFields $fields; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); + parent::__construct($rawResponse, $indentLevel); $this->fields = new InferenceFields( - $serverResponse['fields'], + $rawResponse['fields'], $this->indentLevel + 1 ); } diff --git a/src/V2/Parsing/Inference/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php index be162ce7..1ba0d69d 100644 --- a/src/V2/Parsing/Inference/Field/SimpleField.php +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -19,13 +19,13 @@ class SimpleField extends BaseField public $value; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $serverResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, int $indentLevel = 0) { - parent::__construct($serverResponse, $indentLevel); - $this->value = array_key_exists('value', $serverResponse) ? $serverResponse['value'] : null; + parent::__construct($rawResponse, $indentLevel); + $this->value = array_key_exists('value', $rawResponse) ? $rawResponse['value'] : null; if (is_int($this->value)) { $this->value = (float) $this->value; } diff --git a/src/V2/Parsing/Inference/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php index edb8ce8d..ff0fbd37 100644 --- a/src/V2/Parsing/Inference/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -50,16 +50,16 @@ class InferenceActiveOptions public DataSchemaActiveOption $dataSchema; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->rag = $serverResponse['rag']; - $this->rawText = $serverResponse['raw_text']; - $this->polygon = $serverResponse['polygon']; - $this->confidence = $serverResponse['confidence']; - $this->textContext = $serverResponse['text_context']; - $this->dataSchema = new DataSchemaActiveOption($serverResponse['data_schema']); + $this->rag = $rawResponse['rag']; + $this->rawText = $rawResponse['raw_text']; + $this->polygon = $rawResponse['polygon']; + $this->confidence = $rawResponse['confidence']; + $this->textContext = $rawResponse['text_context']; + $this->dataSchema = new DataSchemaActiveOption($rawResponse['data_schema']); } /** diff --git a/src/V2/Parsing/Inference/InferenceFile.php b/src/V2/Parsing/Inference/InferenceFile.php index f9ed9674..74251acc 100644 --- a/src/V2/Parsing/Inference/InferenceFile.php +++ b/src/V2/Parsing/Inference/InferenceFile.php @@ -30,14 +30,14 @@ class InferenceFile public string $mimeType; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->name = $serverResponse['name']; - $this->alias = $serverResponse['alias']; - $this->pageCount = $serverResponse['page_count']; - $this->mimeType = $serverResponse['mime_type']; + $this->name = $rawResponse['name']; + $this->alias = $rawResponse['alias']; + $this->pageCount = $rawResponse['page_count']; + $this->mimeType = $rawResponse['mime_type']; } /** diff --git a/src/V2/Parsing/Inference/InferenceJob.php b/src/V2/Parsing/Inference/InferenceJob.php index 4ec2303f..5bc7a552 100644 --- a/src/V2/Parsing/Inference/InferenceJob.php +++ b/src/V2/Parsing/Inference/InferenceJob.php @@ -15,11 +15,11 @@ class InferenceJob public string $id; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; } /** diff --git a/src/V2/Parsing/Inference/InferenceModel.php b/src/V2/Parsing/Inference/InferenceModel.php index 390dfc75..7dbbdf76 100644 --- a/src/V2/Parsing/Inference/InferenceModel.php +++ b/src/V2/Parsing/Inference/InferenceModel.php @@ -15,11 +15,11 @@ class InferenceModel public string $id; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; } /** diff --git a/src/V2/Parsing/Inference/RAGMetadata.php b/src/V2/Parsing/Inference/RAGMetadata.php index b96a07a9..f63935e3 100644 --- a/src/V2/Parsing/Inference/RAGMetadata.php +++ b/src/V2/Parsing/Inference/RAGMetadata.php @@ -15,7 +15,7 @@ class RAGMetadata public ?string $retrievedDocumentId; /** - * @param array $rawResponse Raw response from the server. + * @param array> $rawResponse Raw response from the server. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/Inference/RawText.php b/src/V2/Parsing/Inference/RawText.php index 1afb247f..1f6bf181 100644 --- a/src/V2/Parsing/Inference/RawText.php +++ b/src/V2/Parsing/Inference/RawText.php @@ -17,12 +17,12 @@ class RawText public array $pages; /** - * @param array $serverResponse JSON response from the server. + * @param array> $rawResponse JSON response from the server. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - if (array_key_exists('pages', $serverResponse)) { - foreach ($serverResponse['pages'] as $page) { + if (array_key_exists('pages', $rawResponse)) { + foreach ($rawResponse['pages'] as $page) { $this->pages[] = new RawTextPage($page); } } else { diff --git a/src/V2/Parsing/Inference/RawTextPage.php b/src/V2/Parsing/Inference/RawTextPage.php index 60db7c3c..85d67245 100644 --- a/src/V2/Parsing/Inference/RawTextPage.php +++ b/src/V2/Parsing/Inference/RawTextPage.php @@ -11,16 +11,15 @@ class RawTextPage { /** * Page content as a single string. - * */ - public string $content; + public ?string $content; /** - * @param array $serverResponse JSON response from the server. + * @param array> $rawResponse JSON response from the server. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->content = $serverResponse['content']; + $this->content = $rawResponse['content']; } /** diff --git a/src/V2/Parsing/Job.php b/src/V2/Parsing/Job.php index 59e2d61b..884ad054 100644 --- a/src/V2/Parsing/Job.php +++ b/src/V2/Parsing/Job.php @@ -70,34 +70,34 @@ class Job public array $webhooks; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; + $this->id = $rawResponse['id']; - $this->status = $serverResponse['status']; + $this->status = $rawResponse['status']; $this->error = null; if ( - !empty($serverResponse['error']) + !empty($rawResponse['error']) ) { - $this->error = new ErrorResponse($serverResponse['error']); + $this->error = new ErrorResponse($rawResponse['error']); } - $this->createdAt = $this->parseDate($serverResponse['created_at']); - $this->completedAt = isset($serverResponse['completed_at']) - ? $this->parseDate($serverResponse['completed_at']) + $this->createdAt = $this->parseDate($rawResponse['created_at']); + $this->completedAt = isset($rawResponse['completed_at']) + ? $this->parseDate($rawResponse['completed_at']) : null; - $this->modelId = $serverResponse['model_id']; - $this->pollingUrl = $serverResponse['polling_url']; - $this->filename = $serverResponse['filename']; - $this->resultUrl = $serverResponse['result_url'] ?? null; - $this->alias = $serverResponse['alias']; + $this->modelId = $rawResponse['model_id']; + $this->pollingUrl = $rawResponse['polling_url']; + $this->filename = $rawResponse['filename']; + $this->resultUrl = $rawResponse['result_url'] ?? null; + $this->alias = $rawResponse['alias']; $this->webhooks = []; - if (array_key_exists("webhooks", $serverResponse)) { - foreach ($serverResponse['webhooks'] as $webhook) { + if (array_key_exists("webhooks", $rawResponse)) { + foreach ($rawResponse['webhooks'] as $webhook) { $this->webhooks[] = new JobWebhook($webhook); } } @@ -110,7 +110,7 @@ public function __construct(array $serverResponse) */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } diff --git a/src/V2/Parsing/JobResponse.php b/src/V2/Parsing/JobResponse.php index c0afcee6..21a8fc0d 100644 --- a/src/V2/Parsing/JobResponse.php +++ b/src/V2/Parsing/JobResponse.php @@ -17,7 +17,7 @@ class JobResponse extends BaseResponse public Job $job; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Parsing/JobWebhook.php b/src/V2/Parsing/JobWebhook.php index 5be52b05..c8d856b3 100644 --- a/src/V2/Parsing/JobWebhook.php +++ b/src/V2/Parsing/JobWebhook.php @@ -33,17 +33,17 @@ class JobWebhook public ?ErrorResponse $error; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->id = $serverResponse['id']; - $this->createdAt = isset($serverResponse['created_at']) - ? $this->parseDate($serverResponse['created_at']) + $this->id = $rawResponse['id']; + $this->createdAt = isset($rawResponse['created_at']) + ? $this->parseDate($rawResponse['created_at']) : null; - $this->status = $serverResponse['status']; - $this->error = isset($serverResponse['error']) - ? new ErrorResponse($serverResponse['error']) + $this->status = $rawResponse['status']; + $this->error = isset($rawResponse['error']) + ? new ErrorResponse($rawResponse['error']) : null; } @@ -54,7 +54,7 @@ public function __construct(array $serverResponse) */ private function parseDate(?string $dateString): ?DateTime { - if ($dateString === null || $dateString === '') { + if (empty($dateString)) { return null; } diff --git a/src/V2/Product/Classification/ClassificationClassifier.php b/src/V2/Product/Classification/ClassificationClassifier.php index ecbbc029..5bf6ee32 100644 --- a/src/V2/Product/Classification/ClassificationClassifier.php +++ b/src/V2/Product/Classification/ClassificationClassifier.php @@ -22,7 +22,7 @@ class ClassificationClassifier public ?ExtractionResponse $extractionResponse; /** - * @param array $rawPrediction Raw prediction array. + * @param array> $rawPrediction Raw prediction array. */ public function __construct(array $rawPrediction) { diff --git a/src/V2/Product/Classification/ClassificationInference.php b/src/V2/Product/Classification/ClassificationInference.php index 5ee94dab..3d34cf36 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.php @@ -18,7 +18,7 @@ class ClassificationInference extends BaseInference public ClassificationResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Classification/ClassificationResponse.php b/src/V2/Product/Classification/ClassificationResponse.php index f4598522..01d78391 100644 --- a/src/V2/Product/Classification/ClassificationResponse.php +++ b/src/V2/Product/Classification/ClassificationResponse.php @@ -22,7 +22,7 @@ class ClassificationResponse extends BaseResponse public static string $slug = "classification"; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Classification/ClassificationResult.php b/src/V2/Product/Classification/ClassificationResult.php index e83dfc3a..5b5e22e3 100644 --- a/src/V2/Product/Classification/ClassificationResult.php +++ b/src/V2/Product/Classification/ClassificationResult.php @@ -15,7 +15,7 @@ class ClassificationResult public ClassificationClassifier $classification; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropInference.php b/src/V2/Product/Crop/CropInference.php index cdecf2c8..b0472c24 100644 --- a/src/V2/Product/Crop/CropInference.php +++ b/src/V2/Product/Crop/CropInference.php @@ -17,7 +17,7 @@ class CropInference extends BaseInference public CropResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropItem.php b/src/V2/Product/Crop/CropItem.php index 54e786ba..7b0b8e08 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -27,7 +27,7 @@ class CropItem */ public ?ExtractionResponse $extractionResponse; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropResponse.php b/src/V2/Product/Crop/CropResponse.php index f0a08c62..98b6b4f0 100644 --- a/src/V2/Product/Crop/CropResponse.php +++ b/src/V2/Product/Crop/CropResponse.php @@ -22,7 +22,7 @@ class CropResponse extends BaseResponse public static string $slug = "crop"; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Crop/CropResult.php b/src/V2/Product/Crop/CropResult.php index b88b008f..23428a97 100644 --- a/src/V2/Product/Crop/CropResult.php +++ b/src/V2/Product/Crop/CropResult.php @@ -15,7 +15,7 @@ class CropResult public array $crops; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionInference.php b/src/V2/Product/Extraction/ExtractionInference.php index 83027850..2ef76ce2 100644 --- a/src/V2/Product/Extraction/ExtractionInference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -24,7 +24,7 @@ class ExtractionInference extends BaseInference public ExtractionResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionResponse.php b/src/V2/Product/Extraction/ExtractionResponse.php index 10037ad0..3705f419 100644 --- a/src/V2/Product/Extraction/ExtractionResponse.php +++ b/src/V2/Product/Extraction/ExtractionResponse.php @@ -22,7 +22,7 @@ class ExtractionResponse extends BaseResponse public static string $slug = "extraction"; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Extraction/ExtractionResult.php b/src/V2/Product/Extraction/ExtractionResult.php index 9d91bbf4..f6102026 100644 --- a/src/V2/Product/Extraction/ExtractionResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -29,17 +29,17 @@ class ExtractionResult public ?RAGMetadata $rag; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->fields = new InferenceFields($serverResponse['fields']); - $this->rawText = isset($serverResponse['raw_text']) - ? new RawText($serverResponse['raw_text']) + $this->fields = new InferenceFields($rawResponse['fields']); + $this->rawText = isset($rawResponse['raw_text']) + ? new RawText($rawResponse['raw_text']) : null; $this->rag = isset( - $serverResponse['rag'] - ) ? new RAGMetadata($serverResponse['rag']) : null; + $rawResponse['rag'] + ) ? new RAGMetadata($rawResponse['rag']) : null; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchema.php b/src/V2/Product/Extraction/Params/DataSchema.php index 54f6de67..faf492ff 100644 --- a/src/V2/Product/Extraction/Params/DataSchema.php +++ b/src/V2/Product/Extraction/Params/DataSchema.php @@ -20,7 +20,7 @@ class DataSchema public ?DataSchemaReplace $replace; /** - * @param array|string|DataSchema $dataSchema Raw server response array. + * @param array>|string|DataSchema $dataSchema Raw server response array. * @throws InvalidArgumentException Throws if the data schema is invalid. */ public function __construct(self|array|string $dataSchema) @@ -40,7 +40,7 @@ public function __construct(self|array|string $dataSchema) } /** - * @return array JSON representation. + * @return array> JSON representation. */ public function toJson(): array { @@ -76,7 +76,7 @@ private function toJsonStringProperSpacing(): string { $jsonStr = json_encode($this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $lines = explode("\n", $jsonStr); - return implode("\n", array_map('self::fixLineSpaces', $lines)) . "\n"; + return implode("\n", array_map(static fn($line) => self::fixLineSpaces($line), $lines)) . "\n"; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index 5003ab40..e5c62f88 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -15,11 +15,11 @@ class DataSchemaActiveOption public bool $replace; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->replace = $serverResponse['replace']; + $this->replace = $rawResponse['replace']; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchemaField.php b/src/V2/Product/Extraction/Params/DataSchemaField.php index 1679db9f..b7103429 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaField.php +++ b/src/V2/Product/Extraction/Params/DataSchemaField.php @@ -38,38 +38,38 @@ class DataSchemaField */ public ?bool $uniqueValues; /** - * @var array|null Subfields when type is `nested_object`. Leave empty for other types. + * @var array>|null Subfields when type is `nested_object`. Leave empty for other types. */ public ?array $nestedFields; /** - * @var array|null Allowed values when type is `classification`. Leave empty for other types. + * @var array|null Allowed values when type is `classification`. Leave empty for other types. */ public ?array $classificationValues; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { - $this->name = $serverResponse['name']; - $this->title = $serverResponse['title']; - $this->isArray = $serverResponse['is_array']; - $this->type = $serverResponse['type']; - $this->description = $serverResponse['description']; - $this->guidelines = $serverResponse['guidelines']; - if (isset($serverResponse['unique_values'])) { - $this->uniqueValues = $serverResponse['unique_values']; + $this->name = $rawResponse['name']; + $this->title = $rawResponse['title']; + $this->isArray = $rawResponse['is_array']; + $this->type = $rawResponse['type']; + $this->description = $rawResponse['description']; + $this->guidelines = $rawResponse['guidelines']; + if (isset($rawResponse['unique_values'])) { + $this->uniqueValues = $rawResponse['unique_values']; } - if (isset($serverResponse['nested_fields'])) { - $this->nestedFields = $serverResponse['nested_fields']; + if (isset($rawResponse['nested_fields'])) { + $this->nestedFields = $rawResponse['nested_fields']; } - if (isset($serverResponse['classification_values'])) { - $this->classificationValues = $serverResponse['classification_values']; + if (isset($rawResponse['classification_values'])) { + $this->classificationValues = $rawResponse['classification_values']; } } /** - * @return array JSON representation. + * @return array> JSON representation. */ public function toJson(): array { diff --git a/src/V2/Product/Extraction/Params/DataSchemaReplace.php b/src/V2/Product/Extraction/Params/DataSchemaReplace.php index f9223438..77cd9c4a 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaReplace.php +++ b/src/V2/Product/Extraction/Params/DataSchemaReplace.php @@ -20,23 +20,23 @@ class DataSchemaReplace public array $fields; /** - * @param array $serverResponse Raw server response array. + * @param array> $rawResponse Raw server response array. * @throws InvalidArgumentException Throws if the fields array is empty or the Data schema is incorrect. */ - public function __construct(array $serverResponse) + public function __construct(array $rawResponse) { if ( - !isset($serverResponse['fields']) - || !is_array($serverResponse['fields']) - || count($serverResponse['fields']) === 0 + !isset($rawResponse['fields']) + || !is_array($rawResponse['fields']) + || count($rawResponse['fields']) === 0 ) { throw new InvalidArgumentException('Data Schema replacement fields cannot be empty.'); } - $this->fields = array_map(static fn($field) => new DataSchemaField($field), $serverResponse['fields']); + $this->fields = array_map(static fn($field) => new DataSchemaField($field), $rawResponse['fields']); } /** - * @return array JSON representation. + * @return array> JSON representation. */ public function toJson(): array { diff --git a/src/V2/Product/Extraction/Params/ExtractionParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php index 16b635e8..dd6a5dc3 100644 --- a/src/V2/Product/Extraction/Params/ExtractionParameters.php +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -61,8 +61,8 @@ class ExtractionParameters extends BaseParameters * @param array|null $webhooksIds List of webhook IDs. * @param string|null $textContext Additional text context used by the model during * inference. - * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during - * inference. + * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during + * inference. */ public function __construct( string $modelId, @@ -90,7 +90,7 @@ public function __construct( } /** - * @return array Hash representation. + * @return array> Hash representation. */ public function asHash(): array { diff --git a/src/V2/Product/Ocr/OcrInference.php b/src/V2/Product/OCR/OCRInference.php similarity index 56% rename from src/V2/Product/Ocr/OcrInference.php rename to src/V2/Product/OCR/OCRInference.php index 50dd3b97..d14e841e 100644 --- a/src/V2/Product/Ocr/OcrInference.php +++ b/src/V2/Product/OCR/OCRInference.php @@ -2,27 +2,27 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\V2\Parsing\BaseInference; /** * Response for an OCR utility inference. */ -class OcrInference extends BaseInference +class OCRInference extends BaseInference { /** - * @var OcrResult Result of the inference. + * @var OCRResult Result of the inference. */ - public OcrResult $result; + public OCRResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->result = new OcrResult($rawResponse['result']); + $this->result = new OCRResult($rawResponse['result']); } /** diff --git a/src/V2/Product/Ocr/OcrPage.php b/src/V2/Product/OCR/OCRPage.php similarity index 71% rename from src/V2/Product/Ocr/OcrPage.php rename to src/V2/Product/OCR/OCRPage.php index f440c7c2..3d4ba986 100644 --- a/src/V2/Product/Ocr/OcrPage.php +++ b/src/V2/Product/OCR/OCRPage.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; /** * OCR result for a single page. */ -class OcrPage +class OCRPage { /** - * @var OcrWord[] OCR result for a single page. + * @var OCRWord[] OCR result for a single page. */ public array $words; @@ -20,11 +20,11 @@ class OcrPage public string $content; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->words = array_map(static fn($word) => new OcrWord($word), $rawResponse['words']); + $this->words = array_map(static fn($word) => new OCRWord($word), $rawResponse['words']); $this->content = $rawResponse['content']; } diff --git a/src/V2/Product/Ocr/OcrResponse.php b/src/V2/Product/OCR/OCRResponse.php similarity index 52% rename from src/V2/Product/Ocr/OcrResponse.php rename to src/V2/Product/OCR/OCRResponse.php index 9912da67..9dd334dd 100644 --- a/src/V2/Product/Ocr/OcrResponse.php +++ b/src/V2/Product/OCR/OCRResponse.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\V2\Parsing\Inference\BaseResponse; /** * Response for an OCR utility inference. */ -class OcrResponse extends BaseResponse +class OCRResponse extends BaseResponse { /** - * @var OcrInference Result of an OCR inference. + * @var OCRInference Result of an OCR inference. */ - public OcrInference $inference; + public OCRInference $inference; /** * @var string Slug for the inference. @@ -22,11 +22,11 @@ class OcrResponse extends BaseResponse public static string $slug = "ocr"; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->inference = new OcrInference($rawResponse['inference']); + $this->inference = new OCRInference($rawResponse['inference']); } } diff --git a/src/V2/Product/Ocr/OcrResult.php b/src/V2/Product/OCR/OCRResult.php similarity index 72% rename from src/V2/Product/Ocr/OcrResult.php rename to src/V2/Product/OCR/OCRResult.php index 811cc10a..6799ab4c 100644 --- a/src/V2/Product/Ocr/OcrResult.php +++ b/src/V2/Product/OCR/OCRResult.php @@ -2,26 +2,26 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use function strlen; /** * Result of the OCR utility inference. */ -class OcrResult +class OCRResult { /** - * @var OcrPage[] List of pages. + * @var OCRPage[] List of pages. */ public array $pages; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { - $this->pages = array_map(static fn($page) => new OcrPage($page), $rawResponse['pages']); + $this->pages = array_map(static fn($page) => new OCRPage($page), $rawResponse['pages']); } /** diff --git a/src/V2/Product/Ocr/OcrWord.php b/src/V2/Product/OCR/OCRWord.php similarity index 81% rename from src/V2/Product/Ocr/OcrWord.php rename to src/V2/Product/OCR/OCRWord.php index 4f4d8e68..189632ea 100644 --- a/src/V2/Product/Ocr/OcrWord.php +++ b/src/V2/Product/OCR/OCRWord.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr; +namespace Mindee\V2\Product\OCR; use Mindee\Geometry\Polygon; /** * OCR result for a single word extracted from the document page. */ -class OcrWord +class OCRWord { /** * @var string Content of the word. @@ -22,7 +22,7 @@ class OcrWord public Polygon $polygon; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Ocr/Params/OcrParameters.php b/src/V2/Product/OCR/Params/OCRParameters.php similarity index 88% rename from src/V2/Product/Ocr/Params/OcrParameters.php rename to src/V2/Product/OCR/Params/OCRParameters.php index f162d1ec..bb9a95dc 100644 --- a/src/V2/Product/Ocr/Params/OcrParameters.php +++ b/src/V2/Product/OCR/Params/OCRParameters.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Product\Ocr\Params; +namespace Mindee\V2\Product\OCR\Params; use Mindee\ClientOptions\PollingOptions; use Mindee\V2\ClientOptions\BaseParameters; @@ -10,7 +10,7 @@ /** * Parameters for an ocr utility inference. */ -class OcrParameters extends BaseParameters +class OCRParameters extends BaseParameters { /** * @var string Slug of the endpoint. diff --git a/src/V2/Product/Split/SplitInference.php b/src/V2/Product/Split/SplitInference.php index a601d3e2..bf72acc4 100644 --- a/src/V2/Product/Split/SplitInference.php +++ b/src/V2/Product/Split/SplitInference.php @@ -17,7 +17,7 @@ class SplitInference extends BaseInference public SplitResult $result; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitRange.php b/src/V2/Product/Split/SplitRange.php index b8d2ad3f..772b3858 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -29,7 +29,7 @@ class SplitRange /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitResponse.php b/src/V2/Product/Split/SplitResponse.php index d1ba75be..ee435b5e 100644 --- a/src/V2/Product/Split/SplitResponse.php +++ b/src/V2/Product/Split/SplitResponse.php @@ -22,7 +22,7 @@ class SplitResponse extends BaseResponse public static string $slug = "split"; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/src/V2/Product/Split/SplitResult.php b/src/V2/Product/Split/SplitResult.php index 45187f0d..86859187 100644 --- a/src/V2/Product/Split/SplitResult.php +++ b/src/V2/Product/Split/SplitResult.php @@ -15,7 +15,7 @@ class SplitResult public array $splits; /** - * @param array $rawResponse Raw server response array. + * @param array> $rawResponse Raw server response array. */ public function __construct(array $rawResponse) { diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/CLI/MindeeCLICommandTestFunctional.php index b5d287f4..5dc870ea 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/CLI/MindeeCLICommandTestFunctional.php @@ -40,6 +40,7 @@ public static function provideProductCases(): iterable { $data = []; $data[] = ["generated", true, ["-a", "mindee", "-e", "invoice_splitter", "-d", "1"]]; + /** @phpstan-ignore-next-line */ foreach (MindeeCLIDocuments::getSpecs() as $productName => $productSpecs) { if ($productName !== "custom" && $productName !== "generated") { if ($productSpecs->isSync) { diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 3b93413f..1e96dbee 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -40,7 +40,7 @@ public function testShouldSendCropperExtra(): void self::assertGreaterThan(0, count($response->document->inference->pages[0]->extras->cropper->croppings)); } - public function testShouldSendFullTextOcrExtra(): void + public function testShouldSendFullTextOCRExtra(): void { $sample = $this->client->sourceFromPath( TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" diff --git a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php similarity index 95% rename from tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php rename to tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php index 90774d3d..eb90ab63 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -class FullTextOcrExtraTest extends TestCase +class FullTextOCRExtraTest extends TestCase { private $extrasDir; diff --git a/tests/V2/ClientOptions/BaseParametersTest.php b/tests/V2/ClientOptions/BaseParametersTest.php index 6d7cc135..6603b97b 100644 --- a/tests/V2/ClientOptions/BaseParametersTest.php +++ b/tests/V2/ClientOptions/BaseParametersTest.php @@ -11,7 +11,7 @@ class BaseParametersTest extends TestCase { public function testAsHashShouldSerializeMultipleWebhookIdsAsIndexedFields(): void { - $params = new class ('model-id', null, ['first-id', 'second-id'], null) extends BaseParameters { + $params = new class ('model-id', null, ['first-id', 'second-id']) extends BaseParameters { public static string $slug = 'test'; }; diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 7c49181e..6ff0e62a 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -153,7 +153,7 @@ public function testInvalidBaseUrlRaisesMindeeException(): void $params = new ExtractionParameters('dummy-model-id'); $client->enqueueAndGetResult(ExtractionResponse::class, $input, $params); } finally { - if ($original === null) { + if (null === $original) { putenv('MINDEE_V2_BASE_URL'); } else { putenv('MINDEE_V2_BASE_URL=' . $original); diff --git a/tests/V2/Parsing/ExtractionResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php index 30cae739..d80503a1 100644 --- a/tests/V2/Parsing/ExtractionResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -75,7 +75,7 @@ public function testAsyncPredictWhenEmptyMustHaveValidProperties(): void self::assertCount(9, $supplierAddress->fields); foreach ($fields as $fieldName => $field) { - if ($field === null) { + if (null === $field) { continue; } if ($field instanceof ListField) { diff --git a/tests/V2/Product/OcrFunctional.php b/tests/V2/Product/OCRFunctional.php similarity index 79% rename from tests/V2/Product/OcrFunctional.php rename to tests/V2/Product/OCRFunctional.php index 974d29e7..25517311 100644 --- a/tests/V2/Product/OcrFunctional.php +++ b/tests/V2/Product/OCRFunctional.php @@ -6,14 +6,14 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; -use Mindee\V2\Product\Ocr\OcrResponse; -use Mindee\V2\Product\Ocr\Params\OcrParameters; +use Mindee\V2\Product\OCR\OCRResponse; +use Mindee\V2\Product\OCR\Params\OCRParameters; use PHPUnit\Framework\TestCase; use TestingUtilities; require_once(__DIR__ . "/../../TestingUtilities.php"); -class OcrFunctional extends TestCase +class OCRFunctional extends TestCase { private Client $client; private string $ocrModelId; @@ -30,14 +30,14 @@ protected function setUp(): void * Tests the success of the OCR process using a default sample file. * */ - public function testOcrDefaultSampleMustSucceed(): void + public function testOCRDefaultSampleMustSucceed(): void { $inputSource = new PathInput( TestingUtilities::getV2ProductDir() . '/ocr/default_sample.jpg' ); - $productParams = new OcrParameters($this->ocrModelId); - $response = $this->client->enqueueAndGetResult(OcrResponse::class, $inputSource, $productParams); + $productParams = new OCRParameters($this->ocrModelId); + $response = $this->client->enqueueAndGetResult(OCRResponse::class, $inputSource, $productParams); self::assertNotNull($response); self::assertNotNull($response->inference); diff --git a/tests/V2/Product/OcrTest.php b/tests/V2/Product/OCRTest.php similarity index 91% rename from tests/V2/Product/OcrTest.php rename to tests/V2/Product/OCRTest.php index 784dd7fb..3ff0a7ff 100644 --- a/tests/V2/Product/OcrTest.php +++ b/tests/V2/Product/OCRTest.php @@ -6,14 +6,14 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -use Mindee\V2\Product\Ocr\OcrResponse; +use Mindee\V2\Product\OCR\OCRResponse; require_once(__DIR__ . "/../../TestingUtilities.php"); /** * OCR unit tests. */ -class OcrTest extends TestCase +class OCRTest extends TestCase { /** * Load a JSON sample and return its decoded contents. @@ -43,10 +43,10 @@ private function assertInferenceResponse(mixed $response): void /** * Should correctly map properties when reading a single OCR JSON. */ - public function testOcrWhenSingleMustHaveValidProperties(): void + public function testOCRWhenSingleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_single.json"); - $response = new OcrResponse($jsonSample); + $response = new OCRResponse($jsonSample); $this->assertInferenceResponse($response); @@ -78,10 +78,10 @@ public function testOcrWhenSingleMustHaveValidProperties(): void /** * Should correctly map properties when reading a multiple OCR JSON. */ - public function testOcrWhenMultipleMustHaveValidProperties(): void + public function testOCRWhenMultipleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_multiple.json"); - $response = new OcrResponse($jsonSample); + $response = new OCRResponse($jsonSample); $this->assertInferenceResponse($response); From 84bdc9bfde91d5f733f71a04958beccc3c730bbd Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Wed, 27 May 2026 11:24:26 +0200 Subject: [PATCH 05/11] :wrench: add support for rector (#189) --- .github/workflows/_static-analysis.yml | 4 ++ bin/MindeeCLICommand.php | 4 +- composer.json | 8 ++- docs/code_samples/v2_extraction_webhook.txt | 2 +- docs/code_samples/v2_ocr.txt | 6 +- rector.php | 15 ++++ src/Dependency/DependencyChecker.php | 4 +- src/Error/MindeeHttpException.php | 9 +-- ...DFException.php => MindeePdfException.php} | 2 +- src/Extraction/ExtractedImage.php | 36 +--------- .../{ExtractedPDF.php => ExtractedPdf.php} | 24 ++----- src/Extraction/ImageExtractor.php | 10 +-- .../{PDFExtractor.php => PdfExtractor.php} | 26 +++---- src/Geometry/BBox.php | 29 +------- src/Geometry/MinMax.php | 15 +--- src/Geometry/Point.php | 15 +--- src/Geometry/Polygon.php | 4 +- src/Input/LocalInputSource.php | 56 +++++++-------- src/Input/PageOptions.php | 23 +------ ...{URLInputSource.php => UrlInputSource.php} | 4 +- .../CustomFPDI.php => Pdf/CustomFpdi.php} | 4 +- .../PdfCompressor.php} | 50 +++++++------- src/{PDF/PDFUtils.php => Pdf/PdfUtils.php} | 36 +++++----- src/V1/Client.php | 58 ++++++++-------- src/V1/ClientOptions/CommonOptions.php | 15 +--- src/V1/ClientOptions/PredictMethodOptions.php | 4 +- src/V1/ClientOptions/PredictOptions.php | 24 ++----- src/V1/ClientOptions/WorkflowOptions.php | 33 ++------- src/V1/{HTTP/BaseAPI.php => Http/BaseApi.php} | 25 +++---- src/V1/{HTTP => Http}/BaseEndpoint.php | 14 +--- src/V1/{HTTP => Http}/Endpoint.php | 32 +++------ .../MindeeAPI.php => Http/MindeeApi.php} | 4 +- .../MindeeWorkflowApi.php} | 11 +-- src/V1/{HTTP => Http}/ResponseValidation.php | 2 +- src/V1/{HTTP => Http}/WorkflowEndpoint.php | 10 +-- src/V1/Parsing/Common/ApiResponse.php | 2 +- src/V1/Parsing/Common/Document.php | 15 ++-- src/V1/Parsing/Common/Execution.php | 5 +- src/V1/Parsing/Common/Extras/CropperExtra.php | 3 +- src/V1/Parsing/Common/Extras/Extras.php | 21 +++--- ...lTextOCRExtra.php => FullTextOcrExtra.php} | 9 +-- .../Extras/{RAGExtra.php => RagExtra.php} | 4 +- src/V1/Parsing/Common/Inference.php | 3 +- src/V1/Parsing/Common/Job.php | 9 +-- .../Parsing/Common/{OCR => Ocr}/MVisionV1.php | 10 +-- .../Common/{OCR/OCR.php => Ocr/Ocr.php} | 12 ++-- .../{OCR/OCRLine.php => Ocr/OcrLine.php} | 24 +++---- .../{OCR/OCRPage.php => Ocr/OcrPage.php} | 56 +++++++-------- .../{OCR/OCRWord.php => Ocr/OcrWord.php} | 5 +- src/V1/Parsing/Common/Page.php | 3 +- src/V1/Parsing/Common/Prediction.php | 4 +- src/V1/Parsing/Common/Product.php | 6 +- .../Parsing/Generated/GeneratedListField.php | 10 +-- .../Generated/GeneratedObjectField.php | 3 +- src/V1/Parsing/Standard/BaseField.php | 10 +-- src/V1/Parsing/Standard/Taxes.php | 5 +- .../BillOfLading/BillOfLadingV1Carrier.php | 10 +-- .../BillOfLadingV1CarrierItem.php | 10 +-- .../BillOfLadingV1CarrierItems.php | 3 +- .../BillOfLading/BillOfLadingV1Consignee.php | 10 +-- .../BillOfLadingV1NotifyParty.php | 10 +-- .../BillOfLading/BillOfLadingV1Shipper.php | 10 +-- .../FinancialDocumentV1LineItem.php | 10 +-- .../FinancialDocumentV1LineItems.php | 3 +- .../BankAccountDetailsV2Bban.php | 10 +-- .../EnergyBill/EnergyBillV1EnergyConsumer.php | 10 +-- .../EnergyBill/EnergyBillV1EnergySupplier.php | 10 +-- .../Fr/EnergyBill/EnergyBillV1EnergyUsage.php | 10 +-- .../EnergyBill/EnergyBillV1EnergyUsages.php | 3 +- .../Fr/EnergyBill/EnergyBillV1MeterDetail.php | 10 +-- .../EnergyBill/EnergyBillV1Subscription.php | 10 +-- .../EnergyBill/EnergyBillV1Subscriptions.php | 3 +- .../EnergyBillV1TaxesAndContribution.php | 10 +-- .../EnergyBillV1TaxesAndContributions.php | 3 +- .../Fr/Payslip/PayslipV3BankAccountDetail.php | 10 +-- .../Product/Fr/Payslip/PayslipV3Employee.php | 10 +-- .../Product/Fr/Payslip/PayslipV3Employer.php | 10 +-- .../Fr/Payslip/PayslipV3Employment.php | 10 +-- .../Fr/Payslip/PayslipV3PaidTimeOff.php | 10 +-- .../Fr/Payslip/PayslipV3PaidTimeOffs.php | 3 +- .../Product/Fr/Payslip/PayslipV3PayDetail.php | 10 +-- .../Product/Fr/Payslip/PayslipV3PayPeriod.php | 10 +-- .../Fr/Payslip/PayslipV3SalaryDetail.php | 10 +-- .../Fr/Payslip/PayslipV3SalaryDetails.php | 3 +- src/V1/Product/Invoice/InvoiceV4LineItem.php | 10 +-- src/V1/Product/Invoice/InvoiceV4LineItems.php | 3 +- .../InvoiceSplitterV1InvoicePageGroup.php | 10 +-- .../InvoiceSplitterV1InvoicePageGroups.php | 3 +- .../NutritionFactsLabelV1AddedSugar.php | 10 +-- .../NutritionFactsLabelV1Calorie.php | 10 +-- .../NutritionFactsLabelV1Cholesterol.php | 10 +-- .../NutritionFactsLabelV1DietaryFiber.php | 10 +-- .../NutritionFactsLabelV1Nutrient.php | 10 +-- .../NutritionFactsLabelV1Nutrients.php | 3 +- .../NutritionFactsLabelV1Protein.php | 10 +-- .../NutritionFactsLabelV1SaturatedFat.php | 10 +-- .../NutritionFactsLabelV1ServingSize.php | 10 +-- .../NutritionFactsLabelV1Sodium.php | 10 +-- ...NutritionFactsLabelV1TotalCarbohydrate.php | 10 +-- .../NutritionFactsLabelV1TotalFat.php | 10 +-- .../NutritionFactsLabelV1TotalSugar.php | 10 +-- .../NutritionFactsLabelV1TransFat.php | 10 +-- src/V1/Product/Receipt/ReceiptV5LineItem.php | 10 +-- src/V1/Product/Receipt/ReceiptV5LineItems.php | 3 +- src/V1/Product/Resume/ResumeV1Certificate.php | 10 +-- .../Product/Resume/ResumeV1Certificates.php | 3 +- src/V1/Product/Resume/ResumeV1Education.php | 10 +-- src/V1/Product/Resume/ResumeV1Educations.php | 3 +- src/V1/Product/Resume/ResumeV1Language.php | 10 +-- src/V1/Product/Resume/ResumeV1Languages.php | 3 +- .../Resume/ResumeV1ProfessionalExperience.php | 10 +-- .../ResumeV1ProfessionalExperiences.php | 3 +- .../Resume/ResumeV1SocialNetworksUrl.php | 10 +-- .../Resume/ResumeV1SocialNetworksUrls.php | 3 +- .../HealthcareCard/HealthcareCardV1Copay.php | 10 +-- .../HealthcareCard/HealthcareCardV1Copays.php | 3 +- .../Us/UsMail/UsMailV3RecipientAddress.php | 10 +-- .../Us/UsMail/UsMailV3RecipientAddresses.php | 3 +- .../Us/UsMail/UsMailV3SenderAddress.php | 10 +-- src/V2/Client.php | 8 +-- src/V2/ClientOptions/BaseParameters.php | 25 +++---- src/V2/FileOperations/Crop.php | 10 +-- src/V2/FileOperations/Split.php | 22 ++---- src/V2/FileOperations/SplitFiles.php | 8 +-- .../MindeeAPIV2.php => Http/MindeeApiV2.php} | 18 ++--- src/V2/Parsing/BaseInference.php | 3 +- src/V2/Parsing/Inference/BaseResponse.php | 12 +--- src/V2/Parsing/Inference/Field/BaseField.php | 10 +-- .../Parsing/Inference/Field/FieldLocation.php | 3 +- .../Inference/Field/InferenceFields.php | 9 +-- .../Inference/InferenceActiveOptions.php | 3 +- src/V2/Parsing/Inference/InferenceFile.php | 4 +- src/V2/Parsing/Inference/InferenceJob.php | 4 +- src/V2/Parsing/Inference/InferenceModel.php | 4 +- .../{RAGMetadata.php => RagMetadata.php} | 2 +- src/V2/Parsing/Inference/RawText.php | 4 +- src/V2/Parsing/Inference/RawTextPage.php | 4 +- src/V2/Parsing/Job.php | 2 +- src/V2/Parsing/JobWebhook.php | 2 +- .../ClassificationClassifier.php | 3 +- .../Classification/ClassificationResult.php | 4 +- .../Params/ClassificationParameters.php | 6 +- src/V2/Product/Crop/CropItem.php | 5 +- src/V2/Product/Crop/CropResult.php | 4 +- src/V2/Product/Crop/Params/CropParameters.php | 6 +- .../Product/Extraction/ExtractionResult.php | 11 +-- .../Product/Extraction/Params/DataSchema.php | 7 +- .../Params/DataSchemaActiveOption.php | 4 +- .../Extraction/Params/DataSchemaField.php | 6 +- .../Extraction/Params/DataSchemaReplace.php | 5 +- .../Params/ExtractionParameters.php | 47 +++---------- .../OCRInference.php => Ocr/OcrInference.php} | 12 ++-- .../{OCR/OCRPage.php => Ocr/OcrPage.php} | 14 ++-- .../OCRResponse.php => Ocr/OcrResponse.php} | 12 ++-- .../{OCR/OCRResult.php => Ocr/OcrResult.php} | 14 ++-- .../{OCR/OCRWord.php => Ocr/OcrWord.php} | 7 +- .../Params/OcrParameters.php} | 10 +-- .../Product/Split/Params/SplitParameters.php | 6 +- src/V2/Product/Split/SplitRange.php | 3 +- src/V2/Product/Split/SplitResult.php | 4 +- ...=> DependencyCheckerNoExtendedTestPdf.php} | 24 ++++--- ...FTest.php => DependencyCheckerPdfTest.php} | 2 +- tests/Geometry/PolygonUtilsTest.php | 6 +- tests/Input/LocalInputSourceTest.php | 68 +++++++++---------- ...tSourceTest.php => UrlInputSourceTest.php} | 14 ++-- tests/V1/CLI/MindeeCLICommandTest.php | 4 +- .../V1/CLI/MindeeCLICommandTestFunctional.php | 2 +- tests/V1/Error/MindeeHttpExceptionTest.php | 18 ++--- tests/V1/Extraction/ImageExtractorTest.php | 2 +- ...ceSplitterAutoExtractionTestFunctional.php | 6 +- ...ExtractorTest.php => PdfExtractorTest.php} | 46 ++++++------- tests/V1/Http/MindeeApiTest.php | 10 +-- ...l.php => UrlInputSourceTestFunctional.php} | 2 +- .../Common/AsyncPredictResponseTest.php | 2 +- .../Extras/ExtrasIntegrationFunctional.php | 4 +- ...ExtraTest.php => FullTextOcrExtraTest.php} | 4 +- .../{OCR/OCRTest.php => Ocr/OcrTest.php} | 10 +-- tests/V2/ClientV2Test.php | 15 ++-- tests/V2/ClientV2TestFunctional.php | 6 +- tests/V2/FileOperations/CropFunctional.php | 2 +- tests/V2/FileOperations/SplitFunctional.php | 2 +- tests/V2/Input/LocalResponseV2Test.php | 1 - tests/V2/Parsing/ExtractionResponseTest.php | 2 +- .../{OCRFunctional.php => OcrFunctional.php} | 14 ++-- tests/V2/Product/{OCRTest.php => OcrTest.php} | 18 ++--- 185 files changed, 803 insertions(+), 1169 deletions(-) create mode 100644 rector.php rename src/Error/{MindeePDFException.php => MindeePdfException.php} (77%) rename src/Extraction/{ExtractedPDF.php => ExtractedPdf.php} (82%) rename src/Extraction/{PDFExtractor.php => PdfExtractor.php} (89%) rename src/Input/{URLInputSource.php => UrlInputSource.php} (98%) rename src/{PDF/CustomFPDI.php => Pdf/CustomFpdi.php} (97%) rename src/{PDF/PDFCompressor.php => Pdf/PdfCompressor.php} (83%) rename src/{PDF/PDFUtils.php => Pdf/PdfUtils.php} (89%) rename src/V1/{HTTP/BaseAPI.php => Http/BaseApi.php} (86%) rename src/V1/{HTTP => Http}/BaseEndpoint.php (87%) rename src/V1/{HTTP => Http}/Endpoint.php (85%) rename src/V1/{HTTP/MindeeAPI.php => Http/MindeeApi.php} (96%) rename src/V1/{HTTP/MindeeWorkflowAPI.php => Http/MindeeWorkflowApi.php} (81%) rename src/V1/{HTTP => Http}/ResponseValidation.php (99%) rename src/V1/{HTTP => Http}/WorkflowEndpoint.php (92%) rename src/V1/Parsing/Common/Extras/{FullTextOCRExtra.php => FullTextOcrExtra.php} (86%) rename src/V1/Parsing/Common/Extras/{RAGExtra.php => RagExtra.php} (93%) rename src/V1/Parsing/Common/{OCR => Ocr}/MVisionV1.php (76%) rename src/V1/Parsing/Common/{OCR/OCR.php => Ocr/Ocr.php} (83%) rename src/V1/Parsing/Common/{OCR/OCRLine.php => Ocr/OcrLine.php} (63%) rename src/V1/Parsing/Common/{OCR/OCRPage.php => Ocr/OcrPage.php} (70%) rename src/V1/Parsing/Common/{OCR/OCRWord.php => Ocr/OcrWord.php} (89%) rename src/V2/{HTTP/MindeeAPIV2.php => Http/MindeeApiV2.php} (97%) rename src/V2/Parsing/Inference/{RAGMetadata.php => RagMetadata.php} (96%) rename src/V2/Product/{OCR/OCRInference.php => Ocr/OcrInference.php} (66%) rename src/V2/Product/{OCR/OCRPage.php => Ocr/OcrPage.php} (71%) rename src/V2/Product/{OCR/OCRResponse.php => Ocr/OcrResponse.php} (63%) rename src/V2/Product/{OCR/OCRResult.php => Ocr/OcrResult.php} (73%) rename src/V2/Product/{OCR/OCRWord.php => Ocr/OcrWord.php} (84%) rename src/V2/Product/{OCR/Params/OCRParameters.php => Ocr/Params/OcrParameters.php} (66%) rename tests/Dependencies/{DependencyCheckerNoExtendedTestPDF.php => DependencyCheckerNoExtendedTestPdf.php} (68%) rename tests/Dependencies/{DependencyCheckerPDFTest.php => DependencyCheckerPdfTest.php} (92%) rename tests/Input/{URLInputSourceTest.php => UrlInputSourceTest.php} (79%) rename tests/V1/Extraction/{PDFExtractorTest.php => PdfExtractorTest.php} (58%) rename tests/V1/Input/{URLInputSourceTestFunctional.php => UrlInputSourceTestFunctional.php} (97%) rename tests/V1/Parsing/Common/Extras/{FullTextOCRExtraTest.php => FullTextOcrExtraTest.php} (91%) rename tests/V1/Parsing/Common/{OCR/OCRTest.php => Ocr/OcrTest.php} (88%) rename tests/V2/Product/{OCRFunctional.php => OcrFunctional.php} (75%) rename tests/V2/Product/{OCRTest.php => OcrTest.php} (88%) diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 510b2452..aaadd839 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -38,3 +38,7 @@ jobs: - name: Run PHPStan run: | composer phpstan + + - name: Run Rector + run: | + composer rector:check diff --git a/bin/MindeeCLICommand.php b/bin/MindeeCLICommand.php index c7c3744f..23c358ad 100644 --- a/bin/MindeeCLICommand.php +++ b/bin/MindeeCLICommand.php @@ -8,7 +8,7 @@ use Mindee\Input\InputSource; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\PredictOptions; @@ -359,7 +359,7 @@ private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputI * @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. + * @return PathInput|UrlInputSource|null A valid InputSource. */ private function getFileSource(string $filePathOrUrl, Client $client, OutputInterface $output) { diff --git a/composer.json b/composer.json index 96a7daaf..f18cb53b 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,9 @@ "friendsofphp/php-cs-fixer": "^3.38", "phpunit/phpunit": "^9.6", "madewithlove/license-checker": "^v1.0", - "phpstan/phpstan": "^2.1" + "phpstan/phpstan": "^2.1", + "phpstan/phpstan-deprecation-rules": "^2.0", + "rector/rector": "^2.4" }, "suggest": { "ext-imagick": "Required for PDF rasterization and image processing features", @@ -35,6 +37,8 @@ "scripts": { "lint": "php-cs-fixer fix --dry-run --diff", "phpstan": "phpstan analyse src --level 6", - "format": "php-cs-fixer fix" + "format": "php-cs-fixer fix", + "rector": "rector process src tests", + "rector:check": "rector process src tests --dry-run" } } diff --git a/docs/code_samples/v2_extraction_webhook.txt b/docs/code_samples/v2_extraction_webhook.txt index 63fe599e..28293a6b 100644 --- a/docs/code_samples/v2_extraction_webhook.txt +++ b/docs/code_samples/v2_extraction_webhook.txt @@ -16,7 +16,7 @@ $mindeeClient = new Client($apiKey); $inferenceParams = new ExtractionParameters( // ID of the model, required. $modelId, - webhooksIds: ["MY_WEBHOOK_ID"], + webhookIds: ["MY_WEBHOOK_ID"], // Options: set to `true` or `false` to override defaults diff --git a/docs/code_samples/v2_ocr.txt b/docs/code_samples/v2_ocr.txt index 3921f550..5beba83d 100644 --- a/docs/code_samples/v2_ocr.txt +++ b/docs/code_samples/v2_ocr.txt @@ -1,8 +1,8 @@ withPaths([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->withPhpSets() + ->withTypeCoverageLevel(0) + ->withDeadCodeLevel(0) + ->withCodeQualityLevel(0); diff --git a/src/Dependency/DependencyChecker.php b/src/Dependency/DependencyChecker.php index cde460a1..87cc8e12 100644 --- a/src/Dependency/DependencyChecker.php +++ b/src/Dependency/DependencyChecker.php @@ -48,7 +48,7 @@ public static function isGhostscriptAvailable(): void } else { $commandWasExecuted = (bool) shell_exec('which gs'); } - } catch (Exception $e) { + } catch (Exception) { throw new MindeeUnhandledException( "To enable full support of PDF features, you need " . "to enable Ghostscript on your PHP installation.", @@ -96,7 +96,7 @@ public static function isImageMagickPolicyAllowed(): void /** @phpstan-ignore-next-line */ TestingUtilities::getV1DataDir() . "/products/expense_receipts/default_sample.jpg" ); - } catch (Exception $e) { + } catch (Exception) { throw new MindeeUnhandledException( "To enable full support of PDF features, you need " . "to enable ImageMagick on your PHP installation. Also, you " diff --git a/src/Error/MindeeHttpException.php b/src/Error/MindeeHttpException.php index f83692d3..98384c81 100644 --- a/src/Error/MindeeHttpException.php +++ b/src/Error/MindeeHttpException.php @@ -20,10 +20,6 @@ */ class MindeeHttpException extends MindeeException { - /** - * @var integer Status code as sent by the server. - */ - public int $statusCode; /** * @var string|null API code as sent by the server. */ @@ -40,11 +36,10 @@ class MindeeHttpException extends MindeeException /** * @param array> $httpError Array containing the error data. * @param string $url Remote URL the error was found on. - * @param integer $code Error code. + * @param integer $statusCode Error code. */ - public function __construct(array $httpError, string $url, int $code) + public function __construct(array $httpError, string $url, public int $statusCode) { - $this->statusCode = $code; if (array_key_exists('code', $httpError)) { $this->apiCode = $httpError['code']; } else { diff --git a/src/Error/MindeePDFException.php b/src/Error/MindeePdfException.php similarity index 77% rename from src/Error/MindeePDFException.php rename to src/Error/MindeePdfException.php index 45b145ec..589b2844 100644 --- a/src/Error/MindeePDFException.php +++ b/src/Error/MindeePdfException.php @@ -12,4 +12,4 @@ /** * Exceptions relating to the handling of PDF documents. */ -class MindeePDFException extends MindeeException {} +class MindeePdfException extends MindeeException {} diff --git a/src/Extraction/ExtractedImage.php b/src/Extraction/ExtractedImage.php index d7a694e6..5ba66a81 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Extraction/ExtractedImage.php @@ -19,51 +19,21 @@ */ class ExtractedImage { - /** - * @var Imagick Wrapper for the image. - */ - public Imagick $image; - - /** - * @var string Name of the file. - */ - public string $filename; - - /** - * @var integer Page ID of the image. - */ - public int $pageId; - - /** - * @var integer Element ID of the image. - */ - public int $elementId; - - /** - * @var string String representation of the save format. - */ - protected string $saveFormat; - /** * Initializes a new instance of the ExtractedImage class. * * @param Imagick $image The extracted image. * @param string $filename The filename for the image. * @param string $saveFormat The format to save the image. - * @param integer $pageIndex The page index of the image. - * @param integer $index The element index of the image. + * @param integer $pageId The page index of the image. + * @param integer $elementId The element index of the image. * * @throws MindeeUnhandledException Throws if PDF operations aren't supported. */ - public function __construct(Imagick $image, string $filename, string $saveFormat, int $pageIndex, int $index) + public function __construct(public Imagick $image, public string $filename, protected string $saveFormat, public int $pageId, public int $elementId) { DependencyChecker::isImageMagickAvailable(); DependencyChecker::isGhostscriptAvailable(); - $this->image = $image; - $this->filename = $filename; - $this->saveFormat = $saveFormat; - $this->pageId = $pageIndex; - $this->elementId = $index; } /** diff --git a/src/Extraction/ExtractedPDF.php b/src/Extraction/ExtractedPdf.php similarity index 82% rename from src/Extraction/ExtractedPDF.php rename to src/Extraction/ExtractedPdf.php index d2874e85..ba738442 100644 --- a/src/Extraction/ExtractedPDF.php +++ b/src/Extraction/ExtractedPdf.php @@ -6,7 +6,7 @@ use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Error\MindeeUnhandledException; use Mindee\Input\BytesInput; use setasign\Fpdi\Fpdi; @@ -17,18 +17,8 @@ /** * An extracted sub-Pdf. */ -class ExtractedPDF +class ExtractedPdf { - /** - * @var string name of the original file - */ - public string $filename; - - /** - * @var string File object for an ExtractedPdf. - */ - protected string $pdfBytes; - /** * Initializes a new instance of the ExtractedPdf class. * @@ -37,12 +27,10 @@ class ExtractedPDF * * @throws MindeeUnhandledException Throws if PDF operations aren't supported. */ - public function __construct(string $pdfBytes, string $filename) + public function __construct(protected string $pdfBytes, public string $filename) { DependencyChecker::isImageMagickAvailable(); DependencyChecker::isGhostscriptAvailable(); - $this->pdfBytes = $pdfBytes; - $this->filename = $filename; } /** @@ -50,7 +38,7 @@ public function __construct(string $pdfBytes, string $filename) * * @return integer the number of pages in the file * - * @throws MindeePDFException Throws if FPDI is unable to process the file. + * @throws MindeePdfException Throws if FPDI is unable to process the file. */ public function getPageCount(): int { @@ -62,7 +50,7 @@ public function getPageCount(): int return $pdfHandle->setSourceFile($tempFilename); } catch (PdfParserException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Couldn't open PDF file.", ErrorCode::PDF_CANT_CREATE, $e @@ -102,7 +90,7 @@ public function asInputSource(): BytesInput /** * @return string the pdf bytes */ - public function getPDFBytes(): string + public function getPdfBytes(): string { return $this->pdfBytes; } diff --git a/src/Extraction/ImageExtractor.php b/src/Extraction/ImageExtractor.php index 80512d48..764922e4 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Extraction/ImageExtractor.php @@ -9,7 +9,7 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeGeometryException; use Mindee\Error\MindeeImageException; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Geometry\BBox; use Mindee\Geometry\BBoxUtils; use Mindee\Geometry\Point; @@ -51,7 +51,7 @@ class ImageExtractor * @param LocalInputSource $localInput Local input, accepts all compatible formats. * @param null|string $saveFormat Save format, will be coerced to jpg by default. * - * @throws MindeePDFException Throws if PDF operations aren't supported, or if the file can't be read, respectively. + * @throws MindeePdfException Throws if PDF operations aren't supported, or if the file can't be read, respectively. */ public function __construct(LocalInputSource $localInput, ?string $saveFormat = null) { @@ -71,14 +71,14 @@ public function __construct(LocalInputSource $localInput, ?string $saveFormat = $this->saveFormat = $saveFormat; } - if ($this->inputSource->isPDF()) { - $this->pageImages = $this->pdfToImages($this->inputSource->readContents()[1]); + if ($this->inputSource->isPdf()) { + $this->pageImages = static::pdfToImages($this->inputSource->readContents()[1]); } else { try { $image = new Imagick(); $image->readImageBlob($this->inputSource->readContents()[1]); } catch (ImagickException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Image couldn't be processed.", ErrorCode::IMAGE_CANT_PROCESS, $e diff --git a/src/Extraction/PDFExtractor.php b/src/Extraction/PdfExtractor.php similarity index 89% rename from src/Extraction/PDFExtractor.php rename to src/Extraction/PdfExtractor.php index bffe885c..25bf10cb 100644 --- a/src/Extraction/PDFExtractor.php +++ b/src/Extraction/PdfExtractor.php @@ -5,7 +5,7 @@ namespace Mindee\Extraction; use Mindee\Dependency\DependencyChecker; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Input\LocalInputSource; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1InvoicePageGroups; use setasign\Fpdi\Fpdi; @@ -24,7 +24,7 @@ /** * PDF extraction class. */ -class PDFExtractor +class PdfExtractor { /** * @var string bytes representation of a file @@ -34,12 +34,12 @@ class PDFExtractor /** * @var string name of the file */ - private string $fileName; + private readonly string $fileName; /** * @param LocalInputSource $localInput Local Input, accepts all compatible formats. * - * @throws MindeePDFException Throws if PDF operations aren't supported, or if the file + * @throws MindeePdfException Throws if PDF operations aren't supported, or if the file * can't be read, respectively. */ public function __construct(LocalInputSource $localInput) @@ -48,13 +48,13 @@ public function __construct(LocalInputSource $localInput) DependencyChecker::isGhostscriptAvailable(); $this->fileName = $localInput->fileName; - if ($localInput->isPDF()) { + if ($localInput->isPdf()) { $this->pdfBytes = $localInput->readContents()[1]; } else { try { $image = new Imagick(); } catch (ImagickException $e) { - throw new MindeePDFException("Imagick could not process this file.\n", 0, $e); + throw new MindeePdfException("Imagick could not process this file.\n", 0, $e); } $image->readImageBlob($localInput->readContents()[1]); $image->setImageFormat('pdf'); @@ -67,7 +67,7 @@ public function __construct(LocalInputSource $localInput) * * @return integer The number of pages in the file. * - * @throws MindeePDFException Throws if FPDI is unable to process the file. + * @throws MindeePdfException Throws if FPDI is unable to process the file. */ public function getPageCount(): int { @@ -79,7 +79,7 @@ public function getPageCount(): int return $pdfHandle->setSourceFile($tempFilename); } catch (PdfParserException $e) { - throw new MindeePDFException("Couldn't open PDF file. FPDI sent the following: ", 0, $e); + throw new MindeePdfException("Couldn't open PDF file. FPDI sent the following: ", 0, $e); } } @@ -88,9 +88,9 @@ public function getPageCount(): int * * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * - * @return ExtractedPDF[] list of extracted documents + * @return ExtractedPdf[] list of extracted documents * - * @throws MindeePDFException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. + * @throws MindeePdfException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. * @throws InvalidArgumentException Throws if invalid indexes are provided. */ public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes): array @@ -130,9 +130,9 @@ public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pa PdfParserException| PdfReaderException $e ) { - throw new MindeePDFException("PDF file couldn't be processed during extraction.", 0, $e); + throw new MindeePdfException("PDF file couldn't be processed during extraction.", 0, $e); } - $extractedPdfs[] = new ExtractedPDF($mergedPdfBytes, $fieldFilename); + $extractedPdfs[] = new ExtractedPdf($mergedPdfBytes, $fieldFilename); } return $extractedPdfs; @@ -144,7 +144,7 @@ public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pa * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. * @param boolean $strict Whether to trust confidence scores or not. * - * @return ExtractedPDF[] a list of extracted invoices + * @return ExtractedPdf[] a list of extracted invoices */ public function extractInvoices(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes, bool $strict = false): array { diff --git a/src/Geometry/BBox.php b/src/Geometry/BBox.php index dd0c6d32..5a930b7e 100644 --- a/src/Geometry/BBox.php +++ b/src/Geometry/BBox.php @@ -9,40 +9,13 @@ */ class BBox { - /** - * @var float Minimum X coordinate. - */ - private float $minX; - /** - * @var float Maximum X coordinate. - */ - private float $maxX; - /** - * @var float Minimum Y coordinate. - */ - private float $minY; - /** - * @var float Maximum Y coordinate. - */ - private float $maxY; - /** * @param float $minX Input minimum X coordinate. * @param float $maxX Input maximum X coordinate. * @param float $minY Input minimum Y coordinate. * @param float $maxY Input maximum Y coordinate. */ - public function __construct( - float $minX, - float $maxX, - float $minY, - float $maxY - ) { - $this->minX = $minX; - $this->maxX = $maxX; - $this->minY = $minY; - $this->maxY = $maxY; - } + public function __construct(private float $minX, private float $maxX, private float $minY, private float $maxY) {} /** * Retrieves the minimum x coordinate. diff --git a/src/Geometry/MinMax.php b/src/Geometry/MinMax.php index 3e04e6ae..84787df3 100644 --- a/src/Geometry/MinMax.php +++ b/src/Geometry/MinMax.php @@ -9,24 +9,11 @@ */ class MinMax { - /** - * @var float Minimum. - */ - private float $min; - /** - * @var float Maximum. - */ - private float $max; - /** * @param float $min Input minimum. * @param float $max Input maximum. */ - public function __construct(float $min, float $max) - { - $this->min = $min; - $this->max = $max; - } + public function __construct(private readonly float $min, private readonly float $max) {} /** * @return float Retrieves the minimum. diff --git a/src/Geometry/Point.php b/src/Geometry/Point.php index 57906202..f94ad890 100644 --- a/src/Geometry/Point.php +++ b/src/Geometry/Point.php @@ -15,24 +15,11 @@ */ class Point implements ArrayAccess { - /** - * @var float X coordinate. - */ - private float $x; - /** - * @var float Y coordinate. - */ - private float $y; - /** * @param float $x Input x coordinate. * @param float $y Input y coordinate. */ - public function __construct(float $x, float $y) - { - $this->x = $x; - $this->y = $y; - } + public function __construct(private float $x, private float $y) {} /** * Retrieves the x coordinate. diff --git a/src/Geometry/Polygon.php b/src/Geometry/Polygon.php index 75aad681..7db2bd3d 100644 --- a/src/Geometry/Polygon.php +++ b/src/Geometry/Polygon.php @@ -4,12 +4,14 @@ namespace Mindee\Geometry; +use Stringable; + use function count; /** * Polygon represented as a set of coordinates (vertices/points). */ -class Polygon +class Polygon implements Stringable { /** * @var array|null Vertices of the polygon. diff --git a/src/Input/LocalInputSource.php b/src/Input/LocalInputSource.php index 968a29b4..9963f2b0 100644 --- a/src/Input/LocalInputSource.php +++ b/src/Input/LocalInputSource.php @@ -12,11 +12,11 @@ use Exception; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeMimeTypeException; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Error\MindeeSourceException; use Mindee\Image\ImageCompressor; -use Mindee\PDF\PDFCompressor; -use Mindee\PDF\PDFUtils; +use Mindee\Pdf\PdfCompressor; +use Mindee\Pdf\PdfUtils; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\PdfParserException; use setasign\Fpdi\PdfReader\PdfReaderException; @@ -61,7 +61,7 @@ abstract class LocalInputSource extends InputSource /** * @var string|null Path of the file for files retrieved from a path. */ - public ?string $filePath; + public ?string $filePath = null; /** * Checks if the file needs fixing. @@ -108,7 +108,7 @@ public function __construct() * * @return boolean */ - public function isPDF(): bool + public function isPdf(): bool { $this->checkMimeType(); return $this->fileMimetype === 'application/pdf'; @@ -118,12 +118,12 @@ public function isPDF(): bool * Counts the amount of pages in a PDF. * * @return integer - * @throws MindeePDFException Throws if the source pdf can't be properly processed. + * @throws MindeePdfException Throws if the source pdf can't be properly processed. * @throws MindeeSourceException Throws if the source isn't a pdf. */ public function getPageCount(): int { - if (!$this->isPDF()) { + if (!$this->isPdf()) { throw new MindeeSourceException( "File is not a PDF.", ErrorCode::USER_OPERATION_ERROR @@ -133,7 +133,7 @@ public function getPageCount(): int try { return $pdf->setSourceFile($this->fileObject->getFilename()); } catch (PdfParserException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -164,9 +164,9 @@ 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. - * @throws MindeePDFException Throws if the pdf file can't be processed. + * @throws MindeePdfException Throws if the pdf file can't be processed. */ - public function mergePDFPages(array $pageNumbers): void + public function mergePdfPages(array $pageNumbers): void { try { $pdf = new Fpdi(); @@ -178,7 +178,7 @@ public function mergePDFPages(array $pageNumbers): void $this->saveBytesAsFile($pdf->Output($this->fileName, 'S')); $pdf->Close(); } catch (PdfParserException|PdfReaderException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -191,9 +191,9 @@ public function mergePDFPages(array $pageNumbers): void * @param integer $threshold Semi-arbitrary threshold of minimum bytes on the page for it to be considered empty. * * @return boolean - * @throws MindeePDFException Throws if the pdf file can't be processed. + * @throws MindeePdfException Throws if the pdf file can't be processed. */ - public function isPDFEmpty(int $threshold = 1024): bool + public function isPdfEmpty(int $threshold = 1024): bool { try { $pdf = new Fpdi(); @@ -204,14 +204,14 @@ public function isPDFEmpty(int $threshold = 1024): bool $pdfPage->setSourceFile($this->fileObject->getFilename()); $pdfPage->AddPage(); $pdfPage->useTemplate($pdfPage->importPage($pageNumber + 1)); - if (strlen($pdfPage->Output('', 'S')) > $threshold) { + if (strlen((string) $pdfPage->Output('', 'S')) > $threshold) { $pdfPage->Close(); return false; } $pdfPage->Close(); } } catch (PdfParserException|PdfReaderException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -237,7 +237,7 @@ public function readContents(): array * * @throws MindeeSourceException Throws if the file couldn't be fixed. */ - public function fixPDF(): void + public function fixPdf(): void { if (str_starts_with($this->fileMimetype, "image/")) { error_log("Input file is an image, skipping PDF fix."); @@ -283,15 +283,15 @@ public function compress( bool $forceSourceTextCompression = false, bool $disableSourceText = true ): void { - if ($this->isPDF()) { - $this->fileObject = PDFCompressor::compress( + if ($this->isPdf()) { + $this->fileObject = PdfCompressor::compress( $this->fileObject, $quality, $forceSourceTextCompression, $disableSourceText ); $this->fileMimetype = 'application/pdf'; - $pathInfo = pathinfo($this->filePath); + $pathInfo = pathinfo((string) $this->filePath); $this->filePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . '.pdf'; } else { $this->fileObject = ImageCompressor::compress( @@ -301,7 +301,7 @@ public function compress( $maxHeight ); $this->fileMimetype = 'image/jpeg'; - $pathInfo = pathinfo($this->filePath); + $pathInfo = pathinfo((string) $this->filePath); $this->filePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . '.jpg'; } } @@ -314,10 +314,10 @@ public function compress( */ public function hasSourceText(): bool { - if (!$this->isPDF()) { + if (!$this->isPdf()) { return false; } - return PDFUtils::hasSourceText($this->filePath); + return PdfUtils::hasSourceText($this->filePath); } @@ -325,12 +325,12 @@ public function hasSourceText(): bool * Applies PDF-specific operations on the current file based on the specified PageOptions. * * @param PageOptions|null $pageOptions The options specifying which pages to modify or retain in the PDF file. - * @throws MindeePDFException If a PDF processing error occurs during the operation. + * @throws MindeePdfException If a PDF processing error occurs during the operation. */ public function applyPageOptions(?PageOptions $pageOptions): void { - if ($this->isPDFEmpty()) { - throw new MindeePDFException( + if ($this->isPdfEmpty()) { + throw new MindeePdfException( "Pages are empty in PDF file.", ErrorCode::USER_INPUT_ERROR ); @@ -365,17 +365,17 @@ public function applyPageOptions(?PageOptions $pageOptions): void } $pagesToKeep = array_diff($allPages, $pagesToRemove); } else { - throw new MindeePDFException( + throw new MindeePdfException( "Unknown operation '" . $pageOptions->operation . "'.", ErrorCode::USER_OPERATION_ERROR ); } if (count($pagesToKeep) < 1) { - throw new MindeePDFException( + throw new MindeePdfException( "Resulting PDF would have no pages left.", ErrorCode::USER_OPERATION_ERROR ); } - $this->mergePDFPages($pagesToKeep); + $this->mergePdfPages($pagesToKeep); } } diff --git a/src/Input/PageOptions.php b/src/Input/PageOptions.php index 999c6867..1f211217 100644 --- a/src/Input/PageOptions.php +++ b/src/Input/PageOptions.php @@ -22,33 +22,12 @@ */ class PageOptions { - /** - * @var array|null Indexes of the page to apply the transformations to. - */ - public ?array $pageIndexes; - /** - * @var string Operation to apply to the page. - */ - public string $operation; - /** - * @var integer Apply the operation only if the document has at least this many pages. - */ - public int $onMinPage; - /** * @param array|null $pageIndexes Indexes of the page. * @param string $operation Operation to apply. * @param integer $onMinPage Minimum page amount. */ - public function __construct( - ?array $pageIndexes = null, - string $operation = KEEP_ONLY, - int $onMinPage = 0 - ) { - $this->pageIndexes = $pageIndexes; - $this->operation = $operation; - $this->onMinPage = $onMinPage; - } + public function __construct(public ?array $pageIndexes = null, public string $operation = KEEP_ONLY, public int $onMinPage = 0) {} /** diff --git a/src/Input/URLInputSource.php b/src/Input/UrlInputSource.php similarity index 98% rename from src/Input/URLInputSource.php rename to src/Input/UrlInputSource.php index 30f9c3c7..41116abf 100644 --- a/src/Input/URLInputSource.php +++ b/src/Input/UrlInputSource.php @@ -10,7 +10,7 @@ /** * A local or distant URL input. */ -class URLInputSource extends InputSource +class UrlInputSource extends InputSource { /** * @var string The Uniform Resource Locator. @@ -70,7 +70,7 @@ public function asLocalInputSource( */ private static function getFileExtension(?string $filename): ?string { - $extension = pathinfo($filename, PATHINFO_EXTENSION); + $extension = pathinfo((string) $filename, PATHINFO_EXTENSION); return $extension ? "." . strtolower($extension) : null; } diff --git a/src/PDF/CustomFPDI.php b/src/Pdf/CustomFpdi.php similarity index 97% rename from src/PDF/CustomFPDI.php rename to src/Pdf/CustomFpdi.php index b72e8645..96551c12 100644 --- a/src/PDF/CustomFPDI.php +++ b/src/Pdf/CustomFpdi.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\PDF; +namespace Mindee\Pdf; use setasign\Fpdi\Fpdi; use setasign\Fpdi\FpdiTrait; @@ -12,7 +12,7 @@ /** * Custom wrapper to add text rotation to FPDI. */ -class CustomFPDI extends Fpdi +class CustomFpdi extends Fpdi { use FpdiTrait; diff --git a/src/PDF/PDFCompressor.php b/src/Pdf/PdfCompressor.php similarity index 83% rename from src/PDF/PDFCompressor.php rename to src/Pdf/PdfCompressor.php index a2681a6f..8c474157 100644 --- a/src/PDF/PDFCompressor.php +++ b/src/Pdf/PdfCompressor.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace Mindee\PDF; +namespace Mindee\Pdf; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Error\MindeeUnhandledException; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; @@ -21,7 +21,7 @@ /** * PDF compression class. */ -class PDFCompressor +class PdfCompressor { /** * Compresses each page of a provided PDF stream. Skips if force_source_text isn't set and source text is detected. @@ -30,7 +30,7 @@ class PDFCompressor * @param integer $quality Compression quality (70-100 for most JPG images in the test dataset). * @param boolean $forceSourceTextCompression If true, attempts to re-write detected text. * @param boolean $disableSourceText If true, doesn't re-apply source text to the original PDF. - * @throws MindeePDFException Throws if the operation fails at any step. + * @throws MindeePdfException Throws if the operation fails at any step. * //phpcs:disable * @throws MindeeUnhandledException Throws if one of the dependencies isn't installed. */ @@ -44,7 +44,7 @@ public static function compress( DependencyChecker::isImageMagickAvailable(); DependencyChecker::isGhostscriptAvailable(); try { - $pdfPath = PDFUtils::extractFilePath($input); + $pdfPath = PdfUtils::extractFilePath($input); $initialFileSize = filesize($pdfPath); $config = new Config(); $config->setDataTmFontInfoHasToBeIncluded(true); @@ -63,25 +63,25 @@ public static function compress( error_log("[WARNING] Source-text detected in input PDF '$pdfPath'. Aborting operation."); $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; copy($pdfPath, $outputPath); - return PDFUtils::toCURLFile($outputPath); + return PdfUtils::toCURLFile($outputPath); } } try { - $fpdi = new CustomFPDI(); + $fpdi = new CustomFpdi(); $pageCount = $fpdi->setSourceFile($pdfPath); } catch (CrossReferenceException) { error_log("[WARNING] PDF format for '$pdfPath' is not directly supported." . " Output PDF will be rasterized and source text won't be available."); - $pdfPath = PDFUtils::downgradePDFVersion($pdfPath); - $fpdi = new CustomFPDI(); + $pdfPath = PdfUtils::downgradePdfVersion($pdfPath); + $fpdi = new CustomFpdi(); $pdf = $parser->parseFile($pdfPath); $pageCount = $fpdi->setSourceFile($pdfPath); } - $outPdf = new CustomFPDI(); + $outPdf = new CustomFpdi(); for ($i = 1; $i <= $pageCount; $i++) { - [$tempJpegFile, $orientation] = static::processPDFPage($pdfPath, $i, $quality); + [$tempJpegFile, $orientation] = static::processPdfPage($pdfPath, $i, $quality); [$width, $height] = getimagesize($tempJpegFile); $outPdf->AddPage($orientation, [$width, $height]); $outPdf->Image($tempJpegFile, 0, 0, $width, $height); @@ -94,16 +94,16 @@ public static function compress( $outputPath = tempnam(sys_get_temp_dir(), 'compressed_pdf_') . '.pdf'; $outPdf->Output('F', $outputPath); - $finalPDFSize = filesize($outputPath); + $finalPdfSize = filesize($outputPath); - if ($initialFileSize < $finalPDFSize) { + if ($initialFileSize < $finalPdfSize) { error_log("[WARNING] Compressed PDF for '$pdfPath' would be larger than input." . " Aborting operation."); - return PDFUtils::toCURLFile(PDFUtils::extractFilePath($input)); + return PdfUtils::toCURLFile(PdfUtils::extractFilePath($input)); } - return PDFUtils::toCURLFile($outputPath); + return PdfUtils::toCURLFile($outputPath); } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Couldn't compress PDF.", ErrorCode::FILE_OPERATION_ABORTED, $e @@ -113,18 +113,18 @@ public static function compress( /** * @param Page $inputPage Input page. - * @param CustomFPDI $outputPdf Output PDF handle. - * @throws MindeePDFException Throws if text can't be inserted into the page. + * @param CustomFpdi $outputPdf Output PDF handle. + * @throws MindeePdfException Throws if text can't be inserted into the page. */ - protected static function injectTextForPage(Page $inputPage, CustomFPDI $outputPdf): void + protected static function injectTextForPage(Page $inputPage, CustomFpdi $outputPdf): void { try { - $textElements = PDFUtils::extractTextElements($inputPage); + $textElements = PdfUtils::extractTextElements($inputPage); foreach ($textElements as $element) { - PDFUtils::addTextElement($outputPdf, $element); + PdfUtils::addTextElement($outputPdf, $element); } } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Couldn't inject text into the new file.", ErrorCode::PDF_CANT_EDIT, $e @@ -139,9 +139,9 @@ protected static function injectTextForPage(Page $inputPage, CustomFPDI $outputP * @param integer $pageIndex The index of the page to process. * @param integer $imageQuality The quality setting for JPEG compression. * @return array{0: string, 1: string} Path to the temporary JPEG file and orientation of the page. - * @throws MindeePDFException If there's an error processing the page. + * @throws MindeePdfException If there's an error processing the page. */ - protected static function processPDFPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array + protected static function processPdfPage(string $sourcePdfPath, int $pageIndex, int $imageQuality): array { try { $singlePagePdf = new Fpdi(); @@ -169,7 +169,7 @@ protected static function processPDFPage(string $sourcePdfPath, int $pageIndex, return [$tempJpegFile, $size['orientation']]; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Couldn't process PDF page $pageIndex.", ErrorCode::PDF_CANT_PROCESS, $e diff --git a/src/PDF/PDFUtils.php b/src/Pdf/PdfUtils.php similarity index 89% rename from src/PDF/PDFUtils.php rename to src/Pdf/PdfUtils.php index 1eb6718c..1e0aefca 100644 --- a/src/PDF/PDFUtils.php +++ b/src/Pdf/PdfUtils.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Mindee\PDF; +namespace Mindee\Pdf; use CURLFile; use Exception; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeImageException; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Smalot\PdfParser\Config; use Smalot\PdfParser\Font; use Smalot\PdfParser\Page; @@ -23,12 +23,12 @@ /** * PDF utility class. */ -class PDFUtils +class PdfUtils { /** * @param SplFileObject|Imagick|CURLFile|string|resource $input Input file. Accepts SplFileObject, Imagick, Curl, resources & paths. * @return string Path of the file. - * @throws MindeePDFException Throws if a path can't be extracted from the input. + * @throws MindeePdfException Throws if a path can't be extracted from the input. */ public static function extractFilePath(mixed $input): string { @@ -53,12 +53,12 @@ public static function extractFilePath(mixed $input): string return $tempPath; } else { - throw new MindeePDFException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); + throw new MindeePdfException('Input PDF must be a SplFileObject, path, resource or Imagick handle.'); } - } catch (MindeePDFException $e) { + } catch (MindeePdfException $e) { throw $e; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Conversion to MagickImage failed.\n", ErrorCode::IMAGE_CANT_PROCESS, $e @@ -87,7 +87,7 @@ public static function hasSourceText(string $pdfPath): bool * @param string $pdfPath Path to the PDF file. * @return array A page-indexed array of text elements. * Each text element includes text content, position, font, size, and color. - * @throws MindeePDFException Throws if the PDF can't be parsed or text elements can't be extracted. + * @throws MindeePdfException Throws if the PDF can't be parsed or text elements can't be extracted. */ public static function extractPagesTextElements(string $pdfPath): array { @@ -106,7 +106,7 @@ public static function extractPagesTextElements(string $pdfPath): array return $allPagesTextElements; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( 'Failed to parse PDF or extract text elements: ', ErrorCode::PDF_CANT_PROCESS, $e @@ -120,10 +120,10 @@ public static function extractPagesTextElements(string $pdfPath): array * * @param string $inputPath Input PDF path. * @return string Output path. - * @throws MindeePDFException Throws if the file can't be handled through Imagick. - * @throws Exception Will be thrown as MindeePDFException, this is just for PHPCS linting purposes. + * @throws MindeePdfException Throws if the file can't be handled through ghostscript. + * @throws Exception Will be thrown as MindeePdfException, this is just for PHPCS linting purposes. */ - public static function downgradePDFVersion(string $inputPath): string + public static function downgradePdfVersion(string $inputPath): string { try { $outputPath = tempnam(sys_get_temp_dir(), 'downgrade_pdf_') . '.pdf'; @@ -139,7 +139,7 @@ public static function downgradePDFVersion(string $inputPath): string return $outputPath; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Cannot downgrade PDF version.", ErrorCode::PDF_CANT_PROCESS, $e @@ -154,7 +154,7 @@ public static function downgradePDFVersion(string $inputPath): string * @param Page $page Page object. * @return array> An array of text elements, each containing text content, * position, font, size, and color. - * @throws MindeePDFException Throws if the text elements can't be extracted. + * @throws MindeePdfException Throws if the text elements can't be extracted. */ public static function extractTextElements(Page $page): array { @@ -180,7 +180,7 @@ public static function extractTextElements(Page $page): array return $textElements; } catch (Exception $e) { - throw new MindeePDFException( + throw new MindeePdfException( 'Failed to parse text elements: ', ErrorCode::PDF_CANT_PROCESS, $e @@ -195,7 +195,7 @@ public static function extractTextElements(Page $page): array protected static function standardizeFontName(string $fontName): array { $cleanName = preg_replace('/^.*?\+/', '', $fontName); - $parts = explode('-', $cleanName, 2); + $parts = explode('-', (string) $cleanName, 2); $fontFamily = $parts[0]; $fontStyle = $parts[1] ?? ''; @@ -217,10 +217,10 @@ protected static function standardizeFontName(string $fontName): array /** * Adds a text element to the output PDF. * - * @param CustomFPDI $pdf The output PDF object. + * @param CustomFpdi $pdf The output PDF object. * @param array $element Text element array containing text, position, font, size, and color. */ - public static function addTextElement(CustomFPDI $pdf, array $element): void + public static function addTextElement(CustomFpdi $pdf, array $element): void { $fontInfo = static::standardizeFontName($element['font']->getName()); $pageHeight = $pdf->GetPageHeight(); diff --git a/src/V1/Client.php b/src/V1/Client.php index c07f9dc3..b187b962 100644 --- a/src/V1/Client.php +++ b/src/V1/Client.php @@ -27,14 +27,14 @@ use Mindee\Input\LocalResponse; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\WorkflowOptions; -use Mindee\V1\HTTP\Endpoint; -use Mindee\V1\HTTP\MindeeAPI; -use Mindee\V1\HTTP\MindeeWorkflowAPI; -use Mindee\V1\HTTP\ResponseValidation; -use Mindee\V1\HTTP\WorkflowEndpoint; +use Mindee\V1\Http\Endpoint; +use Mindee\V1\Http\MindeeApi; +use Mindee\V1\Http\MindeeWorkflowApi; +use Mindee\V1\Http\ResponseValidation; +use Mindee\V1\Http\WorkflowEndpoint; use Mindee\V1\Parsing\Common\AsyncPredictResponse; use Mindee\V1\Parsing\Common\PredictResponse; use Mindee\V1\Parsing\Common\WorkflowResponse; @@ -77,13 +77,13 @@ public function __construct(?string $apiKey = null) * Load a document from an absolute path, as a string. * * @param string $filePath Path of the file. - * @param boolean $fixPDF Whether the PDF should be fixed or not. + * @param boolean $fixPdf Whether the PDF should be fixed or not. */ - public function sourceFromPath(string $filePath, bool $fixPDF = false): PathInput + public function sourceFromPath(string $filePath, bool $fixPdf = false): PathInput { $input = new PathInput($filePath); - if ($fixPDF) { - $input->fixPDF(); + if ($fixPdf) { + $input->fixPdf(); } return $input; } @@ -92,13 +92,13 @@ public function sourceFromPath(string $filePath, bool $fixPDF = false): PathInpu * Load a document from a normal PHP file object. * * @param SplFileObject|CURLFile|string|resource $file File object as created from the file() function. - * @param boolean $fixPDF Whether the PDF should be fixed or not. + * @param boolean $fixPdf Whether the PDF should be fixed or not. */ - public function sourceFromFile(mixed $file, bool $fixPDF = false): FileInput + public function sourceFromFile(mixed $file, bool $fixPdf = false): FileInput { $input = new FileInput($file); - if ($fixPDF) { - $input->fixPDF(); + if ($fixPdf) { + $input->fixPdf(); } return $input; } @@ -108,13 +108,13 @@ public function sourceFromFile(mixed $file, bool $fixPDF = false): FileInput * * @param string $fileBytes File object in raw bytes. * @param string $fileName File name, mandatory. - * @param boolean $fixPDF Whether the PDF should be fixed or not. + * @param boolean $fixPdf Whether the PDF should be fixed or not. */ - public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPDF = false): BytesInput + public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPdf = false): BytesInput { $input = new BytesInput($fileBytes, $fileName); - if ($fixPDF) { - $input->fixPDF(); + if ($fixPdf) { + $input->fixPdf(); } return $input; } @@ -124,13 +124,13 @@ public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPD * * @param string $fileB64 File object in Base64. * @param string $fileName File name, mandatory. - * @param boolean $fixPDF Whether the PDF should be fixed or not. + * @param boolean $fixPdf Whether the PDF should be fixed or not. */ - public function sourceFromB64String(string $fileB64, string $fileName, bool $fixPDF = false): Base64Input + public function sourceFromB64String(string $fileB64, string $fileName, bool $fixPdf = false): Base64Input { $input = new Base64Input($fileB64, $fileName); - if ($fixPDF) { - $input->fixPDF(); + if ($fixPdf) { + $input->fixPdf(); } return $input; } @@ -140,9 +140,9 @@ public function sourceFromB64String(string $fileB64, string $fileName, bool $fix * * @param string $url File URL. Must start with "https://". */ - public function sourceFromUrl(string $url): URLInputSource + public function sourceFromUrl(string $url): UrlInputSource { - return new URLInputSource($url); + return new UrlInputSource($url); } /** @@ -159,7 +159,7 @@ private function constructEndpoint( ): Endpoint { $endpointVersion = $endpointVersion !== '' ? $endpointVersion : '1'; - $endpointSettings = new MindeeAPI($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); + $endpointSettings = new MindeeApi($this->apiKey, $endpointName, $endpointOwner, $endpointVersion); return new Endpoint($endpointName, $endpointOwner, $endpointVersion, $endpointSettings); } @@ -324,7 +324,7 @@ private function makeWorkflowExecutionRequest( string $workflowId, PredictMethodOptions $options ): WorkflowResponse { - $workflowRouterSettings = new MindeeWorkflowAPI($this->apiKey, $workflowId); + $workflowRouterSettings = new MindeeWorkflowApi($this->apiKey, $workflowId); $options->endpoint = new WorkflowEndpoint($workflowRouterSettings); if (!$options->pageOptions->isEmpty()) { if ($inputDoc instanceof LocalInputSource) { @@ -412,7 +412,7 @@ public function parse( if (null === $options) { $options = new PredictMethodOptions(); } - if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } $options->endpoint ??= $this->constructOTSEndpoint( @@ -497,7 +497,7 @@ public function enqueue( if (null === $options) { $options = new PredictMethodOptions(); } - if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } $options->endpoint ??= $this->constructOTSEndpoint( @@ -566,7 +566,7 @@ public function executeWorkflow( if (null === $options) { $options = new WorkflowOptions(); } - if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) { + if ($pageOptions !== null && $inputDoc instanceof LocalInputSource && $inputDoc->isPdf()) { $this->cutDocPages($inputDoc, $pageOptions); } diff --git a/src/V1/ClientOptions/CommonOptions.php b/src/V1/ClientOptions/CommonOptions.php index 531cbfbb..e6493c76 100644 --- a/src/V1/ClientOptions/CommonOptions.php +++ b/src/V1/ClientOptions/CommonOptions.php @@ -9,21 +9,12 @@ */ abstract class CommonOptions { - /** - * @var boolean Whether to include the full OCR text response in compatible APIs. - * This performs a full OCR operation on the server and will increase response time. - */ - public bool $fullText; - /** * Prediction options. - * @param boolean $fullText Whether to include the full OCR text response in compatible APIs. - * This performs a full OCR operation on the server and will increase response time. + * @param boolean $fullText Whether to include the full Ocr text response in compatible APIs. + * This performs a full Ocr operation on the server and will increase response time. */ - public function __construct(bool $fullText = false) - { - $this->fullText = $fullText; - } + public function __construct(public bool $fullText = false) {} /** * @param boolean $fullText Whether to include the full text. diff --git a/src/V1/ClientOptions/PredictMethodOptions.php b/src/V1/ClientOptions/PredictMethodOptions.php index 076918bb..360215b4 100644 --- a/src/V1/ClientOptions/PredictMethodOptions.php +++ b/src/V1/ClientOptions/PredictMethodOptions.php @@ -5,8 +5,8 @@ namespace Mindee\V1\ClientOptions; use Mindee\Input\PageOptions; -use Mindee\V1\HTTP\Endpoint; -use Mindee\V1\HTTP\WorkflowEndpoint; +use Mindee\V1\Http\Endpoint; +use Mindee\V1\Http\WorkflowEndpoint; /** * Handles options tied to prediction method. diff --git a/src/V1/ClientOptions/PredictOptions.php b/src/V1/ClientOptions/PredictOptions.php index 99ccb908..26276199 100644 --- a/src/V1/ClientOptions/PredictOptions.php +++ b/src/V1/ClientOptions/PredictOptions.php @@ -9,35 +9,21 @@ */ class PredictOptions extends CommonOptions { - /** - * @var boolean Whether to include the full text for each page. - * This performs a full OCR operation on the server and will increase response time. - */ - public bool $includeWords; - - /** - * @var boolean Whether to include cropper results for each page. - * This performs a cropping operation on the server and may increase response time. - */ - public bool $cropper; - /** * Prediction options. - * @param boolean $fullText Whether to include the full OCR text response in compatible APIs. - * This performs a full OCR operation on the server and will increase response time. + * @param boolean $fullText Whether to include the full Ocr text response in compatible APIs. + * This performs a full Ocr operation on the server and will increase response time. * @param boolean $includeWords Whether to include the full text for each page. - * This performs a full OCR operation on the server and will increase response time. + * This performs a full Ocr operation on the server and will increase response time. * @param boolean $cropper Whether to include cropper results for each page. * This performs a cropping operation on the server and may increase response time. */ public function __construct( bool $fullText = false, - bool $includeWords = false, - bool $cropper = false + public bool $includeWords = false, + public bool $cropper = false ) { parent::__construct($fullText); - $this->includeWords = $includeWords; - $this->cropper = $cropper; } /** diff --git a/src/V1/ClientOptions/WorkflowOptions.php b/src/V1/ClientOptions/WorkflowOptions.php index 051ae962..45d70e63 100644 --- a/src/V1/ClientOptions/WorkflowOptions.php +++ b/src/V1/ClientOptions/WorkflowOptions.php @@ -9,27 +9,6 @@ */ class WorkflowOptions extends CommonOptions { - /** - * @var string|null Alias to give to the document. - */ - public ?string $alias; - - /** - * @var string|null Priority to give to the document. - */ - public ?string $priority; - - /** - * @var string|null A unique, encrypted URL for accessing the document validation interface without requiring - * authentication. - */ - public ?string $publicUrl; - - /** - * @var boolean|null Whether to enable Retrieval-Augmented Generation. - */ - public ?bool $rag; - /** * @param string|null $alias Alias for the document. * @param string|null $priority Priority for the document. @@ -38,16 +17,12 @@ class WorkflowOptions extends CommonOptions * @param boolean $rag Whether to enable Retrieval-Augmented Generation. */ public function __construct( - ?string $alias = null, - ?string $priority = null, + public ?string $alias = null, + public ?string $priority = null, bool $fullTextOcr = false, - ?string $publicUrl = null, - bool $rag = false + public ?string $publicUrl = null, + public ?bool $rag = false ) { parent::__construct($fullTextOcr); - $this->alias = $alias; - $this->priority = $priority; - $this->publicUrl = $publicUrl; - $this->rag = $rag; } } diff --git a/src/V1/HTTP/BaseAPI.php b/src/V1/Http/BaseApi.php similarity index 86% rename from src/V1/HTTP/BaseAPI.php rename to src/V1/Http/BaseApi.php index 457dca2e..fafb1b4f 100644 --- a/src/V1/HTTP/BaseAPI.php +++ b/src/V1/Http/BaseApi.php @@ -6,7 +6,7 @@ * Settings and variables linked to all API usage. */ -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; /** * Default key name for the API key entry in environment variables. @@ -45,25 +45,22 @@ */ function getUserAgent(): string { - switch (PHP_OS_FAMILY) { - case "Darwin": - $os = "macos"; - break; - default: - $os = strtolower(PHP_OS_FAMILY); - } + $os = match (PHP_OS_FAMILY) { + "Darwin" => "macos", + default => strtolower(PHP_OS_FAMILY), + }; return 'mindee-api-php@v' . VERSION . ' php-v' . PHP_VERSION . ' ' . $os; } /** * Base class for API settings. */ -abstract class BaseAPI +abstract class BaseApi { /** * @var string|null API key. */ - public ?string $apiKey; + public ?string $apiKey = null; /** * @var integer Timeout for the request, in ms. */ @@ -104,8 +101,8 @@ protected function setTimeout(int $value): void protected function setFromEnv(): void { $envVars = [ - BASE_URL_ENV_NAME => [$this, 'setBaseUrl'], - REQUEST_TIMEOUT_ENV_NAME => [$this, 'setTimeout'], + BASE_URL_ENV_NAME => $this->setBaseUrl(...), + REQUEST_TIMEOUT_ENV_NAME => $this->setTimeout(...), ]; foreach ($envVars as $key => $func) { $envVal = getenv($key) ?: ''; @@ -121,7 +118,7 @@ protected function setFromEnv(): void * * @param string|null $apiKey Optional API key. */ - protected function setApiKey(?string $apiKey = null): void + protected function setAPIKey(?string $apiKey = null): void { $envVal = !getenv(API_KEY_ENV_NAME) ? '' : getenv(API_KEY_ENV_NAME); if (!$apiKey) { @@ -138,7 +135,7 @@ protected function setApiKey(?string $apiKey = null): void public function __construct( ?string $apiKey ) { - $this->setApiKey($apiKey); + $this->setAPIKey($apiKey); $this->baseUrl = BASE_URL_DEFAULT; $this->requestTimeout = TIMEOUT_DEFAULT; $this->setFromEnv(); diff --git a/src/V1/HTTP/BaseEndpoint.php b/src/V1/Http/BaseEndpoint.php similarity index 87% rename from src/V1/HTTP/BaseEndpoint.php rename to src/V1/Http/BaseEndpoint.php index 1c360253..1439f57e 100644 --- a/src/V1/HTTP/BaseEndpoint.php +++ b/src/V1/Http/BaseEndpoint.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use CurlHandle; @@ -12,17 +12,9 @@ abstract class BaseEndpoint { /** - * @var MindeeAPI|MindeeWorkflowAPI Settings of the endpoint. + * @param MindeeApi|MindeeWorkflowApi $settings Input settings. */ - public MindeeAPI|MindeeWorkflowAPI $settings; - - /** - * @param MindeeAPI|MindeeWorkflowAPI $settings Input settings. - */ - public function __construct(MindeeAPI|MindeeWorkflowAPI $settings) - { - $this->settings = $settings; - } + public function __construct(public MindeeApi|MindeeWorkflowApi $settings) {} /** * Starts a CURL session using GET. diff --git a/src/V1/HTTP/Endpoint.php b/src/V1/Http/Endpoint.php similarity index 85% rename from src/V1/HTTP/Endpoint.php rename to src/V1/Http/Endpoint.php index 9b10b6fa..94a87c6e 100644 --- a/src/V1/HTTP/Endpoint.php +++ b/src/V1/Http/Endpoint.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V1\ClientOptions\PredictMethodOptions; /** @@ -15,35 +15,19 @@ */ class Endpoint extends BaseEndpoint { - /** - * @var string Url (name) of then endpoint. - */ - public string $urlName; - /** - * @var string Name of the endpoint's owner. - */ - public string $owner; - /** - * @var string Version of the endpoint. - */ - public string $version; - /** * @param string $urlName Url (name) of the endpoint. * @param string $owner Name of the endpoint's owner. * @param string $version Version of the endpoint. - * @param MindeeAPI $settings Settings for the endpoint. + * @param MindeeApi $settings Settings for the endpoint. */ public function __construct( - string $urlName, - string $owner, - string $version, - MindeeAPI $settings + public string $urlName, + public string $owner, + public string $version, + MindeeApi $settings ) { parent::__construct($settings); - $this->urlName = $urlName; - $this->owner = $owner; - $this->version = $version; } /** @@ -119,7 +103,7 @@ private function initCurlSessionPost( curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); $postFields = null; - if ($inputSource instanceof URLInputSource) { + if ($inputSource instanceof UrlInputSource) { $postFields = ['document' => $inputSource->url]; } elseif ($inputSource instanceof LocalInputSource) { $inputSource->checkNeedsFix(); diff --git a/src/V1/HTTP/MindeeAPI.php b/src/V1/Http/MindeeApi.php similarity index 96% rename from src/V1/HTTP/MindeeAPI.php rename to src/V1/Http/MindeeApi.php index 89f14fa9..af0b7f06 100644 --- a/src/V1/HTTP/MindeeAPI.php +++ b/src/V1/Http/MindeeApi.php @@ -6,7 +6,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; @@ -15,7 +15,7 @@ /** * Data class containing settings for endpoints. */ -class MindeeAPI extends BaseAPI +class MindeeApi extends BaseApi { /** * @var string Name of the endpoint. diff --git a/src/V1/HTTP/MindeeWorkflowAPI.php b/src/V1/Http/MindeeWorkflowApi.php similarity index 81% rename from src/V1/HTTP/MindeeWorkflowAPI.php rename to src/V1/Http/MindeeWorkflowApi.php index 3f5af199..bff07d07 100644 --- a/src/V1/HTTP/MindeeWorkflowAPI.php +++ b/src/V1/Http/MindeeWorkflowApi.php @@ -6,7 +6,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; @@ -14,12 +14,8 @@ /** * Data class containing settings for workflows. */ -class MindeeWorkflowAPI extends BaseAPI +class MindeeWorkflowApi extends BaseApi { - /** - * @var string ID of the workflow. - */ - public string $workflowId; /** * @param string|null $apiKey API key. * @param string $workflowId ID of the workflow. @@ -27,7 +23,7 @@ class MindeeWorkflowAPI extends BaseAPI */ public function __construct( ?string $apiKey, - string $workflowId + public string $workflowId ) { parent::__construct($apiKey); if (empty($this->apiKey)) { @@ -37,7 +33,6 @@ public function __construct( ErrorCode::USER_INPUT_ERROR ); } - $this->workflowId = $workflowId; $this->urlRoot = rtrim( $this->baseUrl, "/" diff --git a/src/V1/HTTP/ResponseValidation.php b/src/V1/Http/ResponseValidation.php similarity index 99% rename from src/V1/HTTP/ResponseValidation.php rename to src/V1/Http/ResponseValidation.php index bd8501c0..7a3c585e 100644 --- a/src/V1/HTTP/ResponseValidation.php +++ b/src/V1/Http/ResponseValidation.php @@ -6,7 +6,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use function count; use function is_string; diff --git a/src/V1/HTTP/WorkflowEndpoint.php b/src/V1/Http/WorkflowEndpoint.php similarity index 92% rename from src/V1/HTTP/WorkflowEndpoint.php rename to src/V1/Http/WorkflowEndpoint.php index 87568786..cb8120fa 100644 --- a/src/V1/HTTP/WorkflowEndpoint.php +++ b/src/V1/Http/WorkflowEndpoint.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Mindee\V1\HTTP; +namespace Mindee\V1\Http; use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V1\ClientOptions\WorkflowOptions; /** @@ -16,10 +16,10 @@ class WorkflowEndpoint extends BaseEndpoint { /** - * @param MindeeWorkflowAPI $settings Settings for the endpoint. + * @param MindeeWorkflowApi $settings Settings for the endpoint. */ public function __construct( - MindeeWorkflowAPI $settings + MindeeWorkflowApi $settings ) { parent::__construct($settings); } @@ -64,7 +64,7 @@ private function initCurlSessionPost( curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->settings->requestTimeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); - if ($fileCurl instanceof URLInputSource) { + if ($fileCurl instanceof UrlInputSource) { $postFields = ['document' => $fileCurl->url]; } elseif ($fileCurl instanceof LocalInputSource) { $postFields = ['document' => $fileCurl->fileObject]; diff --git a/src/V1/Parsing/Common/ApiResponse.php b/src/V1/Parsing/Common/ApiResponse.php index 71f5a8a6..f09cb7b5 100644 --- a/src/V1/Parsing/Common/ApiResponse.php +++ b/src/V1/Parsing/Common/ApiResponse.php @@ -16,7 +16,7 @@ abstract class ApiResponse /** * @var array> Raw http result. Used for debugging purposes. */ - private array $rawHttp; + private readonly array $rawHttp; /** * @param array> $rawResponse Raw prediction array. diff --git a/src/V1/Parsing/Common/Document.php b/src/V1/Parsing/Common/Document.php index 57b97bcf..0a5075fb 100644 --- a/src/V1/Parsing/Common/Document.php +++ b/src/V1/Parsing/Common/Document.php @@ -7,16 +7,17 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Mindee\V1\Parsing\Common\Extras\Extras; -use Mindee\V1\Parsing\Common\OCR\OCR; +use Mindee\V1\Parsing\Common\Ocr\Ocr; use ReflectionClass; use ReflectionException; +use Stringable; use function array_key_exists; /** * Base class for all predictions. */ -class Document +class Document implements Stringable { /** * @var string Name of the input document. @@ -39,9 +40,9 @@ class Document */ public ?Extras $extras; /** - * @var OCR|null Potential raw text results read by the OCR (limited feature) + * @var Ocr|null Potential raw text results read by the Ocr (limited feature) */ - public ?OCR $ocr; + public ?Ocr $ocr; /** * @param string $predictionType Type of prediction. @@ -64,12 +65,12 @@ public function __construct(string $predictionType, array $rawResponse) ); } if (array_key_exists('ocr', $rawResponse) && $rawResponse['ocr']) { - $this->ocr = new OCR($rawResponse['ocr']); + $this->ocr = new Ocr($rawResponse['ocr']); } if (array_key_exists("extras", $rawResponse['inference']) && $rawResponse['inference']['extras']) { $this->extras = new Extras($rawResponse['inference']['extras']); } - $this->injectFullTextOCR($rawResponse); + $this->injectFullTextOcr($rawResponse); } /** @@ -91,7 +92,7 @@ public function __toString(): string * * @param array> $rawResponse Raw HTTP response. */ - private function injectFullTextOCR(array $rawResponse): void + private function injectFullTextOcr(array $rawResponse): void { $pages = $rawResponse['inference']['pages'] ?? []; diff --git a/src/V1/Parsing/Common/Execution.php b/src/V1/Parsing/Common/Execution.php index a7837197..ec0e24e2 100644 --- a/src/V1/Parsing/Common/Execution.php +++ b/src/V1/Parsing/Common/Execution.php @@ -11,11 +11,12 @@ use Mindee\V1\Product\Generated\GeneratedV1Document; use ReflectionClass; use ReflectionException; +use Stringable; /** * Representation of a workflow execution. */ -class Execution +class Execution implements Stringable { /** * Identifier for the batch to which the execution belongs. @@ -127,6 +128,6 @@ public function __toString(): string $objAsArray = get_object_vars($this); ksort($objAsArray); - return json_encode($objAsArray, JSON_PRETTY_PRINT); + return (string) json_encode($objAsArray, JSON_PRETTY_PRINT); } } diff --git a/src/V1/Parsing/Common/Extras/CropperExtra.php b/src/V1/Parsing/Common/Extras/CropperExtra.php index 316c1aad..112bf18b 100644 --- a/src/V1/Parsing/Common/Extras/CropperExtra.php +++ b/src/V1/Parsing/Common/Extras/CropperExtra.php @@ -5,13 +5,14 @@ namespace Mindee\V1\Parsing\Common\Extras; use Mindee\V1\Parsing\Standard\PositionField; +use Stringable; use function array_key_exists; /** * Contains information on the cropping of a prediction. */ -class CropperExtra +class CropperExtra implements Stringable { /** * @var array List of all croppings coordiantes. diff --git a/src/V1/Parsing/Common/Extras/Extras.php b/src/V1/Parsing/Common/Extras/Extras.php index cd053a4b..4e51521e 100644 --- a/src/V1/Parsing/Common/Extras/Extras.php +++ b/src/V1/Parsing/Common/Extras/Extras.php @@ -4,6 +4,8 @@ namespace Mindee\V1\Parsing\Common\Extras; +use Stringable; + use function is_scalar; /** @@ -11,20 +13,20 @@ * * Is roughly equivalent to an array of Extras, with a bit more utility. */ -class Extras +class Extras implements Stringable { /** * @var CropperExtra|null Cropper extra. */ public ?CropperExtra $cropper; /** - * @var FullTextOCRExtra|null Full text OCR extra. + * @var FullTextOcrExtra|null Full text Ocr extra. */ - public ?FullTextOCRExtra $fullTextOcr; + public ?FullTextOcrExtra $fullTextOcr; /** - * @var RAGExtra|null Rag Extra. + * @var RagExtra|null Rag Extra. */ - public ?RAGExtra $rag; + public ?RagExtra $rag; /** * @var array> Other extras. */ @@ -50,9 +52,9 @@ public function __construct(array $rawPrediction) if ($key === 'cropper' && isset($rawPrediction['cropper'])) { $this->cropper = new CropperExtra($rawPrediction['cropper']); } elseif ($key === 'full_text_ocr' && isset($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); + $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); } elseif ($key === 'rag' && isset($rawPrediction['rag'])) { - $this->rag = new RAGExtra($rawPrediction['rag']); + $this->rag = new RagExtra($rawPrediction['rag']); } else { $this->__set($key, $extra); } @@ -68,14 +70,13 @@ public function __construct(array $rawPrediction) public function addArtificialExtra(array $rawPrediction): void { if (!empty($rawPrediction['full_text_ocr'])) { - $this->fullTextOcr = new FullTextOCRExtra($rawPrediction['full_text_ocr']); + $this->fullTextOcr = new FullTextOcrExtra($rawPrediction['full_text_ocr']); } } /** - * @return string */ - public function __toString() + public function __toString(): string { $resStr = ''; foreach ($this->data as $key => $extra) { diff --git a/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php similarity index 86% rename from src/V1/Parsing/Common/Extras/FullTextOCRExtra.php rename to src/V1/Parsing/Common/Extras/FullTextOcrExtra.php index 869d8358..05635db3 100644 --- a/src/V1/Parsing/Common/Extras/FullTextOCRExtra.php +++ b/src/V1/Parsing/Common/Extras/FullTextOcrExtra.php @@ -4,10 +4,12 @@ namespace Mindee\V1\Parsing\Common\Extras; +use Stringable; + /** - * Full Text OCR result. + * Full Text Ocr result. */ -class FullTextOCRExtra +class FullTextOcrExtra implements Stringable { /** * @var string|null Text content of the full text ocr reading. @@ -34,9 +36,8 @@ public function __construct(array $rawPrediction) } /** - * @return string */ - public function __toString() + public function __toString(): string { return $this->content ?? ''; } diff --git a/src/V1/Parsing/Common/Extras/RAGExtra.php b/src/V1/Parsing/Common/Extras/RagExtra.php similarity index 93% rename from src/V1/Parsing/Common/Extras/RAGExtra.php rename to src/V1/Parsing/Common/Extras/RagExtra.php index 4d469c1b..351ea48b 100644 --- a/src/V1/Parsing/Common/Extras/RAGExtra.php +++ b/src/V1/Parsing/Common/Extras/RagExtra.php @@ -4,10 +4,12 @@ namespace Mindee\V1\Parsing\Common\Extras; +use Stringable; + /** * Contains information on the Retrieval-Augmented-Generation of a prediction. */ -class RAGExtra +class RagExtra implements Stringable { /** * @var string|null The document ID of the matching document. diff --git a/src/V1/Parsing/Common/Inference.php b/src/V1/Parsing/Common/Inference.php index 0875c344..ca2713c9 100644 --- a/src/V1/Parsing/Common/Inference.php +++ b/src/V1/Parsing/Common/Inference.php @@ -5,6 +5,7 @@ namespace Mindee\V1\Parsing\Common; use Mindee\V1\Parsing\Common\Extras\Extras; +use Stringable; use function array_key_exists; use function count; @@ -12,7 +13,7 @@ /** * Base Inference class for all predictions. */ -abstract class Inference +abstract class Inference implements Stringable { /** * @var Product Name and version of a given product, as sent back by the API. diff --git a/src/V1/Parsing/Common/Job.php b/src/V1/Parsing/Common/Job.php index e159e495..e21f711f 100644 --- a/src/V1/Parsing/Common/Job.php +++ b/src/V1/Parsing/Common/Job.php @@ -8,6 +8,7 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Exception; +use Stringable; use function array_key_exists; @@ -16,7 +17,7 @@ * * Will hold information on the queue a document has been submitted to. */ -class Job +class Job implements Stringable { /** * @var string|null ID of the job sent by the API in response to an enqueue request. @@ -41,7 +42,7 @@ class Job /** * @var array>|null Information about an error that occurred during the job processing. */ - public ?array $error; + public ?array $error = null; /** * @param array> $rawResponse Raw prediction array. @@ -81,7 +82,7 @@ public function __construct(array $rawResponse) throw new Exception("Invalid date format"); } $this->availableAt = new DateTimeImmutable('@' . $timestamp); - } catch (Exception $e2) { + } catch (Exception) { throw new MindeeApiException( "Could not create date from " . $rawResponse['available_at'], ErrorCode::API_UNPROCESSABLE_ENTITY, @@ -105,6 +106,6 @@ public function __toString(): string $objAsJson = get_object_vars($this); ksort($objAsJson); - return json_encode($objAsJson, JSON_PRETTY_PRINT); + return (string) json_encode($objAsJson, JSON_PRETTY_PRINT); } } diff --git a/src/V1/Parsing/Common/OCR/MVisionV1.php b/src/V1/Parsing/Common/Ocr/MVisionV1.php similarity index 76% rename from src/V1/Parsing/Common/OCR/MVisionV1.php rename to src/V1/Parsing/Common/Ocr/MVisionV1.php index b31688b3..95f23d62 100644 --- a/src/V1/Parsing/Common/OCR/MVisionV1.php +++ b/src/V1/Parsing/Common/Ocr/MVisionV1.php @@ -2,15 +2,17 @@ declare(strict_types=1); -namespace Mindee\V1\Parsing\Common\OCR; +namespace Mindee\V1\Parsing\Common\Ocr; + +use Stringable; /** * Mindee Vision V1. */ -class MVisionV1 +class MVisionV1 implements Stringable { /** - * @var array List of pages. + * @var array List of pages. */ public array $pages; @@ -21,7 +23,7 @@ public function __construct(array $rawPrediction) { $this->pages = []; foreach ($rawPrediction['pages'] as $pagePrediction) { - $this->pages[] = new OCRPage($pagePrediction); + $this->pages[] = new OcrPage($pagePrediction); } } diff --git a/src/V1/Parsing/Common/OCR/OCR.php b/src/V1/Parsing/Common/Ocr/Ocr.php similarity index 83% rename from src/V1/Parsing/Common/OCR/OCR.php rename to src/V1/Parsing/Common/Ocr/Ocr.php index afc4746a..c0b5bbfc 100644 --- a/src/V1/Parsing/Common/OCR/OCR.php +++ b/src/V1/Parsing/Common/Ocr/Ocr.php @@ -2,15 +2,17 @@ declare(strict_types=1); -namespace Mindee\V1\Parsing\Common\OCR; +namespace Mindee\V1\Parsing\Common\Ocr; + +use Stringable; use function array_key_exists; use function count; /** - * OCR extraction from the entire document. + * Ocr extraction from the entire document. */ -class OCR +class Ocr implements Stringable { /** * @var MVisionV1 Mindee Vision v1 results. @@ -33,10 +35,10 @@ public function __toString(): string } /** - * Finds all lines matching the given regex in the OCR data, indexed by their page. + * Finds all lines matching the given regex in the Ocr data, indexed by their page. * * @param string $regex The regular expression to match against. - * @return array> All lines that match the regex, indexed by their page. + * @return array> All lines that match the regex, indexed by their page. */ public function findLineByRegex(string $regex): array { diff --git a/src/V1/Parsing/Common/OCR/OCRLine.php b/src/V1/Parsing/Common/Ocr/OcrLine.php similarity index 63% rename from src/V1/Parsing/Common/OCR/OCRLine.php rename to src/V1/Parsing/Common/Ocr/OcrLine.php index 68480840..c86672da 100644 --- a/src/V1/Parsing/Common/OCR/OCRLine.php +++ b/src/V1/Parsing/Common/Ocr/OcrLine.php @@ -2,27 +2,21 @@ declare(strict_types=1); -namespace Mindee\V1\Parsing\Common\OCR; +namespace Mindee\V1\Parsing\Common\Ocr; + +use Stringable; use function count; /** * A list of words which are on the same line. */ -class OCRLine +class OcrLine implements Stringable { /** - * @var array Words in the line. - */ - private array $words; - - /** - * @param array $words Words to insert in the line. + * @param array $words Words to insert in the line. */ - public function __construct(array $words = []) - { - $this->words = $words; - } + public function __construct(private array $words = []) {} /** * Sort the words on the line from left to right. @@ -30,15 +24,15 @@ public function __construct(array $words = []) */ public function sortOnX(): void { - usort($this->words, "Mindee\\V1\\Parsing\\Common\\OCR\\OCRPage::getMinMaxX"); + usort($this->words, OcrPage::getMinMaxX(...)); } /** * Appends a word to the line. * - * @param OCRWord $word Word to add. + * @param OcrWord $word Word to add. */ - public function add(OCRWord $word): void + 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 similarity index 70% rename from src/V1/Parsing/Common/OCR/OCRPage.php rename to src/V1/Parsing/Common/Ocr/OcrPage.php index 3cc1f80a..37a8478a 100644 --- a/src/V1/Parsing/Common/OCR/OCRPage.php +++ b/src/V1/Parsing/Common/Ocr/OcrPage.php @@ -2,33 +2,35 @@ declare(strict_types=1); -namespace Mindee\V1\Parsing\Common\OCR; +namespace Mindee\V1\Parsing\Common\Ocr; + +use Stringable; use function count; use function in_array; /** - * OCR extraction for a single page. + * Ocr extraction for a single page. */ -class OCRPage +class OcrPage implements Stringable { /** - * @var array List of all words. + * @var array List of all words. */ private array $allWords; /** - * @var array List of lines. + * @var array List of lines. */ private array $lines; /** * Checks whether the words are on the same line. * - * @param OCRWord $currentWord Reference word to compare. - * @param OCRWord $nextWord Next word to compare. + * @param OcrWord $currentWord Reference word to compare. + * @param OcrWord $nextWord Next word to compare. * @return boolean */ - private static function areWordsOnSameLine(OCRWord $currentWord, OCRWord $nextWord): bool + private static function areWordsOnSameLine(OcrWord $currentWord, OcrWord $nextWord): bool { $currentInNext = $nextWord->polygon->isPointInY($currentWord->polygon->getCentroid()); $nextInCurrent = $currentWord->polygon->isPointInY($nextWord->polygon->getCentroid()); @@ -38,40 +40,34 @@ private static function areWordsOnSameLine(OCRWord $currentWord, OCRWord $nextWo /** * Compares word positions on the X axis. Returns a sort-compliant result (0;-1;1). * - * @param OCRWord $word1 First word. - * @param OCRWord $word2 Second word. + * @param OcrWord $word1 First word. + * @param OcrWord $word2 Second word. * @return integer */ - public static function getMinMaxX(OCRWord $word1, OCRWord $word2): int + public static function getMinMaxX(OcrWord $word1, OcrWord $word2): int { $word1X = $word1->polygon->getMinMaxX()->getMin(); $word2X = $word2->polygon->getMinMaxX()->getMin(); - if ($word1X === $word2X) { - return 0; - } - return $word1X < $word2X ? -1 : 1; + return $word1X <=> $word2X; } /** * Compares word positions on the Y axis. Returns a sort-compliant result (0;-1;1). * - * @param OCRWord $word1 First word. - * @param OCRWord $word2 Second word. + * @param OcrWord $word1 First word. + * @param OcrWord $word2 Second word. * @return integer */ - public static function getMinMaxY(OCRWord $word1, OCRWord $word2): int + public static function getMinMaxY(OcrWord $word1, OcrWord $word2): int { $word1Y = $word1->polygon->getMinMaxY()->getMin(); $word2Y = $word2->polygon->getMinMaxY()->getMin(); - if ($word1Y === $word2Y) { - return 0; - } - return $word1Y < $word2Y ? -1 : 1; + return $word1Y <=> $word2Y; } /** * Puts all words on the page into an array of lines. - * @return array + * @return array */ private function toLines(): array { @@ -79,17 +75,17 @@ private function toLines(): array $indexes = []; $lines = []; foreach ($this->allWords as $_) { - $line = new OCRLine(); + $line = new OcrLine(); for ($idx = 0; $idx < count($this->allWords); $idx++) { $word = $this->allWords[$idx]; if (!in_array($idx, $indexes, true)) { if (null === $current) { $current = $word; $indexes[] = $idx; - $line = new OCRLine(); + $line = new OcrLine(); $line->add($word); } else { - if ($this->areWordsOnSameLine($current, $word)) { + if (self::areWordsOnSameLine($current, $word)) { $line->add($word); $indexes[] = $idx; } @@ -107,7 +103,7 @@ private function toLines(): array /** * Retrieves all lines on the page. - * @return array + * @return array */ public function getAllLines(): array { @@ -119,7 +115,7 @@ public function getAllLines(): array /** * Retrieves all words on the page. - * @return array + * @return array */ public function getAllWords(): array { @@ -133,9 +129,9 @@ public function __construct(array $rawPrediction) { $this->allWords = []; foreach ($rawPrediction['all_words'] as $wordPrediction) { - $this->allWords[] = new OCRWord($wordPrediction); + $this->allWords[] = new OcrWord($wordPrediction); } - usort($this->allWords, "self::getMinMaxY"); + usort($this->allWords, self::getMinMaxY(...)); } /** diff --git a/src/V1/Parsing/Common/OCR/OCRWord.php b/src/V1/Parsing/Common/Ocr/OcrWord.php similarity index 89% rename from src/V1/Parsing/Common/OCR/OCRWord.php rename to src/V1/Parsing/Common/Ocr/OcrWord.php index 62d8e634..622b4c2d 100644 --- a/src/V1/Parsing/Common/OCR/OCRWord.php +++ b/src/V1/Parsing/Common/Ocr/OcrWord.php @@ -2,14 +2,15 @@ declare(strict_types=1); -namespace Mindee\V1\Parsing\Common\OCR; +namespace Mindee\V1\Parsing\Common\Ocr; use Mindee\V1\Parsing\Standard\FieldPositionMixin; +use Stringable; /** * A single word. */ -class OCRWord +class OcrWord implements Stringable { use FieldPositionMixin; diff --git a/src/V1/Parsing/Common/Page.php b/src/V1/Parsing/Common/Page.php index 1fefe6e6..bdef85fc 100644 --- a/src/V1/Parsing/Common/Page.php +++ b/src/V1/Parsing/Common/Page.php @@ -8,6 +8,7 @@ use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeUnsetException; use Mindee\V1\Parsing\Common\Extras\Extras; +use Stringable; use function array_key_exists; use function is_subclass_of; @@ -15,7 +16,7 @@ /** * Base Page object for predictions. */ -class Page +class Page implements Stringable { /** * @var integer ID of the current page. diff --git a/src/V1/Parsing/Common/Prediction.php b/src/V1/Parsing/Common/Prediction.php index 3608c13c..94d4c8a0 100644 --- a/src/V1/Parsing/Common/Prediction.php +++ b/src/V1/Parsing/Common/Prediction.php @@ -4,10 +4,12 @@ namespace Mindee\V1\Parsing\Common; +use Stringable; + /** * Base class for prediction responses. */ -abstract class Prediction +abstract class Prediction implements Stringable { /** * @return string String representation. diff --git a/src/V1/Parsing/Common/Product.php b/src/V1/Parsing/Common/Product.php index f5b9fa90..82edf9f5 100644 --- a/src/V1/Parsing/Common/Product.php +++ b/src/V1/Parsing/Common/Product.php @@ -4,10 +4,12 @@ namespace Mindee\V1\Parsing\Common; +use Stringable; + /** * Class for keeping track of a product's info. */ -class Product +class Product implements Stringable { /** * @var string Product's name. @@ -30,7 +32,7 @@ public function __construct(array $rawPrediction) /** * @return string String representation. */ - public function __toString() + public function __toString(): string { return "$this->name v$this->version"; } diff --git a/src/V1/Parsing/Generated/GeneratedListField.php b/src/V1/Parsing/Generated/GeneratedListField.php index dfba11bf..2ed9b6b0 100644 --- a/src/V1/Parsing/Generated/GeneratedListField.php +++ b/src/V1/Parsing/Generated/GeneratedListField.php @@ -5,6 +5,7 @@ namespace Mindee\V1\Parsing\Generated; use Mindee\V1\Parsing\Standard\StringField; +use Stringable; use function is_float; use function is_int; @@ -12,11 +13,8 @@ /** * A list of value or words for generated APIs. */ -class GeneratedListField +class GeneratedListField implements Stringable { - /** @var integer|null ID of the page the object was found on */ - public ?int $pageId; - /** @var array List of values */ public array $values = []; @@ -26,10 +24,8 @@ class GeneratedListField * @param list>> $rawPrediction Array containing the list elements. * @param integer|null $pageId ID of the page. */ - public function __construct(array $rawPrediction, ?int $pageId = null) + public function __construct(array $rawPrediction, public ?int $pageId = null) { - $this->pageId = $pageId; - foreach ($rawPrediction as $value) { if (isset($value['page_id']) && is_int($value['page_id'])) { $this->pageId = $value['page_id']; diff --git a/src/V1/Parsing/Generated/GeneratedObjectField.php b/src/V1/Parsing/Generated/GeneratedObjectField.php index 17f6ff9b..28f05842 100644 --- a/src/V1/Parsing/Generated/GeneratedObjectField.php +++ b/src/V1/Parsing/Generated/GeneratedObjectField.php @@ -7,6 +7,7 @@ use Mindee\Geometry\Polygon; use Mindee\V1\Parsing\Standard\BaseField; use Mindee\V1\Parsing\Standard\PositionField; +use Stringable; use function in_array; use function is_array; @@ -20,7 +21,7 @@ * @property PositionField|null $quadrangle * @property PositionField|null $rectangle */ -class GeneratedObjectField +class GeneratedObjectField implements Stringable { /** @var integer|null ID of the page the object was found on */ public ?int $pageId; diff --git a/src/V1/Parsing/Standard/BaseField.php b/src/V1/Parsing/Standard/BaseField.php index 467f844a..0118e142 100644 --- a/src/V1/Parsing/Standard/BaseField.php +++ b/src/V1/Parsing/Standard/BaseField.php @@ -5,6 +5,7 @@ namespace Mindee\V1\Parsing\Standard; use Mindee\Geometry\Polygon; +use Stringable; use function array_key_exists; @@ -12,7 +13,7 @@ * Base class for most fields. * @template T Generic typing for value type handling. */ -abstract class BaseField +abstract class BaseField implements Stringable { use FieldConfidenceMixin; @@ -20,10 +21,6 @@ abstract class BaseField * @var T|null Raw field value. */ public mixed $value; - /** - * @var boolean Whether the field was reconstructed from other fields. - */ - public bool $reconstructed; /** * @var integer|null The document page on which the information was found. */ @@ -38,7 +35,7 @@ abstract class BaseField public function __construct( array $rawPrediction, ?int $pageId = null, - bool $reconstructed = false, + public bool $reconstructed = false, string $valueKey = 'value' ) { if (!isset($pageId) && (array_key_exists('page_id', $rawPrediction) && isset($rawPrediction['page_id']))) { @@ -46,7 +43,6 @@ public function __construct( } else { $this->pageId = $pageId; } - $this->reconstructed = $reconstructed; if (array_key_exists($valueKey, $rawPrediction) && $rawPrediction[$valueKey] !== 'N/A') { $this->value = $rawPrediction[$valueKey]; $this->setConfidence($rawPrediction); diff --git a/src/V1/Parsing/Standard/Taxes.php b/src/V1/Parsing/Standard/Taxes.php index 60479542..496aceba 100644 --- a/src/V1/Parsing/Standard/Taxes.php +++ b/src/V1/Parsing/Standard/Taxes.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Parsing\Standard; use ArrayObject; +use Stringable; /** * List of tax lines information. * @extends ArrayObject */ -class Taxes extends ArrayObject +class Taxes extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. @@ -43,7 +44,7 @@ private static function lineSeparator(string $char): string /** * @return string String representation. */ - public function __toString() + public function __toString(): string { $outStr = "\n" . self::lineSeparator('-') . "\n"; $outStr .= " | Base | Code | Rate (%) | Amount |\n"; diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php index c420113d..59e75647 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The shipping company responsible for transporting the goods. */ -class BillOfLadingV1Carrier +class BillOfLadingV1Carrier implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,23 +29,18 @@ class BillOfLadingV1Carrier * @var string|null The Standard Carrier Alpha Code (SCAC) of the carrier. */ public ?string $scac; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->name = $rawPrediction["name"] ?? null; $this->professionalNumber = $rawPrediction["professional_number"] ?? null; $this->scac = $rawPrediction["scac"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php index 484a287a..2df1d83a 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The goods being shipped. */ -class BillOfLadingV1CarrierItem +class BillOfLadingV1CarrierItem implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -40,16 +41,12 @@ class BillOfLadingV1CarrierItem * @var string|null The unit of measurement for weights. */ public ?string $weightUnit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -62,7 +59,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; $this->weightUnit = $rawPrediction["weight_unit"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php index 25b1d410..73d953af 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\BillOfLading; use ArrayObject; +use Stringable; /** * The goods being shipped. * @extends ArrayObject */ -class BillOfLadingV1CarrierItems extends ArrayObject +class BillOfLadingV1CarrierItems extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php index e3e1c70b..be1fa8ba 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The party to whom the goods are being shipped. */ -class BillOfLadingV1Consignee +class BillOfLadingV1Consignee implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,16 +33,12 @@ class BillOfLadingV1Consignee * @var string|null The phone number of the consignee. */ public ?string $phone; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -49,7 +46,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php index d1ae412d..d27b5bf4 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The party to be notified of the arrival of the goods. */ -class BillOfLadingV1NotifyParty +class BillOfLadingV1NotifyParty implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,16 +33,12 @@ class BillOfLadingV1NotifyParty * @var string|null The phone number of the notify party. */ public ?string $phone; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -49,7 +46,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php index 9b0f7b0b..a893209b 100644 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php +++ b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The party responsible for shipping the goods. */ -class BillOfLadingV1Shipper +class BillOfLadingV1Shipper implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,16 +33,12 @@ class BillOfLadingV1Shipper * @var string|null The phone number of the shipper. */ public ?string $phone; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -49,7 +46,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->email = $rawPrediction["email"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->phone = $rawPrediction["phone"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php index 08822185..665934ec 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItem.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * List of line item present on the document. */ -class FinancialDocumentV1LineItem +class FinancialDocumentV1LineItem implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -48,16 +49,12 @@ class FinancialDocumentV1LineItem * @var float|null The item unit price. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -74,7 +71,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php index ef29c697..cffcc2a2 100644 --- a/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php +++ b/src/V1/Product/FinancialDocument/FinancialDocumentV1LineItems.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\FinancialDocument; use ArrayObject; +use Stringable; /** * List of line item present on the document. * @extends ArrayObject */ -class FinancialDocumentV1LineItems extends ArrayObject +class FinancialDocumentV1LineItems extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php index 3b54ac2a..045676a7 100644 --- a/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php +++ b/src/V1/Product/Fr/BankAccountDetails/BankAccountDetailsV2Bban.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Full extraction of BBAN, including: branch code, bank code, account and key. */ -class BankAccountDetailsV2Bban +class BankAccountDetailsV2Bban implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,16 +33,12 @@ class BankAccountDetailsV2Bban * @var string|null The BBAN Account number outputted as a string. */ public ?string $bbanNumber; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -49,7 +46,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->bbanBranchCode = $rawPrediction["bban_branch_code"] ?? null; $this->bbanKey = $rawPrediction["bban_key"] ?? null; $this->bbanNumber = $rawPrediction["bban_number"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php index ea53b24b..7d4edd8b 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The entity that consumes the energy. */ -class EnergyBillV1EnergyConsumer +class EnergyBillV1EnergyConsumer implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,22 +25,17 @@ class EnergyBillV1EnergyConsumer * @var string|null The name of the energy consumer. */ public ?string $name; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php index cd0c1df5..fbd394a3 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The company that supplies the energy. */ -class EnergyBillV1EnergySupplier +class EnergyBillV1EnergySupplier implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,22 +25,17 @@ class EnergyBillV1EnergySupplier * @var string|null The name of the energy supplier. */ public ?string $name; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->address = $rawPrediction["address"] ?? null; $this->name = $rawPrediction["name"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php index d0d6a1c1..8587380c 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Details of energy consumption. */ -class EnergyBillV1EnergyUsage +class EnergyBillV1EnergyUsage implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -48,16 +49,12 @@ class EnergyBillV1EnergyUsage * @var float|null The price per unit of energy consumed. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -66,7 +63,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; - $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php index 889ffbd1..9dc7dbfe 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Fr\EnergyBill; use ArrayObject; +use Stringable; /** * Details of energy consumption. * @extends ArrayObject */ -class EnergyBillV1EnergyUsages extends ArrayObject +class EnergyBillV1EnergyUsages extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php index 2946189f..00dd1112 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the energy meter. */ -class EnergyBillV1MeterDetail +class EnergyBillV1MeterDetail implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,23 +29,18 @@ class EnergyBillV1MeterDetail * @var string|null The unit of power for energy consumption. */ public ?string $unit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->meterNumber = $rawPrediction["meter_number"] ?? null; $this->meterType = $rawPrediction["meter_type"] ?? null; $this->unit = $rawPrediction["unit"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php index 9ce540ba..aa106d59 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The subscription details fee for the energy service. */ -class EnergyBillV1Subscription +class EnergyBillV1Subscription implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -40,16 +41,12 @@ class EnergyBillV1Subscription * @var float|null The price per unit of subscription. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -62,7 +59,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total"]) : null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php index f9500b5e..040ca44e 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Fr\EnergyBill; use ArrayObject; +use Stringable; /** * The subscription details fee for the energy service. * @extends ArrayObject */ -class EnergyBillV1Subscriptions extends ArrayObject +class EnergyBillV1Subscriptions extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php index 9a3c0daf..b7119cbe 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Details of Taxes and Contributions. */ -class EnergyBillV1TaxesAndContribution +class EnergyBillV1TaxesAndContribution implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -40,23 +41,18 @@ class EnergyBillV1TaxesAndContribution * @var float|null The price per unit of Taxes and Contributions. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->description = $rawPrediction["description"] ?? null; $this->endDate = $rawPrediction["end_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; - $this->pageId = $pageId; $this->taxRate = isset($rawPrediction["tax_rate"]) ? (float) ($rawPrediction["tax_rate"]) : null; $this->total = isset($rawPrediction["total"]) diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php index 207029ed..4604115a 100644 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Fr\EnergyBill; use ArrayObject; +use Stringable; /** * Details of Taxes and Contributions. * @extends ArrayObject */ -class EnergyBillV1TaxesAndContributions extends ArrayObject +class EnergyBillV1TaxesAndContributions extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php index 60abe46b..ead83953 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the employee's bank account. */ -class PayslipV3BankAccountDetail +class PayslipV3BankAccountDetail implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,23 +29,18 @@ class PayslipV3BankAccountDetail * @var string|null The SWIFT code of the bank. */ public ?string $swift; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->bankName = $rawPrediction["bank_name"] ?? null; $this->iban = $rawPrediction["iban"] ?? null; $this->swift = $rawPrediction["swift"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php index cf1a2059..2cc9ae3b 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the employee. */ -class PayslipV3Employee +class PayslipV3Employee implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -44,16 +45,12 @@ class PayslipV3Employee * @var string|null The social security number of the employee. */ public ?string $socialSecurityNumber; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -61,7 +58,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->dateOfBirth = $rawPrediction["date_of_birth"] ?? null; $this->firstName = $rawPrediction["first_name"] ?? null; $this->lastName = $rawPrediction["last_name"] ?? null; - $this->pageId = $pageId; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->registrationNumber = $rawPrediction["registration_number"] ?? null; $this->socialSecurityNumber = $rawPrediction["social_security_number"] ?? null; diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php index 81fbed17..9b34639e 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the employer. */ -class PayslipV3Employer +class PayslipV3Employer implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -44,16 +45,12 @@ class PayslipV3Employer * @var string|null The URSSAF number of the employer. */ public ?string $urssafNumber; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -64,7 +61,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->name = $rawPrediction["name"] ?? null; $this->phoneNumber = $rawPrediction["phone_number"] ?? null; $this->urssafNumber = $rawPrediction["urssaf_number"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php index 7dd5ce1d..27390d5f 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the employment. */ -class PayslipV3Employment +class PayslipV3Employment implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -44,16 +45,12 @@ class PayslipV3Employment * @var string|null The start date of the employment. */ public ?string $startDate; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -64,7 +61,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->positionLevel = $rawPrediction["position_level"] ?? null; $this->seniorityDate = $rawPrediction["seniority_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php index 364a9043..fa691052 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about paid time off. */ -class PayslipV3PaidTimeOff +class PayslipV3PaidTimeOff implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -36,16 +37,12 @@ class PayslipV3PaidTimeOff * @var float|null The amount of paid time off used in the period. */ public ?float $used; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -57,7 +54,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["remaining"]) : null; $this->used = isset($rawPrediction["used"]) ? (float) ($rawPrediction["used"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php index a7bbbe48..8fc8dc9c 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Fr\Payslip; use ArrayObject; +use Stringable; /** * Information about paid time off. * @extends ArrayObject */ -class PayslipV3PaidTimeOffs extends ArrayObject +class PayslipV3PaidTimeOffs extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php index 293191a1..795781da 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Detailed information about the pay. */ -class PayslipV3PayDetail +class PayslipV3PayDetail implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -56,16 +57,12 @@ class PayslipV3PayDetail * @var float|null The total taxes and deductions of the employee. */ public ?float $totalTaxesAndDeductions; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -89,7 +86,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["total_cost_employer"]) : null; $this->totalTaxesAndDeductions = isset($rawPrediction["total_taxes_and_deductions"]) ? (float) ($rawPrediction["total_taxes_and_deductions"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php index 5b498b84..a3550b72 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Information about the pay period. */ -class PayslipV3PayPeriod +class PayslipV3PayPeriod implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -36,16 +37,12 @@ class PayslipV3PayPeriod * @var string|null The year of the pay period. */ public ?string $year; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -54,7 +51,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->paymentDate = $rawPrediction["payment_date"] ?? null; $this->startDate = $rawPrediction["start_date"] ?? null; $this->year = $rawPrediction["year"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php index 06d1bc95..8705c39d 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Detailed information about the earnings. */ -class PayslipV3SalaryDetail +class PayslipV3SalaryDetail implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -36,16 +37,12 @@ class PayslipV3SalaryDetail * @var float|null The rate of the earning. */ public ?float $rate; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -58,7 +55,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["number"]) : null; $this->rate = isset($rawPrediction["rate"]) ? (float) ($rawPrediction["rate"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php index e36b6814..833a56da 100644 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Fr\Payslip; use ArrayObject; +use Stringable; /** * Detailed information about the earnings. * @extends ArrayObject */ -class PayslipV3SalaryDetails extends ArrayObject +class PayslipV3SalaryDetails extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Invoice/InvoiceV4LineItem.php b/src/V1/Product/Invoice/InvoiceV4LineItem.php index b2e0be1a..29cae4ca 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItem.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItem.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * List of all the line items present on the invoice. */ -class InvoiceV4LineItem +class InvoiceV4LineItem implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -48,16 +49,12 @@ class InvoiceV4LineItem * @var float|null The item unit price. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -74,7 +71,6 @@ public function __construct(array $rawPrediction, ?int $pageId) $this->unitMeasure = $rawPrediction["unit_measure"] ?? null; $this->unitPrice = isset($rawPrediction["unit_price"]) ? (float) ($rawPrediction["unit_price"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/Invoice/InvoiceV4LineItems.php b/src/V1/Product/Invoice/InvoiceV4LineItems.php index 2fbbde2c..fdc203c7 100644 --- a/src/V1/Product/Invoice/InvoiceV4LineItems.php +++ b/src/V1/Product/Invoice/InvoiceV4LineItems.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Invoice; use ArrayObject; +use Stringable; /** * List of all the line items present on the invoice. * @extends ArrayObject */ -class InvoiceV4LineItems extends ArrayObject +class InvoiceV4LineItems extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php index 4ff4da1f..acbcd207 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroup.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * List of page groups. Each group represents a single invoice within a multi-invoice document. */ -class InvoiceSplitterV1InvoicePageGroup +class InvoiceSplitterV1InvoicePageGroup implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -20,21 +21,16 @@ class InvoiceSplitterV1InvoicePageGroup * @var int[] List of page indexes that belong to the same invoice (group). */ public array $pageIndexes; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->pageIndexes = $rawPrediction["page_indexes"] ?? []; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php index 2b94383e..55cf7711 100644 --- a/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php +++ b/src/V1/Product/InvoiceSplitter/InvoiceSplitterV1InvoicePageGroups.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\InvoiceSplitter; use ArrayObject; +use Stringable; /** * List of page groups. Each group represents a single invoice within a multi-invoice document. * @extends ArrayObject */ -class InvoiceSplitterV1InvoicePageGroups extends ArrayObject +class InvoiceSplitterV1InvoicePageGroups extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php index be259d4a..45523691 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of added sugars in the product. */ -class NutritionFactsLabelV1AddedSugar +class NutritionFactsLabelV1AddedSugar implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,16 +29,12 @@ class NutritionFactsLabelV1AddedSugar * @var float|null The amount of added sugars per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -47,7 +44,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php index 38c0f12a..546a123f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of calories in the product. */ -class NutritionFactsLabelV1Calorie +class NutritionFactsLabelV1Calorie implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,16 +29,12 @@ class NutritionFactsLabelV1Calorie * @var float|null The amount of calories per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); @@ -47,7 +44,6 @@ public function __construct(array $rawPrediction, ?int $pageId) ? (float) ($rawPrediction["per_100g"]) : null; $this->perServing = isset($rawPrediction["per_serving"]) ? (float) ($rawPrediction["per_serving"]) : null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php index 001b1eaa..6fba6887 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of cholesterol in the product. */ -class NutritionFactsLabelV1Cholesterol +class NutritionFactsLabelV1Cholesterol implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1Cholesterol * @var float|null The amount of cholesterol per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php index a43d850c..b86ca06f 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of dietary fiber in the product. */ -class NutritionFactsLabelV1DietaryFiber +class NutritionFactsLabelV1DietaryFiber implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1DietaryFiber * @var float|null The amount of dietary fiber per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php index 12ce0a9b..8d85aa46 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of nutrients in the product. */ -class NutritionFactsLabelV1Nutrient +class NutritionFactsLabelV1Nutrient implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -36,20 +37,15 @@ class NutritionFactsLabelV1Nutrient * @var string|null The unit of measurement for the amount of nutrients. */ public ?string $unit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->name = $rawPrediction["name"] ?? null; diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php index 52560227..82ed28cd 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\NutritionFactsLabel; use ArrayObject; +use Stringable; /** * The amount of nutrients in the product. * @extends ArrayObject */ -class NutritionFactsLabelV1Nutrients extends ArrayObject +class NutritionFactsLabelV1Nutrients extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php index ee911866..88e7122e 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of protein in the product. */ -class NutritionFactsLabelV1Protein +class NutritionFactsLabelV1Protein implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1Protein * @var float|null The amount of protein per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php index f35b9369..7233bb43 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of saturated fat in the product. */ -class NutritionFactsLabelV1SaturatedFat +class NutritionFactsLabelV1SaturatedFat implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1SaturatedFat * @var float|null The amount of saturated fat per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php index 430b015a..84bc8ece 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The size of a single serving of the product. */ -class NutritionFactsLabelV1ServingSize +class NutritionFactsLabelV1ServingSize implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,23 +25,18 @@ class NutritionFactsLabelV1ServingSize * @var string|null The unit for the amount of a single serving. */ public ?string $unit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); $this->amount = isset($rawPrediction["amount"]) ? (float) ($rawPrediction["amount"]) : null; $this->unit = $rawPrediction["unit"] ?? null; - $this->pageId = $pageId; } /** diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php index 95835782..7fffe0ef 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of sodium in the product. */ -class NutritionFactsLabelV1Sodium +class NutritionFactsLabelV1Sodium implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,20 +33,15 @@ class NutritionFactsLabelV1Sodium * @var string|null The unit of measurement for the amount of sodium. */ public ?string $unit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php index c08cdbeb..281b2967 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The total amount of carbohydrates in the product. */ -class NutritionFactsLabelV1TotalCarbohydrate +class NutritionFactsLabelV1TotalCarbohydrate implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1TotalCarbohydrate * @var float|null The amount of total carbohydrates per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php index 15e37df0..5407464e 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The total amount of fat in the product. */ -class NutritionFactsLabelV1TotalFat +class NutritionFactsLabelV1TotalFat implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1TotalFat * @var float|null The amount of total fat per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php index e0d18e01..0ee3b05a 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The total amount of sugars in the product. */ -class NutritionFactsLabelV1TotalSugar +class NutritionFactsLabelV1TotalSugar implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1TotalSugar * @var float|null The amount of total sugars per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php index dbdfbcd0..981dc5d8 100644 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The amount of trans fat in the product. */ -class NutritionFactsLabelV1TransFat +class NutritionFactsLabelV1TransFat implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -28,20 +29,15 @@ class NutritionFactsLabelV1TransFat * @var float|null The amount of trans fat per serving of the product. */ public ?float $perServing; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->dailyValue = isset($rawPrediction["daily_value"]) ? (float) ($rawPrediction["daily_value"]) : null; $this->per100G = isset($rawPrediction["per_100g"]) diff --git a/src/V1/Product/Receipt/ReceiptV5LineItem.php b/src/V1/Product/Receipt/ReceiptV5LineItem.php index fbd7e649..0f50da48 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItem.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItem.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * List of all line items on the receipt. */ -class ReceiptV5LineItem +class ReceiptV5LineItem implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,20 +33,15 @@ class ReceiptV5LineItem * @var float|null The item unit price. */ public ?float $unitPrice; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->description = $rawPrediction["description"] ?? null; $this->quantity = isset($rawPrediction["quantity"]) ? (float) ($rawPrediction["quantity"]) : null; diff --git a/src/V1/Product/Receipt/ReceiptV5LineItems.php b/src/V1/Product/Receipt/ReceiptV5LineItems.php index cfc4ceb9..40171070 100644 --- a/src/V1/Product/Receipt/ReceiptV5LineItems.php +++ b/src/V1/Product/Receipt/ReceiptV5LineItems.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Receipt; use ArrayObject; +use Stringable; /** * List of all line items on the receipt. * @extends ArrayObject */ -class ReceiptV5LineItems extends ArrayObject +class ReceiptV5LineItems extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Resume/ResumeV1Certificate.php b/src/V1/Product/Resume/ResumeV1Certificate.php index 455398e5..deeeea2c 100644 --- a/src/V1/Product/Resume/ResumeV1Certificate.php +++ b/src/V1/Product/Resume/ResumeV1Certificate.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The list of certificates obtained by the candidate. */ -class ResumeV1Certificate +class ResumeV1Certificate implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -32,20 +33,15 @@ class ResumeV1Certificate * @var string|null The year when a certificate was issued or received. */ public ?string $year; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->grade = $rawPrediction["grade"] ?? null; $this->name = $rawPrediction["name"] ?? null; $this->provider = $rawPrediction["provider"] ?? null; diff --git a/src/V1/Product/Resume/ResumeV1Certificates.php b/src/V1/Product/Resume/ResumeV1Certificates.php index ca799c88..c109db53 100644 --- a/src/V1/Product/Resume/ResumeV1Certificates.php +++ b/src/V1/Product/Resume/ResumeV1Certificates.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Resume; use ArrayObject; +use Stringable; /** * The list of certificates obtained by the candidate. * @extends ArrayObject */ -class ResumeV1Certificates extends ArrayObject +class ResumeV1Certificates extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Resume/ResumeV1Education.php b/src/V1/Product/Resume/ResumeV1Education.php index 3b87ff07..39e3ecc6 100644 --- a/src/V1/Product/Resume/ResumeV1Education.php +++ b/src/V1/Product/Resume/ResumeV1Education.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The list of the candidate's educational background. */ -class ResumeV1Education +class ResumeV1Education implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -44,20 +45,15 @@ class ResumeV1Education * @var string|null The year when the education program or course began. */ public ?string $startYear; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->degreeDomain = $rawPrediction["degree_domain"] ?? null; $this->degreeType = $rawPrediction["degree_type"] ?? null; $this->endMonth = $rawPrediction["end_month"] ?? null; diff --git a/src/V1/Product/Resume/ResumeV1Educations.php b/src/V1/Product/Resume/ResumeV1Educations.php index b4306901..a2635633 100644 --- a/src/V1/Product/Resume/ResumeV1Educations.php +++ b/src/V1/Product/Resume/ResumeV1Educations.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Resume; use ArrayObject; +use Stringable; /** * The list of the candidate's educational background. * @extends ArrayObject */ -class ResumeV1Educations extends ArrayObject +class ResumeV1Educations extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Resume/ResumeV1Language.php b/src/V1/Product/Resume/ResumeV1Language.php index 955085cc..a05a6b72 100644 --- a/src/V1/Product/Resume/ResumeV1Language.php +++ b/src/V1/Product/Resume/ResumeV1Language.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The list of languages that the candidate is proficient in. */ -class ResumeV1Language +class ResumeV1Language implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,20 +25,15 @@ class ResumeV1Language * @var string|null The candidate's level for the language. */ public ?string $level; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->language = $rawPrediction["language"] ?? null; $this->level = $rawPrediction["level"] ?? null; } diff --git a/src/V1/Product/Resume/ResumeV1Languages.php b/src/V1/Product/Resume/ResumeV1Languages.php index f8edf407..a1a4e2a7 100644 --- a/src/V1/Product/Resume/ResumeV1Languages.php +++ b/src/V1/Product/Resume/ResumeV1Languages.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Resume; use ArrayObject; +use Stringable; /** * The list of languages that the candidate is proficient in. * @extends ArrayObject */ -class ResumeV1Languages extends ArrayObject +class ResumeV1Languages extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php index b4941df7..d9d2d1ee 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperience.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The list of the candidate's professional experiences. */ -class ResumeV1ProfessionalExperience +class ResumeV1ProfessionalExperience implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -52,20 +53,15 @@ class ResumeV1ProfessionalExperience * @var string|null The year when the professional experience began. */ public ?string $startYear; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->contractType = $rawPrediction["contract_type"] ?? null; $this->department = $rawPrediction["department"] ?? null; $this->description = $rawPrediction["description"] ?? null; diff --git a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php index 29c3e1af..8c470bd0 100644 --- a/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php +++ b/src/V1/Product/Resume/ResumeV1ProfessionalExperiences.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Resume; use ArrayObject; +use Stringable; /** * The list of the candidate's professional experiences. * @extends ArrayObject */ -class ResumeV1ProfessionalExperiences extends ArrayObject +class ResumeV1ProfessionalExperiences extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php index 1972668c..3fe6add7 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrl.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The list of social network profiles of the candidate. */ -class ResumeV1SocialNetworksUrl +class ResumeV1SocialNetworksUrl implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,20 +25,15 @@ class ResumeV1SocialNetworksUrl * @var string|null The URL of the social network. */ public ?string $url; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->name = $rawPrediction["name"] ?? null; $this->url = $rawPrediction["url"] ?? null; } diff --git a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php index c1d4cc70..be9ff061 100644 --- a/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php +++ b/src/V1/Product/Resume/ResumeV1SocialNetworksUrls.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Resume; use ArrayObject; +use Stringable; /** * The list of social network profiles of the candidate. * @extends ArrayObject */ -class ResumeV1SocialNetworksUrls extends ArrayObject +class ResumeV1SocialNetworksUrls extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php index f1c9d35b..77b066d2 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * Copayments for covered services. */ -class HealthcareCardV1Copay +class HealthcareCardV1Copay implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -24,20 +25,15 @@ class HealthcareCardV1Copay * @var string|null The name of the service. */ public ?string $serviceName; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->serviceFees = isset($rawPrediction["service_fees"]) ? (float) ($rawPrediction["service_fees"]) : null; $this->serviceName = $rawPrediction["service_name"] ?? null; diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php index ea4d939f..0349c0c6 100644 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Us\HealthcareCard; use ArrayObject; +use Stringable; /** * Copayments for covered services. * @extends ArrayObject */ -class HealthcareCardV1Copays extends ArrayObject +class HealthcareCardV1Copays extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php index e938d7f6..872ae58c 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The addresses of the recipients. */ -class UsMailV3RecipientAddress +class UsMailV3RecipientAddress implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -48,20 +49,15 @@ class UsMailV3RecipientAddress * @var string|null The unit number of the recipient's address. */ public ?string $unit; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->isAddressChange = $rawPrediction["is_address_change"] ?? null; diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php index 03b6a97d..652430f4 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php @@ -5,12 +5,13 @@ namespace Mindee\V1\Product\Us\UsMail; use ArrayObject; +use Stringable; /** * The addresses of the recipients. * @extends ArrayObject */ -class UsMailV3RecipientAddresses extends ArrayObject +class UsMailV3RecipientAddresses extends ArrayObject implements Stringable { /** * @param array> $rawPrediction Raw prediction array. diff --git a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php index ecbde5a3..3414229a 100644 --- a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php +++ b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php @@ -7,11 +7,12 @@ use Mindee\V1\Parsing\Standard\FieldConfidenceMixin; use Mindee\V1\Parsing\Standard\FieldPositionMixin; use Mindee\V1\Parsing\SummaryHelperV1; +use Stringable; /** * The address of the sender. */ -class UsMailV3SenderAddress +class UsMailV3SenderAddress implements Stringable { use FieldConfidenceMixin; use FieldPositionMixin; @@ -36,20 +37,15 @@ class UsMailV3SenderAddress * @var string|null The street of the sender's address. */ public ?string $street; - /** - * @var integer|null Page ID. - */ - public ?int $pageId; /** * @param array> $rawPrediction Array containing the JSON document response. * @param integer|null $pageId Page number for multi pages document. */ - public function __construct(array $rawPrediction, ?int $pageId) + public function __construct(array $rawPrediction, public ?int $pageId) { $this->setConfidence($rawPrediction); $this->setPosition($rawPrediction); - $this->pageId = $pageId; $this->city = $rawPrediction["city"] ?? null; $this->complete = $rawPrediction["complete"] ?? null; $this->postalCode = $rawPrediction["postal_code"] ?? null; diff --git a/src/V2/Client.php b/src/V2/Client.php index 4ad08ef1..649bb553 100644 --- a/src/V2/Client.php +++ b/src/V2/Client.php @@ -9,7 +9,7 @@ use Mindee\Error\MindeeException; use Mindee\Input\InputSource; use Mindee\V2\ClientOptions\BaseParameters; -use Mindee\V2\HTTP\MindeeAPIV2; +use Mindee\V2\Http\MindeeApiV2; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\JobResponse; use Mindee\V2\Product\Extraction\Params\ExtractionParameters; @@ -22,9 +22,9 @@ class Client use CustomSleepMixin; /** - * @var MindeeAPIV2 Mindee API V2. + * @var MindeeApiV2 Mindee API V2. */ - protected MindeeAPIV2 $mindeeApi; + protected MindeeApiV2 $mindeeApi; /** * Mindee Client V2. @@ -33,7 +33,7 @@ class Client */ public function __construct(?string $apiKey = null) { - $this->mindeeApi = new MindeeAPIV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); + $this->mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); } /** diff --git a/src/V2/ClientOptions/BaseParameters.php b/src/V2/ClientOptions/BaseParameters.php index 796a19d1..f146d025 100644 --- a/src/V2/ClientOptions/BaseParameters.php +++ b/src/V2/ClientOptions/BaseParameters.php @@ -4,8 +4,6 @@ namespace Mindee\V2\ClientOptions; -use function count; - /** * Base parameters for running an inference. */ @@ -16,15 +14,10 @@ abstract class BaseParameters */ public ?string $alias; - /** - * @var string Model ID. - */ - public string $modelId; - /** * @var array Optional webhook IDs. */ - public array $webhooksIds; + public array $webhookIds; /** * @var string Slug of the endpoint. @@ -34,19 +27,17 @@ abstract class BaseParameters /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. + * @param array|null $webhookIds List of webhook IDs. */ - public function __construct(string $modelId, ?string $alias, ?array $webhooksIds) + public function __construct(public string $modelId, ?string $alias, ?array $webhookIds) { - $this->modelId = $modelId; - if (isset($alias)) { $this->alias = $alias; } - if (isset($webhooksIds)) { - $this->webhooksIds = $webhooksIds; + if (isset($webhookIds)) { + $this->webhookIds = $webhookIds; } else { - $this->webhooksIds = []; + $this->webhookIds = []; } } @@ -61,8 +52,8 @@ public function asHash(): array } - if (!empty($this->webhooksIds)) { - $outHash['webhook_ids'] = implode(',', $this->webhooksIds); + if (!empty($this->webhookIds)) { + $outHash['webhook_ids'] = implode(',', $this->webhookIds); } return $outHash; } diff --git a/src/V2/FileOperations/Crop.php b/src/V2/FileOperations/Crop.php index 1be4e189..1240d982 100644 --- a/src/V2/FileOperations/Crop.php +++ b/src/V2/FileOperations/Crop.php @@ -16,18 +16,10 @@ */ class Crop { - /** - * @var LocalInputSource localInputSource object - */ - private readonly LocalInputSource $localInput; - /** * @param LocalInputSource $localInput LocalInputSource object. */ - public function __construct(LocalInputSource $localInput) - { - $this->localInput = $localInput; - } + public function __construct(private readonly LocalInputSource $localInput) {} /** * Extracts a crop zone from a file. diff --git a/src/V2/FileOperations/Split.php b/src/V2/FileOperations/Split.php index 93015574..a8a55689 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -5,8 +5,8 @@ namespace Mindee\V2\FileOperations; use Mindee\Error\MindeeInputException; -use Mindee\Extraction\ExtractedPDF; -use Mindee\Extraction\PDFExtractor; +use Mindee\Extraction\ExtractedPdf; +use Mindee\Extraction\PdfExtractor; use Mindee\Input\LocalInputSource; /** @@ -15,17 +15,9 @@ class Split { /** - * @var LocalInputSource localInputSource object + * @param LocalInputSource $localInput LocalInputSource object. */ - private readonly LocalInputSource $localInput; - - /** - * @param LocalInputSource $inputSource LocalInputSource object. - */ - public function __construct(LocalInputSource $inputSource) - { - $this->localInput = $inputSource; - } + public function __construct(private readonly LocalInputSource $localInput) {} /** * Expands a range to a list of integers. @@ -51,9 +43,9 @@ public static function expandRange(int $start, int $end): array * * @param int[] $split Split range to extract. * - * @return ExtractedPDF 2D array of extracted pages + * @return ExtractedPdf 2D array of extracted pages */ - public function extractSingleSplit(array $split): ExtractedPDF + public function extractSingleSplit(array $split): ExtractedPdf { return $this->extractSplits([$split])[0]; } @@ -67,7 +59,7 @@ public function extractSingleSplit(array $split): ExtractedPDF */ public function extractSplits(array $splits): SplitFiles { - $pdfExtractor = new PDFExtractor($this->localInput); + $pdfExtractor = new PdfExtractor($this->localInput); $expandedPageIndexes = array_map(static fn(array $split) => self::expandRange($split[0], $split[1]), $splits); return new SplitFiles(...$pdfExtractor->extractSubDocuments($expandedPageIndexes)); diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index 9b9fd0cf..20a8146c 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -5,7 +5,7 @@ namespace Mindee\V2\FileOperations; use Mindee\Error\MindeeException; -use Mindee\Extraction\ExtractedPDF; +use Mindee\Extraction\ExtractedPdf; use ArrayObject; use Exception; @@ -16,16 +16,16 @@ /** * Split files collection wrapper. * - * @extends ArrayObject + * @extends ArrayObject */ class SplitFiles extends ArrayObject { /** * Builds a new SplitFiles collection. * - * @param ExtractedPDF ...$items Items. + * @param ExtractedPdf ...$items Items. */ - public function __construct(ExtractedPDF ...$items) + public function __construct(ExtractedPdf ...$items) { parent::__construct($items); } diff --git a/src/V2/HTTP/MindeeAPIV2.php b/src/V2/Http/MindeeApiV2.php similarity index 97% rename from src/V2/HTTP/MindeeAPIV2.php rename to src/V2/Http/MindeeApiV2.php index 28eadd49..34e86328 100644 --- a/src/V2/HTTP/MindeeAPIV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -6,7 +6,7 @@ * Settings and variables linked to endpoint calling & API usage. */ -namespace Mindee\V2\HTTP; +namespace Mindee\V2\Http; use CurlHandle; use Exception; @@ -17,7 +17,7 @@ use Mindee\Error\MindeeV2HttpUnknownException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V2\ClientOptions\BaseParameters; use Mindee\V2\Parsing\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; @@ -29,7 +29,7 @@ use function call_user_func; use function dirname; -use const Mindee\V1\HTTP\API_KEY_ENV_NAME; +use const Mindee\V1\Http\API_KEY_ENV_NAME; use const Mindee\VERSION; // phpcs:disable @@ -64,7 +64,7 @@ /** * Data class containing settings for endpoints. */ -class MindeeAPIV2 +class MindeeApiV2 { /** * Get the User Agent to send for API calls. @@ -81,7 +81,7 @@ private function getUserAgent(): string /** * @var string|null API key. */ - public ?string $apiKey; + public ?string $apiKey = null; /** * @var integer Timeout for the request, in ms. */ @@ -98,7 +98,7 @@ private function getUserAgent(): string */ public function __construct(?string $apiKey) { - $this->setApiKey($apiKey); + $this->setAPIKey($apiKey); $this->baseUrl = API_V2_BASE_URL_DEFAULT; $this->requestTimeout = API_V2_TIMEOUT_DEFAULT; $this->setFromEnv(); @@ -129,7 +129,7 @@ protected function setBaseUrl(string $value): void private function setFromEnv(): void { $envVars = [ - API_V2_BASE_URL_ENV_NAME => [$this, 'setBaseUrl'], + API_V2_BASE_URL_ENV_NAME => $this->setBaseUrl(...), API_V2_REQUEST_TIMEOUT_ENV_NAME => [$this, 'setTimeout'], ]; foreach ($envVars as $key => $func) { @@ -147,7 +147,7 @@ private function setFromEnv(): void * * @param string|null $apiKey Optional API key. */ - protected function setApiKey(?string $apiKey = null): void + protected function setAPIKey(?string $apiKey = null): void { $envVal = !getenv(API_V2_KEY_ENV_NAME) ? '' : getenv(API_V2_KEY_ENV_NAME); if (!$apiKey) { @@ -346,7 +346,7 @@ private function documentEnqueuePost( $ch = $this->initChannel(); $postFields = $params->asHash(); - if ($inputSource instanceof URLInputSource) { + if ($inputSource instanceof UrlInputSource) { $postFields['url'] = $inputSource->url; } elseif ($inputSource instanceof LocalInputSource) { $inputSource->checkNeedsFix(); diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/BaseInference.php index 81b2a855..5d39473a 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/BaseInference.php @@ -8,11 +8,12 @@ use Mindee\V2\Parsing\Inference\InferenceFile; use Mindee\V2\Parsing\Inference\InferenceJob; use Mindee\V2\Parsing\Inference\InferenceModel; +use Stringable; /** * Base for all inference-based V2 products. */ -abstract class BaseInference +abstract class BaseInference implements Stringable { /** * @var string ID of the inference. diff --git a/src/V2/Parsing/Inference/BaseResponse.php b/src/V2/Parsing/Inference/BaseResponse.php index 341d85ed..94c2cdfc 100644 --- a/src/V2/Parsing/Inference/BaseResponse.php +++ b/src/V2/Parsing/Inference/BaseResponse.php @@ -10,17 +10,9 @@ abstract class BaseResponse { /** - * @var array> Raw HTTP response from the server. + * @param array> $rawHttp Raw server response array. */ - private array $rawHttp; - - /** - * @param array> $rawResponse Raw server response array. - */ - protected function __construct(array $rawResponse) - { - $this->rawHttp = $rawResponse; - } + protected function __construct(private readonly array $rawHttp) {} /** * @return string Raw dump of the JSON response. diff --git a/src/V2/Parsing/Inference/Field/BaseField.php b/src/V2/Parsing/Inference/Field/BaseField.php index 02d64559..f11d30d6 100644 --- a/src/V2/Parsing/Inference/Field/BaseField.php +++ b/src/V2/Parsing/Inference/Field/BaseField.php @@ -5,6 +5,7 @@ namespace Mindee\V2\Parsing\Inference\Field; use Mindee\Error\MindeeApiException; +use Stringable; use function array_key_exists; use function sprintf; @@ -12,12 +13,8 @@ /** * Base class for V2 fields. */ -abstract class BaseField +abstract class BaseField implements Stringable { - /** - * @var integer Level of indentation for rst display. - */ - protected int $indentLevel; /** * @var array List of possible locations for a field. */ @@ -32,9 +29,8 @@ abstract class BaseField * @param array> $rawPrediction Raw prediction array. * @param integer $indentLevel Level of indentation for rst display. */ - public function __construct(array $rawPrediction, int $indentLevel = 0) + public function __construct(array $rawPrediction, protected int $indentLevel = 0) { - $this->indentLevel = $indentLevel; if (array_key_exists("locations", $rawPrediction) && $rawPrediction["locations"]) { $this->locations = []; foreach ($rawPrediction["locations"] as $location) { diff --git a/src/V2/Parsing/Inference/Field/FieldLocation.php b/src/V2/Parsing/Inference/Field/FieldLocation.php index 6699af10..6de9bcb9 100644 --- a/src/V2/Parsing/Inference/Field/FieldLocation.php +++ b/src/V2/Parsing/Inference/Field/FieldLocation.php @@ -5,13 +5,14 @@ namespace Mindee\V2\Parsing\Inference\Field; use Mindee\Geometry\Polygon; +use Stringable; use function is_int; /** * Location of a field. */ -class FieldLocation +class FieldLocation implements Stringable { /** * Free polygon made up of points (can be null when not provided). diff --git a/src/V2/Parsing/Inference/Field/InferenceFields.php b/src/V2/Parsing/Inference/Field/InferenceFields.php index 7a041273..aa2018d9 100644 --- a/src/V2/Parsing/Inference/Field/InferenceFields.php +++ b/src/V2/Parsing/Inference/Field/InferenceFields.php @@ -20,19 +20,12 @@ class InferenceFields extends ArrayObject */ private array $fields = []; - /** - * @var integer Indentation level. - */ - private int $indentLevel; - /** * @param array> $rawResponse Raw server response array. * @param integer $indentLevel Level of indentation. */ - public function __construct(array $rawResponse, int $indentLevel = 0) + public function __construct(array $rawResponse, private readonly int $indentLevel = 0) { - $this->indentLevel = $indentLevel; - foreach ($rawResponse as $key => $value) { $this->fields[$key] = BaseField::createField($value, 1); } diff --git a/src/V2/Parsing/Inference/InferenceActiveOptions.php b/src/V2/Parsing/Inference/InferenceActiveOptions.php index ff0fbd37..7d1e214e 100644 --- a/src/V2/Parsing/Inference/InferenceActiveOptions.php +++ b/src/V2/Parsing/Inference/InferenceActiveOptions.php @@ -6,6 +6,7 @@ use Mindee\Parsing\SummaryHelper; use Mindee\V2\Product\Extraction\Params\DataSchemaActiveOption; +use Stringable; /** * Options which were activated during the inference. @@ -14,7 +15,7 @@ * - By setting their default values on the Platform UI * - By explicitly setting them in the inference request */ -class InferenceActiveOptions +class InferenceActiveOptions implements Stringable { /** * @var boolean Whether the Retrieval-Augmented Generation feature was activated. diff --git a/src/V2/Parsing/Inference/InferenceFile.php b/src/V2/Parsing/Inference/InferenceFile.php index 74251acc..e39bf6b0 100644 --- a/src/V2/Parsing/Inference/InferenceFile.php +++ b/src/V2/Parsing/Inference/InferenceFile.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Parsing\Inference; +use Stringable; + /** * Inference result file class. */ -class InferenceFile +class InferenceFile implements Stringable { /** * @var string Name of the file. diff --git a/src/V2/Parsing/Inference/InferenceJob.php b/src/V2/Parsing/Inference/InferenceJob.php index 5bc7a552..4c288bd2 100644 --- a/src/V2/Parsing/Inference/InferenceJob.php +++ b/src/V2/Parsing/Inference/InferenceJob.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Parsing\Inference; +use Stringable; + /** * Information on the Job associated to a given Inference. */ -class InferenceJob +class InferenceJob implements Stringable { /** * @var string UUID of the job. diff --git a/src/V2/Parsing/Inference/InferenceModel.php b/src/V2/Parsing/Inference/InferenceModel.php index 7dbbdf76..d508b10d 100644 --- a/src/V2/Parsing/Inference/InferenceModel.php +++ b/src/V2/Parsing/Inference/InferenceModel.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Parsing\Inference; +use Stringable; + /** * Inference result model class. */ -class InferenceModel +class InferenceModel implements Stringable { /** * @var string ID of the model. diff --git a/src/V2/Parsing/Inference/RAGMetadata.php b/src/V2/Parsing/Inference/RagMetadata.php similarity index 96% rename from src/V2/Parsing/Inference/RAGMetadata.php rename to src/V2/Parsing/Inference/RagMetadata.php index f63935e3..b1916f3b 100644 --- a/src/V2/Parsing/Inference/RAGMetadata.php +++ b/src/V2/Parsing/Inference/RagMetadata.php @@ -7,7 +7,7 @@ /** * Metadata about the RAG operation. */ -class RAGMetadata +class RagMetadata { /** * @var string|null ID of the matched document, if present. diff --git a/src/V2/Parsing/Inference/RawText.php b/src/V2/Parsing/Inference/RawText.php index 1f6bf181..5b4be8f6 100644 --- a/src/V2/Parsing/Inference/RawText.php +++ b/src/V2/Parsing/Inference/RawText.php @@ -4,12 +4,14 @@ namespace Mindee\V2\Parsing\Inference; +use Stringable; + use function array_key_exists; /** * Raw text as found in the document. */ -class RawText +class RawText implements Stringable { /** * @var RawTextPage[] list of pages found in the document. diff --git a/src/V2/Parsing/Inference/RawTextPage.php b/src/V2/Parsing/Inference/RawTextPage.php index 85d67245..e0008988 100644 --- a/src/V2/Parsing/Inference/RawTextPage.php +++ b/src/V2/Parsing/Inference/RawTextPage.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Parsing\Inference; +use Stringable; + /** * Raw text extracted from the page. */ -class RawTextPage +class RawTextPage implements Stringable { /** * Page content as a single string. diff --git a/src/V2/Parsing/Job.php b/src/V2/Parsing/Job.php index 884ad054..3957e17f 100644 --- a/src/V2/Parsing/Job.php +++ b/src/V2/Parsing/Job.php @@ -116,7 +116,7 @@ private function parseDate(?string $dateString): ?DateTime try { return new DateTime($dateString); - } catch (Exception $e) { + } catch (Exception) { return null; } } diff --git a/src/V2/Parsing/JobWebhook.php b/src/V2/Parsing/JobWebhook.php index c8d856b3..3205c2ce 100644 --- a/src/V2/Parsing/JobWebhook.php +++ b/src/V2/Parsing/JobWebhook.php @@ -60,7 +60,7 @@ private function parseDate(?string $dateString): ?DateTime try { return new DateTime($dateString); - } catch (Exception $e) { + } catch (Exception) { return null; } } diff --git a/src/V2/Product/Classification/ClassificationClassifier.php b/src/V2/Product/Classification/ClassificationClassifier.php index 5bf6ee32..9e53fc91 100644 --- a/src/V2/Product/Classification/ClassificationClassifier.php +++ b/src/V2/Product/Classification/ClassificationClassifier.php @@ -5,11 +5,12 @@ namespace Mindee\V2\Product\Classification; use Mindee\V2\Product\Extraction\ExtractionResponse; +use Stringable; /** * Classification of document type from the source file. */ -class ClassificationClassifier +class ClassificationClassifier implements Stringable { /** * @var string The document type, as identified on given classification values. diff --git a/src/V2/Product/Classification/ClassificationResult.php b/src/V2/Product/Classification/ClassificationResult.php index 5b5e22e3..fda1e00b 100644 --- a/src/V2/Product/Classification/ClassificationResult.php +++ b/src/V2/Product/Classification/ClassificationResult.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Product\Classification; +use Stringable; + /** * Result of the document classifier inference. */ -class ClassificationResult +class ClassificationResult implements Stringable { /** * @var ClassificationClassifier Classification of document type from the source file. diff --git a/src/V2/Product/Classification/Params/ClassificationParameters.php b/src/V2/Product/Classification/Params/ClassificationParameters.php index fade894e..057f9e1c 100644 --- a/src/V2/Product/Classification/Params/ClassificationParameters.php +++ b/src/V2/Product/Classification/Params/ClassificationParameters.php @@ -20,13 +20,13 @@ class ClassificationParameters extends BaseParameters /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Crop/CropItem.php b/src/V2/Product/Crop/CropItem.php index 7b0b8e08..eba0759c 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -6,11 +6,12 @@ use Mindee\V2\Parsing\Inference\Field\FieldLocation; use Mindee\V2\Product\Extraction\ExtractionResponse; +use Stringable; /** * Result of a cropped document region. */ -class CropItem +class CropItem implements Stringable { /** * @var FieldLocation Location which includes cropping coordinates for the detected object, @@ -40,7 +41,7 @@ public function __construct(array $rawResponse) /** * @return string String representation. */ - public function __toString() + public function __toString(): string { return "* :Location: $this->location\n :Object Type: $this->objectType"; } diff --git a/src/V2/Product/Crop/CropResult.php b/src/V2/Product/Crop/CropResult.php index 23428a97..0e8bdc18 100644 --- a/src/V2/Product/Crop/CropResult.php +++ b/src/V2/Product/Crop/CropResult.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Product\Crop; +use Stringable; + /** * Result of a crop utility inference. */ -class CropResult +class CropResult implements Stringable { /** * @var CropItem[] Crops extracted from the image. diff --git a/src/V2/Product/Crop/Params/CropParameters.php b/src/V2/Product/Crop/Params/CropParameters.php index 1daacedb..e7cdf652 100644 --- a/src/V2/Product/Crop/Params/CropParameters.php +++ b/src/V2/Product/Crop/Params/CropParameters.php @@ -20,13 +20,13 @@ class CropParameters extends BaseParameters /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Extraction/ExtractionResult.php b/src/V2/Product/Extraction/ExtractionResult.php index f6102026..2a1ae194 100644 --- a/src/V2/Product/Extraction/ExtractionResult.php +++ b/src/V2/Product/Extraction/ExtractionResult.php @@ -5,13 +5,14 @@ namespace Mindee\V2\Product\Extraction; use Mindee\V2\Parsing\Inference\Field\InferenceFields; -use Mindee\V2\Parsing\Inference\RAGMetadata; +use Mindee\V2\Parsing\Inference\RagMetadata; use Mindee\V2\Parsing\Inference\RawText; +use Stringable; /** * Inference result class. */ -class ExtractionResult +class ExtractionResult implements Stringable { /** * @var InferenceFields Fields contained in the inference. @@ -24,9 +25,9 @@ class ExtractionResult public ?RawText $rawText; /** - * @var RAGMetadata|null RAG metadata. + * @var RagMetadata|null RAG metadata. */ - public ?RAGMetadata $rag; + public ?RagMetadata $rag; /** * @param array> $rawResponse Raw server response array. @@ -39,7 +40,7 @@ public function __construct(array $rawResponse) : null; $this->rag = isset( $rawResponse['rag'] - ) ? new RAGMetadata($rawResponse['rag']) : null; + ) ? new RagMetadata($rawResponse['rag']) : null; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchema.php b/src/V2/Product/Extraction/Params/DataSchema.php index faf492ff..98d1a0b3 100644 --- a/src/V2/Product/Extraction/Params/DataSchema.php +++ b/src/V2/Product/Extraction/Params/DataSchema.php @@ -5,6 +5,7 @@ namespace Mindee\V2\Product\Extraction\Params; use InvalidArgumentException; +use Stringable; use function get_class; use function gettype; @@ -12,7 +13,7 @@ /** * Modify the Data Schema. */ -class DataSchema +class DataSchema implements Stringable { /** * @var DataSchemaReplace|null If set, completely replaces the data schema of the model. @@ -30,7 +31,7 @@ public function __construct(self|array|string $dataSchema) } elseif (gettype($dataSchema) === 'array') { $jsonData = $dataSchema; } else { - if (get_class($dataSchema) === self::class) { + if ($dataSchema::class === self::class) { $this->replace = $dataSchema->replace; return; } @@ -76,7 +77,7 @@ private function toJsonStringProperSpacing(): string { $jsonStr = json_encode($this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $lines = explode("\n", $jsonStr); - return implode("\n", array_map(static fn($line) => self::fixLineSpaces($line), $lines)) . "\n"; + return implode("\n", array_map(self::fixLineSpaces(...), $lines)) . "\n"; } /** diff --git a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php index e5c62f88..871d592a 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php +++ b/src/V2/Product/Extraction/Params/DataSchemaActiveOption.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Product\Extraction\Params; +use Stringable; + /** * Data schema options activated during the inference. */ -class DataSchemaActiveOption +class DataSchemaActiveOption implements Stringable { /** * @var boolean Whether the Data Schema has been replaced. diff --git a/src/V2/Product/Extraction/Params/DataSchemaField.php b/src/V2/Product/Extraction/Params/DataSchemaField.php index b7103429..a281ce68 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaField.php +++ b/src/V2/Product/Extraction/Params/DataSchemaField.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Product\Extraction\Params; +use Stringable; + /** * Data Schema Field. */ -class DataSchemaField +class DataSchemaField implements Stringable { /** * @var string Name of the field in the data schema. @@ -103,7 +105,7 @@ public function toJson(): array public function __toString(): string { - return json_encode( + return (string) json_encode( $this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ); diff --git a/src/V2/Product/Extraction/Params/DataSchemaReplace.php b/src/V2/Product/Extraction/Params/DataSchemaReplace.php index 77cd9c4a..cc5bfd82 100644 --- a/src/V2/Product/Extraction/Params/DataSchemaReplace.php +++ b/src/V2/Product/Extraction/Params/DataSchemaReplace.php @@ -5,6 +5,7 @@ namespace Mindee\V2\Product\Extraction\Params; use InvalidArgumentException; +use Stringable; use function count; use function is_array; @@ -12,7 +13,7 @@ /** * The structure to completely replace the data schema of the model. */ -class DataSchemaReplace +class DataSchemaReplace implements Stringable { /** * @var DataSchemaField[] Fields to replace in the data schema. @@ -48,7 +49,7 @@ public function toJson(): array */ public function __toString(): string { - return json_encode( + return (string) json_encode( $this->toJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ); diff --git a/src/V2/Product/Extraction/Params/ExtractionParameters.php b/src/V2/Product/Extraction/Params/ExtractionParameters.php index dd6a5dc3..5deaf086 100644 --- a/src/V2/Product/Extraction/Params/ExtractionParameters.php +++ b/src/V2/Product/Extraction/Params/ExtractionParameters.php @@ -11,28 +11,6 @@ */ class ExtractionParameters extends BaseParameters { - /** - * @var boolean|null Enhance extraction accuracy with Retrieval-Augmented Generation.. - */ - public ?bool $rag; - - /** - * @var boolean|null Extract the full text content from the document as strings. - */ - public ?bool $rawText; - - /** - * @var boolean|null Calculate bounding box polygons for all fields. - */ - public ?bool $polygon; - - /** - * @var boolean|null Boost the precision and accuracy of all extractions. - * Calculate confidence scores for all fields. - */ - public ?bool $confidence; - - /** * @var string|null Additional text context used by the model during inference. * Not recommended, for specific use only. @@ -58,29 +36,24 @@ class ExtractionParameters extends BaseParameters * 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 array|null $webhookIds List of webhook IDs. * @param string|null $textContext Additional text context used by the model during * inference. * @param DataSchema|string|array|null $dataSchema Additional text context used by the model during * inference. */ public function __construct( - string $modelId, - ?bool $rag = null, - ?bool $rawText = null, - ?bool $polygon = null, - ?bool $confidence = null, - ?string $alias = null, - ?array $webhooksIds = null, - ?string $textContext = null, + string $modelId, + public ?bool $rag = null, + public ?bool $rawText = null, + public ?bool $polygon = null, + public ?bool $confidence = null, + ?string $alias = null, + ?array $webhookIds = null, + ?string $textContext = null, DataSchema|string|array|null $dataSchema = null, ) { - parent::__construct($modelId, $alias, $webhooksIds); - - $this->rag = $rag; - $this->rawText = $rawText; - $this->polygon = $polygon; - $this->confidence = $confidence; + parent::__construct($modelId, $alias, $webhookIds); if (isset($textContext)) { $this->textContext = $textContext; } diff --git a/src/V2/Product/OCR/OCRInference.php b/src/V2/Product/Ocr/OcrInference.php similarity index 66% rename from src/V2/Product/OCR/OCRInference.php rename to src/V2/Product/Ocr/OcrInference.php index d14e841e..cfe2fc9d 100644 --- a/src/V2/Product/OCR/OCRInference.php +++ b/src/V2/Product/Ocr/OcrInference.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR; +namespace Mindee\V2\Product\Ocr; use Mindee\V2\Parsing\BaseInference; /** - * Response for an OCR utility inference. + * Response for an Ocr utility inference. */ -class OCRInference extends BaseInference +class OcrInference extends BaseInference { /** - * @var OCRResult Result of the inference. + * @var OcrResult Result of the inference. */ - public OCRResult $result; + public OcrResult $result; /** * @param array> $rawResponse Raw server response array. @@ -22,7 +22,7 @@ class OCRInference extends BaseInference public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->result = new OCRResult($rawResponse['result']); + $this->result = new OcrResult($rawResponse['result']); } /** diff --git a/src/V2/Product/OCR/OCRPage.php b/src/V2/Product/Ocr/OcrPage.php similarity index 71% rename from src/V2/Product/OCR/OCRPage.php rename to src/V2/Product/Ocr/OcrPage.php index 3d4ba986..29a96e73 100644 --- a/src/V2/Product/OCR/OCRPage.php +++ b/src/V2/Product/Ocr/OcrPage.php @@ -2,15 +2,17 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR; +namespace Mindee\V2\Product\Ocr; + +use Stringable; /** - * OCR result for a single page. + * Ocr result for a single page. */ -class OCRPage +class OcrPage implements Stringable { /** - * @var OCRWord[] OCR result for a single page. + * @var OcrWord[] Ocr result for a single page. */ public array $words; @@ -24,7 +26,7 @@ class OCRPage */ public function __construct(array $rawResponse) { - $this->words = array_map(static fn($word) => new OCRWord($word), $rawResponse['words']); + $this->words = array_map(static fn($word) => new OcrWord($word), $rawResponse['words']); $this->content = $rawResponse['content']; } @@ -39,6 +41,6 @@ public function __toString(): string $ocrWords .= implode("\n\n", $this->words); } - return "OCR Words\n---------$ocrWords\n\n:Content: $this->content"; + return "Ocr Words\n---------$ocrWords\n\n:Content: $this->content"; } } diff --git a/src/V2/Product/OCR/OCRResponse.php b/src/V2/Product/Ocr/OcrResponse.php similarity index 63% rename from src/V2/Product/OCR/OCRResponse.php rename to src/V2/Product/Ocr/OcrResponse.php index 9dd334dd..2ca6c8b0 100644 --- a/src/V2/Product/OCR/OCRResponse.php +++ b/src/V2/Product/Ocr/OcrResponse.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR; +namespace Mindee\V2\Product\Ocr; use Mindee\V2\Parsing\Inference\BaseResponse; /** - * Response for an OCR utility inference. + * Response for an Ocr utility inference. */ -class OCRResponse extends BaseResponse +class OcrResponse extends BaseResponse { /** - * @var OCRInference Result of an OCR inference. + * @var OcrInference Result of an Ocr inference. */ - public OCRInference $inference; + public OcrInference $inference; /** * @var string Slug for the inference. @@ -27,6 +27,6 @@ class OCRResponse extends BaseResponse public function __construct(array $rawResponse) { parent::__construct($rawResponse); - $this->inference = new OCRInference($rawResponse['inference']); + $this->inference = new OcrInference($rawResponse['inference']); } } diff --git a/src/V2/Product/OCR/OCRResult.php b/src/V2/Product/Ocr/OcrResult.php similarity index 73% rename from src/V2/Product/OCR/OCRResult.php rename to src/V2/Product/Ocr/OcrResult.php index 6799ab4c..c0e39c72 100644 --- a/src/V2/Product/OCR/OCRResult.php +++ b/src/V2/Product/Ocr/OcrResult.php @@ -2,17 +2,19 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR; +namespace Mindee\V2\Product\Ocr; + +use Stringable; use function strlen; /** - * Result of the OCR utility inference. + * Result of the Ocr utility inference. */ -class OCRResult +class OcrResult implements Stringable { /** - * @var OCRPage[] List of pages. + * @var OcrPage[] List of pages. */ public array $pages; @@ -21,7 +23,7 @@ class OCRResult */ public function __construct(array $rawResponse) { - $this->pages = array_map(static fn($page) => new OCRPage($page), $rawResponse['pages']); + $this->pages = array_map(static fn($page) => new OcrPage($page), $rawResponse['pages']); } /** @@ -29,7 +31,7 @@ public function __construct(array $rawResponse) */ public function __toString(): string { - $str = "OCR Result\n##########\n"; + $str = "Ocr Result\n##########\n"; $i = 1; foreach ($this->pages as $page) { diff --git a/src/V2/Product/OCR/OCRWord.php b/src/V2/Product/Ocr/OcrWord.php similarity index 84% rename from src/V2/Product/OCR/OCRWord.php rename to src/V2/Product/Ocr/OcrWord.php index 189632ea..37d8c6c8 100644 --- a/src/V2/Product/OCR/OCRWord.php +++ b/src/V2/Product/Ocr/OcrWord.php @@ -2,14 +2,15 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR; +namespace Mindee\V2\Product\Ocr; use Mindee\Geometry\Polygon; +use Stringable; /** - * OCR result for a single word extracted from the document page. + * Ocr result for a single word extracted from the document page. */ -class OCRWord +class OcrWord implements Stringable { /** * @var string Content of the word. diff --git a/src/V2/Product/OCR/Params/OCRParameters.php b/src/V2/Product/Ocr/Params/OcrParameters.php similarity index 66% rename from src/V2/Product/OCR/Params/OCRParameters.php rename to src/V2/Product/Ocr/Params/OcrParameters.php index bb9a95dc..51423730 100644 --- a/src/V2/Product/OCR/Params/OCRParameters.php +++ b/src/V2/Product/Ocr/Params/OcrParameters.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Product\OCR\Params; +namespace Mindee\V2\Product\Ocr\Params; use Mindee\ClientOptions\PollingOptions; use Mindee\V2\ClientOptions\BaseParameters; @@ -10,7 +10,7 @@ /** * Parameters for an ocr utility inference. */ -class OCRParameters extends BaseParameters +class OcrParameters extends BaseParameters { /** * @var string Slug of the endpoint. @@ -20,13 +20,13 @@ class OCRParameters extends BaseParameters /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Split/Params/SplitParameters.php b/src/V2/Product/Split/Params/SplitParameters.php index 8f5e790e..8de1262e 100644 --- a/src/V2/Product/Split/Params/SplitParameters.php +++ b/src/V2/Product/Split/Params/SplitParameters.php @@ -20,13 +20,13 @@ class SplitParameters extends BaseParameters /** * @param string $modelId ID of the model. * @param string|null $alias Optional file alias. - * @param array|null $webhooksIds List of webhook IDs. + * @param array|null $webhookIds List of webhook IDs. */ public function __construct( string $modelId, ?string $alias = null, - ?array $webhooksIds = null + ?array $webhookIds = null ) { - parent::__construct($modelId, $alias, $webhooksIds); + parent::__construct($modelId, $alias, $webhookIds); } } diff --git a/src/V2/Product/Split/SplitRange.php b/src/V2/Product/Split/SplitRange.php index 772b3858..96fca6b0 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -5,11 +5,12 @@ namespace Mindee\V2\Product\Split; use Mindee\V2\Product\Extraction\ExtractionResponse; +use Stringable; /** * A single document as identified when splitting a multi-document source file. */ -class SplitRange +class SplitRange implements Stringable { /** * @var integer[] 0-based page indexes, where the first integer indicates the start page and the second integer diff --git a/src/V2/Product/Split/SplitResult.php b/src/V2/Product/Split/SplitResult.php index 86859187..403d7944 100644 --- a/src/V2/Product/Split/SplitResult.php +++ b/src/V2/Product/Split/SplitResult.php @@ -4,10 +4,12 @@ namespace Mindee\V2\Product\Split; +use Stringable; + /** * Result of a split utility inference. */ -class SplitResult +class SplitResult implements Stringable { /** * @var SplitRange[] A single document as identified when splitting a multi-document source file. diff --git a/tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php similarity index 68% rename from tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php rename to tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php index 775bb962..89873d95 100644 --- a/tests/Dependencies/DependencyCheckerNoExtendedTestPDF.php +++ b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php @@ -6,16 +6,20 @@ use Mindee\Error\MindeeUnhandledException; use Mindee\Extraction\ExtractedImage; -use Mindee\Extraction\ExtractedPDF; +use Mindee\Extraction\ExtractedPdf; use Mindee\V1\Image\ImageExtractor; -use Mindee\Extraction\PDFExtractor; +use Mindee\Extraction\PdfExtractor; use Mindee\Input\PathInput; use PHPUnit\Framework\TestCase; use TestingUtilities; +use Imagick; +use stdClass; require_once(__DIR__ . "/../TestingUtilities.php"); -class DependencyCheckerNoExtendedTestPDF extends TestCase +class DummyImagick {} + +class DependencyCheckerNoExtendedTestPdf extends TestCase { public function testNoImageExtractor(): void { @@ -23,25 +27,29 @@ public function testNoImageExtractor(): void $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); new ImageExtractor($inputObj); } - public function testNoPDFExtractor(): void + public function testNoPdfExtractor(): void { $this->expectException(MindeeUnhandledException::class); $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); - new PDFExtractor($inputObj); + new PdfExtractor($inputObj); } public function testNoExtractedImage(): void { $this->expectException(MindeeUnhandledException::class); - $inputImage = ""; + if (!class_exists('Imagick')) { + class_alias(DummyImagick::class, 'Imagick'); + } + + $inputImage = new Imagick(); $filename = "dummy"; $saveFormat = "pdf"; new ExtractedImage($inputImage, $filename, $saveFormat, 0, 0); } - public function testNoExtractedPDF(): void + public function testNoExtractedPdf(): void { $this->expectException(MindeeUnhandledException::class); $inputImage = ""; $filename = "dummy"; - new ExtractedPDF($inputImage, $filename); + new ExtractedPdf($inputImage, $filename); } } diff --git a/tests/Dependencies/DependencyCheckerPDFTest.php b/tests/Dependencies/DependencyCheckerPdfTest.php similarity index 92% rename from tests/Dependencies/DependencyCheckerPDFTest.php rename to tests/Dependencies/DependencyCheckerPdfTest.php index 22dd7ede..456f624f 100644 --- a/tests/Dependencies/DependencyCheckerPDFTest.php +++ b/tests/Dependencies/DependencyCheckerPdfTest.php @@ -7,7 +7,7 @@ use Mindee\Dependency\DependencyChecker; use PHPUnit\Framework\TestCase; -class DependencyCheckerPDFTest extends TestCase +class DependencyCheckerPdfTest extends TestCase { public function testGhostScriptDependency(): void { diff --git a/tests/Geometry/PolygonUtilsTest.php b/tests/Geometry/PolygonUtilsTest.php index 45868b52..b338427e 100644 --- a/tests/Geometry/PolygonUtilsTest.php +++ b/tests/Geometry/PolygonUtilsTest.php @@ -12,9 +12,9 @@ class PolygonUtilsTest extends TestCase { - private Polygon $polygonWhichIsNotRectangle; - private Polygon $polygon1; - private Polygon $polygon2; + private readonly Polygon $polygonWhichIsNotRectangle; + private readonly Polygon $polygon1; + private readonly Polygon $polygon2; public function __construct(?string $name = null, array $data = [], $dataName = '') { diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 13f06f46..51637a4a 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -5,7 +5,7 @@ namespace Input; use Mindee\Error\ErrorCode; -use Mindee\Error\MindeePDFException; +use Mindee\Error\MindeePdfException; use Mindee\Error\MindeeSourceException; use Mindee\Image\ImageCompressor; use Mindee\Input\Base64Input; @@ -13,8 +13,8 @@ use Mindee\Input\FileInput; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; -use Mindee\PDF\PDFCompressor; -use Mindee\PDF\PDFUtils; +use Mindee\Pdf\PdfCompressor; +use Mindee\Pdf\PdfUtils; use Mindee\V1\Client; use PHPUnit\Framework\TestCase; use setasign\Fpdi\Fpdi; @@ -24,7 +24,7 @@ use function count; -use const Mindee\V1\HTTP\API_KEY_ENV_NAME; +use const Mindee\V1\Http\API_KEY_ENV_NAME; use const Mindee\Input\KEEP_ONLY; use const Mindee\Input\REMOVE; @@ -69,20 +69,20 @@ protected function tearDown(): void } - public function testPDFCountPages(): void + public function testPdfCountPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFReconstructOK(): void + public function testPdfReconstructOK(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); self::assertSame(5, $inputObj->getPageCount()); } - public function testPDFReadContents(): void + public function testPdfReadContents(): void { $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $contents = $inputDoc->readContents(); @@ -90,9 +90,9 @@ public function testPDFReadContents(): void } /** - * @dataProvider providePDFCutNPagesCases + * @dataProvider providePdfCutNPagesCases */ - public function testPDFCutNPages(array $indexes): void + public function testPdfCutNPages(array $indexes): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions($indexes, KEEP_ONLY, 2)); @@ -121,7 +121,7 @@ public function testPDFCutNPages(array $indexes): void $basePdf->Close(); $cutPdf->Close(); } catch (PdfParserException|PdfReaderException $e) { - throw new MindeePDFException( + throw new MindeePdfException( "Failed to read PDF file.", ErrorCode::PDF_CANT_PROCESS, $e @@ -129,26 +129,26 @@ public function testPDFCutNPages(array $indexes): void } } - public static function providePDFCutNPagesCases(): iterable + public static function providePdfCutNPagesCases(): iterable { return [[[0]], [[0, -2]], [[0, -2, -1]]]; } - public function testPDFKeep5FirstPages(): void + public function testPdfKeep5FirstPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], KEEP_ONLY, 2)); self::assertSame(5, $inputObj->getPageCount()); } - public function testPDFKeepInvalidPages(): void + public function testPdfKeepInvalidPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 17], KEEP_ONLY, 2)); self::assertSame(2, $inputObj->getPageCount()); } - public function testPDFRemove5LastPages(): void + public function testPdfRemove5LastPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); @@ -156,36 +156,36 @@ public function testPDFRemove5LastPages(): void self::assertSame(7, $inputObj->getPageCount()); } - public function testPDFRemove5FirstPages(): void + public function testPdfRemove5FirstPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([0, 1, 2, 3, 4], REMOVE, 2)); self::assertSame(7, $inputObj->getPageCount()); } - public function testPDFRemoveInvalidPages(): void + public function testPdfRemoveInvalidPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputObj->applyPageOptions(new PageOptions([16], REMOVE, 2)); self::assertSame(12, $inputObj->getPageCount()); } - public function testPDFKeepNoPages(): void + public function testPdfKeepNoPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeePDFException::class); + $this->expectException(MindeePdfException::class); $inputObj->applyPageOptions(new PageOptions([], KEEP_ONLY, 2)); } - public function testPDFRemoveAllPages(): void + public function testPdfRemoveAllPages(): void { $inputObj = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeePDFException::class); + $this->expectException(MindeePdfException::class); $pageOptions = new PageOptions(range(0, $inputObj->getPageCount() - 1), REMOVE, 2); $inputObj->applyPageOptions(pageOptions: $pageOptions); } - public function testPDFInputFromFile(): void + public function testPdfInputFromFile(): void { $fileContents = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $fileRef = fopen(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf", "r"); @@ -195,7 +195,7 @@ public function testPDFInputFromFile(): void self::assertSame($fileContents, $contents[1]); } - public function testPDFInputFromBytes(): void + public function testPdfInputFromBytes(): void { $pdfBytes = file_get_contents(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); $inputDoc = new BytesInput($pdfBytes, "dummy.pdf"); @@ -213,21 +213,21 @@ public function testInputFromRawb64String(): void self::assertSame(str_replace("\n", "", $pdfBytes), str_replace("\n", "", base64_encode($contents[1]))); } - public function testShouldNotRaiseMimeErrorForBrokenFixablePDF(): void + public function testShouldNotRaiseMimeErrorForBrokenFixablePdf(): void { $this->expectNotToPerformAssertions(); $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); } - public function testShouldRaiseErrorForBrokenUnfixablePDF(): void + public function testShouldRaiseErrorForBrokenUnfixablePdf(): void { $this->expectException(MindeeSourceException::class); $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); } - public function testShouldSendCorrectResultsForBrokenFixableInvoicePDF(): void + public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf(): void { $sourceDocOriginal = $this->dummyClient->sourceFromPath( TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' @@ -285,7 +285,7 @@ public function testDirectImageQualityCompression(): void self::assertGreaterThan($compressSize[1], $compressSize[10]); } - public function testPDFSourceText(): void + public function testPdfSourceText(): void { $imageInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $pdfEmptyInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); @@ -295,7 +295,7 @@ public function testPDFSourceText(): void self::assertFalse($imageInput->hasSourceText(), "An image should not have any text."); } - public function testCompressPDFFromInputSource(): void + public function testCompressPdfFromInputSource(): void { $pdfInput = $this->dummyClient->sourceFromPath( TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" @@ -319,7 +319,7 @@ public function testCompressPDFFromInputSource(): void self::assertLessThan($sizeOriginal, $sizeCompressed); } - public function testCompressPDFFromCompressor(): void + public function testCompressPdfFromCompressor(): void { $pdfInput = $this->dummyClient->sourceFromPath( TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' @@ -328,10 +328,10 @@ public function testCompressPDFFromCompressor(): void self::assertFalse($pdfInput->hasSourceText()); $pdfCompresses = [ - 85 => PDFCompressor::compress($pdfInput->fileObject), - 75 => PDFCompressor::compress($pdfInput->fileObject, 75), - 50 => PDFCompressor::compress($pdfInput->fileObject, 50), - 10 => PDFCompressor::compress($pdfInput->fileObject, 10), + 85 => PdfCompressor::compress($pdfInput->fileObject), + 75 => PdfCompressor::compress($pdfInput->fileObject, 75), + 50 => PdfCompressor::compress($pdfInput->fileObject, 50), + 10 => PdfCompressor::compress($pdfInput->fileObject, 10), ]; $outputFiles = [ 85 => TestingUtilities::getRootDataDir() . "/output/compress_direct_85.pdf", @@ -354,7 +354,7 @@ public function testCompressPDFFromCompressor(): void self::assertGreaterThan($compressSize[10], $compressSize[50]); } - public function testSourceTextPDFCompression(): void + public function testSourceTextPdfCompression(): void { $pdfInput = $this->dummyClient->sourceFromPath( @@ -374,7 +374,7 @@ public function testSourceTextPDFCompression(): void self::assertSame( str_repeat('*', 650), - implode('', str_replace(" ", "", PDFUtils::extractPagesTextElements(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) + implode('', str_replace(" ", "", PdfUtils::extractPagesTextElements(TestingUtilities::getRootDataDir() . "/output/text_multipage.pdf"))) ); } } diff --git a/tests/Input/URLInputSourceTest.php b/tests/Input/UrlInputSourceTest.php similarity index 79% rename from tests/Input/URLInputSourceTest.php rename to tests/Input/UrlInputSourceTest.php index 275991d3..272a9611 100644 --- a/tests/Input/URLInputSourceTest.php +++ b/tests/Input/UrlInputSourceTest.php @@ -5,13 +5,13 @@ namespace Input; use Mindee\Error\MindeeSourceException; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V1\Client; use PHPUnit\Framework\TestCase; -use const Mindee\V1\HTTP\API_KEY_ENV_NAME; +use const Mindee\V1\Http\API_KEY_ENV_NAME; -class URLInputSourceTest extends TestCase +class UrlInputSourceTest extends TestCase { private string $oldKey; protected Client $dummyClient; @@ -27,16 +27,16 @@ protected function tearDown(): void putenv('MINDEE_API_KEY=' . $this->oldKey); } - public function testInputFromHTTPShouldNotThrow(): void + public function testInputFromHttpShouldNotThrow(): void { $inputDoc = $this->dummyClient->sourceFromUrl("https://example.com/invoice.pdf"); - self::assertInstanceOf(URLInputSource::class, $inputDoc); + self::assertInstanceOf(UrlInputSource::class, $inputDoc); } - public function testInputFromHTTPShouldThrow(): void + public function testInputFromHttpShouldThrow(): void { $this->expectException(MindeeSourceException::class); - new URLInputSource(url: "http://example.com/invoice.pdf"); + new UrlInputSource(url: "http://example.com/invoice.pdf"); } public function testDownloadFileFails(): void diff --git a/tests/V1/CLI/MindeeCLICommandTest.php b/tests/V1/CLI/MindeeCLICommandTest.php index b918fb04..9d9cde6e 100644 --- a/tests/V1/CLI/MindeeCLICommandTest.php +++ b/tests/V1/CLI/MindeeCLICommandTest.php @@ -24,7 +24,7 @@ public function testInvalidFilePath(): void { $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); self::assertSame(1, $cmdOutput["code"]); - self::assertTrue(str_contains($cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); + self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); } public function testInvalidKey(): void @@ -38,6 +38,6 @@ public function testInvalidProduct(): void { $cmdOutput = MindeeCLITestingUtilities::executeTest(["invalid-product", $this->filePath, "-k", "invalid-key", "-D"]); self::assertSame(1, $cmdOutput["code"]); - self::assertTrue(str_contains($cmdOutput["output"][0], "Invalid product: invalid-product")); + self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid product: invalid-product")); } } diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/CLI/MindeeCLICommandTestFunctional.php index 5dc870ea..ec066319 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/CLI/MindeeCLICommandTestFunctional.php @@ -62,7 +62,7 @@ public function testProduct($productName, $async, $additionnalArgs = []): void $cmdOutput = $this->runValidCall($productName, $async, $additionnalArgs); self::assertSame(0, $cmdOutput["code"], $productName . ($async ? " async" : " sync") . " test (code)."); self::assertTrue( - str_contains($cmdOutput["output"][1], "Document"), + str_contains((string) $cmdOutput["output"][1], "Document"), $productName . ($async ? " async" : " sync") . " test (string return)." ); } diff --git a/tests/V1/Error/MindeeHttpExceptionTest.php b/tests/V1/Error/MindeeHttpExceptionTest.php index 4b7193bc..16cd1eb7 100644 --- a/tests/V1/Error/MindeeHttpExceptionTest.php +++ b/tests/V1/Error/MindeeHttpExceptionTest.php @@ -27,31 +27,31 @@ protected function setUp(): void ); } - public function testHTTPClientErrorShouldRaise(): void + public function testHttpClientErrorShouldRaise(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->parse(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueClientException(): void + public function testHttpEnqueueClientException(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPParseClientException(): void + public function testHttpParseClientException(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } - public function testHTTPEnqueueAndParseClientException(): void + public function testHttpEnqueueAndParseClientException(): void { $this->expectException(MindeeHttpClientException::class); $this->dummyClient->enqueueAndParse(InvoiceV4::class, $this->dummyFile); } - public function testHTTP400Exception(): void + public function testHttp400Exception(): void { $json = file_get_contents($this->errorDir . "error_400_no_details.json"); $errorObj = ["data" => json_decode($json, true), "code" => 400]; @@ -64,7 +64,7 @@ public function testHTTP400Exception(): void throw $error400; } - public function testHTTP401Exception(): void + public function testHttp401Exception(): void { $json = file_get_contents($this->errorDir . "error_401_invalid_token.json"); $errorObj = ["data" => json_decode($json, true), "code" => 401]; @@ -77,7 +77,7 @@ public function testHTTP401Exception(): void throw $error401; } - public function testHTTP429Exception(): void + public function testHttp429Exception(): void { $json = file_get_contents($this->errorDir . "error_429_too_many_requests.json"); $errorObj = ["data" => json_decode($json, true), "code" => 429]; @@ -90,7 +90,7 @@ public function testHTTP429Exception(): void throw $error429; } - public function testHTTP500Exception(): void + public function testHttp500Exception(): void { $json = file_get_contents($this->errorDir . "error_500_inference_fail.json"); $errorObj = ["data" => json_decode($json, true), "code" => 500]; @@ -103,7 +103,7 @@ public function testHTTP500Exception(): void throw $error500; } - public function testHTTP500HTMLError(): void + public function testHttp500HTMLError(): void { $errorRefContents = file_get_contents($this->errorDir . "error_50x.html"); $error500 = MindeeHttpException::handleError("dummy-url", ["data" => $errorRefContents, "code" => 500]); diff --git a/tests/V1/Extraction/ImageExtractorTest.php b/tests/V1/Extraction/ImageExtractorTest.php index 380af8fe..a2a1e3fc 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Extraction/ImageExtractorTest.php @@ -86,7 +86,7 @@ public function testGivenAnImageShouldExtractValueFields(): void } } - public function testGivenAPDFShouldExtractPositionFields(): void + public function testGivenAPdfShouldExtractPositionFields(): void { $imageInput = new PathInput( TestingUtilities::getV1DataDir() . "/products/multi_receipts_detector/multipage_sample.pdf" diff --git a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php index 5097b008..5ee29e77 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php @@ -4,7 +4,7 @@ namespace V1\Extraction; -use Mindee\Extraction\PDFExtractor; +use Mindee\Extraction\PdfExtractor; use Mindee\Input\PathInput; use Mindee\V1\Client; use Mindee\V1\Parsing\Common\Document; @@ -32,7 +32,7 @@ private function prepareInvoiceReturn(string $rstFilePath, Document $invoicePred * * @group functional */ - public function testPDFShouldExtractInvoicesStrict(): void + public function testPdfShouldExtractInvoicesStrict(): void { $client = new Client(); $invoiceSplitterInput = new PathInput( @@ -40,7 +40,7 @@ public function testPDFShouldExtractInvoicesStrict(): void ); $response = $client->enqueueAndParse(InvoiceSplitterV1::class, $invoiceSplitterInput); $inference = $response->document->inference; - $pdfExtractor = new PDFExtractor($invoiceSplitterInput); + $pdfExtractor = new PdfExtractor($invoiceSplitterInput); self::assertSame(2, $pdfExtractor->getPageCount()); $extractedPdfsStrict = $pdfExtractor->extractInvoices($inference->prediction->invoicePageGroups); diff --git a/tests/V1/Extraction/PDFExtractorTest.php b/tests/V1/Extraction/PdfExtractorTest.php similarity index 58% rename from tests/V1/Extraction/PDFExtractorTest.php rename to tests/V1/Extraction/PdfExtractorTest.php index aa1c516b..9c2d6ef2 100644 --- a/tests/V1/Extraction/PDFExtractorTest.php +++ b/tests/V1/Extraction/PdfExtractorTest.php @@ -4,7 +4,7 @@ namespace V1\Extraction; -use Mindee\Extraction\PDFExtractor; +use Mindee\Extraction\PdfExtractor; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; use Mindee\V1\Client; @@ -12,7 +12,7 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -class PDFExtractorTest extends TestCase +class PdfExtractorTest extends TestCase { private Client $dummyClient; @@ -20,56 +20,56 @@ protected function setUp(): void { $this->dummyClient = new Client("dummy-key"); } - public function testGivenAnImageShouldExtractAPDF(): void + public function testGivenAnImageShouldExtractAPdf(): void { $jpg = TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg"; $localInput = new PathInput($jpg); - self::assertFalse($localInput->isPDF()); - $extractor = new PDFExtractor($localInput); + self::assertFalse($localInput->isPdf()); + $extractor = new PdfExtractor($localInput); self::assertSame(1, $extractor->getPageCount()); } /** * */ - public function testGivenAPDFShouldExtractInvoicesNoStrict(): void + public function testGivenAPdfShouldExtractInvoicesNoStrict(): void { $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); $response = $this->getPrediction(); self::assertNotNull($response); $inference = $response->document->inference; - $extractor = new PDFExtractor($pdf); + $extractor = new PdfExtractor($pdf); self::assertSame(5, $extractor->getPageCount()); - $extractedPDFSNoStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups); - self::assertCount(3, $extractedPDFSNoStrict); - self::assertSame("invoice_5p_001-001.pdf", $extractedPDFSNoStrict[0]->getFileName()); - self::assertSame(1, $extractedPDFSNoStrict[0]->getPageCount()); - self::assertSame("invoice_5p_002-004.pdf", $extractedPDFSNoStrict[1]->getFileName()); - self::assertSame(3, $extractedPDFSNoStrict[1]->getPageCount()); - self::assertSame("invoice_5p_005-005.pdf", $extractedPDFSNoStrict[2]->getFileName()); - self::assertSame(1, $extractedPDFSNoStrict[2]->getPageCount()); + $extractedPdfSNoStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups); + self::assertCount(3, $extractedPdfSNoStrict); + self::assertSame("invoice_5p_001-001.pdf", $extractedPdfSNoStrict[0]->getFileName()); + self::assertSame(1, $extractedPdfSNoStrict[0]->getPageCount()); + self::assertSame("invoice_5p_002-004.pdf", $extractedPdfSNoStrict[1]->getFileName()); + self::assertSame(3, $extractedPdfSNoStrict[1]->getPageCount()); + self::assertSame("invoice_5p_005-005.pdf", $extractedPdfSNoStrict[2]->getFileName()); + self::assertSame(1, $extractedPdfSNoStrict[2]->getPageCount()); } /** * */ - public function testGivenAPDFShouldExtractInvoicesStrict(): void + public function testGivenAPdfShouldExtractInvoicesStrict(): void { $pdf = new PathInput(TestingUtilities::getV1DataDir() . "/products/invoice_splitter/invoice_5p.pdf"); $response = $this->getPrediction(); self::assertNotNull($response); $inference = $response->document->inference; - $extractor = new PDFExtractor($pdf); + $extractor = new PdfExtractor($pdf); self::assertSame(5, $extractor->getPageCount()); - $extractedPDFStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups, true); - self::assertCount(2, $extractedPDFStrict); - self::assertSame("invoice_5p_001-001.pdf", $extractedPDFStrict[0]->getFileName()); - self::assertSame(1, $extractedPDFStrict[0]->getPageCount()); - self::assertSame("invoice_5p_002-005.pdf", $extractedPDFStrict[1]->getFileName()); - self::assertSame(4, $extractedPDFStrict[1]->getPageCount()); + $extractedPdfStrict = $extractor->extractInvoices($inference->prediction->invoicePageGroups, true); + self::assertCount(2, $extractedPdfStrict); + self::assertSame("invoice_5p_001-001.pdf", $extractedPdfStrict[0]->getFileName()); + self::assertSame(1, $extractedPdfStrict[0]->getPageCount()); + self::assertSame("invoice_5p_002-005.pdf", $extractedPdfStrict[1]->getFileName()); + self::assertSame(4, $extractedPdfStrict[1]->getPageCount()); } private function getPrediction() diff --git a/tests/V1/Http/MindeeApiTest.php b/tests/V1/Http/MindeeApiTest.php index 4cb8af19..e958ad3c 100644 --- a/tests/V1/Http/MindeeApiTest.php +++ b/tests/V1/Http/MindeeApiTest.php @@ -5,12 +5,12 @@ namespace V1\Http; use Mindee\Error\MindeeException; -use Mindee\V1\HTTP\MindeeAPI; +use Mindee\V1\Http\MindeeApi; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; use Mindee\V1\Client; -use const Mindee\V1\HTTP\API_KEY_ENV_NAME; +use const Mindee\V1\Http\API_KEY_ENV_NAME; class MindeeApiTest extends TestCase { @@ -27,7 +27,7 @@ protected function tearDown(): void public function testGivenOTSParametersAProperMindeeApiObjectShouldBeCreated(): void { - $settings = new MindeeAPI("my-api-key", InvoiceSplitterV1::$endpointName); + $settings = new MindeeApi("my-api-key", InvoiceSplitterV1::$endpointName); self::assertSame("my-api-key", $settings->apiKey); self::assertSame(InvoiceSplitterV1::$endpointName, $settings->endpointName); self::assertSame(Client::DEFAULT_OWNER, $settings->accountName); @@ -36,7 +36,7 @@ public function testGivenOTSParametersAProperMindeeApiObjectShouldBeCreated(): v public function testGivenCustomParametersAProperMindeeApiObjectShouldBeCreated(): void { - $settings = new MindeeAPI("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); + $settings = new MindeeApi("my-api-key", "custom-endpoint-name", "custom-owner-name", "1.3"); self::assertSame("my-api-key", $settings->apiKey); self::assertSame("custom-endpoint-name", $settings->endpointName); self::assertSame("custom-owner-name", $settings->accountName); @@ -47,6 +47,6 @@ public function testGivenInvalidApiKeyAnExceptionShouldBeThrown(): void { $this->expectException(MindeeException::class); putenv(API_KEY_ENV_NAME . '='); - new MindeeAPI(null, InvoiceSplitterV1::$endpointName); + new MindeeApi(null, InvoiceSplitterV1::$endpointName); } } diff --git a/tests/V1/Input/URLInputSourceTestFunctional.php b/tests/V1/Input/UrlInputSourceTestFunctional.php similarity index 97% rename from tests/V1/Input/URLInputSourceTestFunctional.php rename to tests/V1/Input/UrlInputSourceTestFunctional.php index b672f42f..d95ec9c9 100644 --- a/tests/V1/Input/URLInputSourceTestFunctional.php +++ b/tests/V1/Input/UrlInputSourceTestFunctional.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -class URLInputSourceTestFunctional extends TestCase +class UrlInputSourceTestFunctional extends TestCase { protected Client $client; protected string $outputFilePath; diff --git a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php index eddb9966..25c3cba1 100644 --- a/tests/V1/Parsing/Common/AsyncPredictResponseTest.php +++ b/tests/V1/Parsing/Common/AsyncPredictResponseTest.php @@ -4,7 +4,7 @@ namespace V1\Parsing\Common; -use Mindee\V1\HTTP\ResponseValidation; +use Mindee\V1\Http\ResponseValidation; use Mindee\V1\Parsing\Common\AsyncPredictResponse; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 1e96dbee..60654471 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -40,7 +40,7 @@ public function testShouldSendCropperExtra(): void self::assertGreaterThan(0, count($response->document->inference->pages[0]->extras->cropper->croppings)); } - public function testShouldSendFullTextOCRExtra(): void + public function testShouldSendFullTextOcrExtra(): void { $sample = $this->client->sourceFromPath( TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" @@ -52,6 +52,6 @@ public function testShouldSendFullTextOCRExtra(): void $response = $this->client->enqueueAndParse(InternationalIdV2::class, $sample, $predictMethodOptions); self::assertNotNull($response->document->extras->fullTextOcr); - self::assertGreaterThan(10, strlen($response->document->extras->fullTextOcr->content)); + self::assertGreaterThan(10, strlen((string) $response->document->extras->fullTextOcr->content)); } } diff --git a/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php similarity index 91% rename from tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php rename to tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php index eb90ab63..2594f049 100644 --- a/tests/V1/Parsing/Common/Extras/FullTextOCRExtraTest.php +++ b/tests/V1/Parsing/Common/Extras/FullTextOcrExtraTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -class FullTextOCRExtraTest extends TestCase +class FullTextOcrExtraTest extends TestCase { private $extrasDir; @@ -27,7 +27,7 @@ private function loadDocument() return $response->document; } - public function testGetsFullTextOCRResult(): void + public function testGetsFullTextOcrResult(): void { $expectedText = file_get_contents($this->extrasDir . '/full_text_ocr/full_text_ocr.txt'); diff --git a/tests/V1/Parsing/Common/OCR/OCRTest.php b/tests/V1/Parsing/Common/Ocr/OcrTest.php similarity index 88% rename from tests/V1/Parsing/Common/OCR/OCRTest.php rename to tests/V1/Parsing/Common/Ocr/OcrTest.php index 1fa20a6d..74b492d3 100644 --- a/tests/V1/Parsing/Common/OCR/OCRTest.php +++ b/tests/V1/Parsing/Common/Ocr/OcrTest.php @@ -2,22 +2,22 @@ declare(strict_types=1); -namespace V1\Parsing\Common\OCR; +namespace V1\Parsing\Common\Ocr; -use Mindee\V1\Parsing\Common\OCR\OCR; +use Mindee\V1\Parsing\Common\Ocr\Ocr; use PHPUnit\Framework\TestCase; use TestingUtilities; -class OCRTest extends TestCase +class OcrTest extends TestCase { - private OCR $ocrObject; + private Ocr $ocrObject; protected function setup(): void { $json = file_get_contents( TestingUtilities::getV1DataDir() . "/extras/ocr/complete.json" ); $jsonData = json_decode($json, true); - $this->ocrObject = new OCR($jsonData["document"]["ocr"]); + $this->ocrObject = new Ocr($jsonData["document"]["ocr"]); } public function testResponse(): void { diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 6ff0e62a..83993d69 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -9,7 +9,7 @@ use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; use Mindee\V2\Client; -use Mindee\V2\HTTP\MindeeAPIV2; +use Mindee\V2\Http\MindeeApiV2; use Mindee\V2\Parsing\JobResponse; use Mindee\V2\Product\Extraction\ExtractionResponse; use Mindee\V2\Product\Extraction\Params\ExtractionParameters; @@ -20,19 +20,18 @@ class ClientV2Test extends TestCase { - private static function makeClientWithMockedApi(MindeeAPIV2 $mockedApi): Client + private static function makeClientWithMockedApi(MindeeApiV2 $mockedApi): Client { $client = new Client("dummy"); $reflection = new ReflectionClass($client); $property = $reflection->getProperty('mindeeApi'); - $property->setAccessible(true); $property->setValue($client, $mockedApi); return $client; } public function testEnqueuePostAsync(): void { - $predictable = $this->createMock(MindeeAPIV2::class); + $predictable = $this->createMock(MindeeApiV2::class); $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $predictable->expects(self::once()) ->method('reqPostEnqueue') @@ -55,8 +54,8 @@ public function testEnqueuePostAsync(): void public function testDocumentGetJobAsync(): void { - /** @var MindeeAPIV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeAPIV2::class); + /** @var MindeeApiV2&MockObject $predictable */ + $predictable = $this->createMock(MindeeApiV2::class); $syntheticResponse = file_get_contents(TestingUtilities::getV2DataDir() . '/job/ok_processing.json'); $processing = new JobResponse(json_decode($syntheticResponse, true)); @@ -76,8 +75,8 @@ public function testDocumentGetJobAsync(): void public function testDocumentGetInferenceAsync(): void { - /** @var MindeeAPIV2&MockObject $predictable */ - $predictable = $this->createMock(MindeeAPIV2::class); + /** @var MindeeApiV2&MockObject $predictable */ + $predictable = $this->createMock(MindeeApiV2::class); $jsonFile = TestingUtilities::getV2DataDir() . '/products/extraction/financial_document/complete.json'; self::assertFileExists($jsonFile, 'Test resource file must exist'); diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index c532676b..6c26449e 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -6,7 +6,7 @@ use Mindee\Error\MindeeV2HttpException; use Mindee\Input\PathInput; -use Mindee\Input\URLInputSource; +use Mindee\Input\UrlInputSource; use Mindee\V2\Client; use Mindee\V2\Product\Extraction\ExtractionResponse; use Mindee\V2\Product\Extraction\Params\ExtractionParameters; @@ -164,7 +164,7 @@ public function testInvalidWebhookIDsMustThrowError(): void public function testUrlInputSourceMustNotRaiseErrors(): void { - $urlSource = new URLInputSource(getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')); + $urlSource = new UrlInputSource(getenv('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')); $inferenceParams = new ExtractionParameters($this->modelId); @@ -227,7 +227,7 @@ public function testMultipleWebhooksMustSucceed(): void $inferenceParams = new ExtractionParameters( $this->modelId, - webhooksIds: [ + webhookIds: [ getenv('MINDEE_V2_FAILURE_WEBHOOK_ID'), getenv('MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID')] ); diff --git a/tests/V2/FileOperations/CropFunctional.php b/tests/V2/FileOperations/CropFunctional.php index 66de7fa7..d0ce95b8 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -93,7 +93,7 @@ public function testExtractCropsFromImageCorrectly(): void self::assertLessThanOrEqual(103000, $file2Info); } - public function testExtractCropsFromEachPDFPageCorrectly(): void + public function testExtractCropsFromEachPdfPageCorrectly(): void { $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/crop/multipage_sample.pdf'); $cropParams = new CropParameters($this->cropModelId); diff --git a/tests/V2/FileOperations/SplitFunctional.php b/tests/V2/FileOperations/SplitFunctional.php index 39314f38..16ca313e 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -60,7 +60,7 @@ private function checkFindocReturn(ExtractionResponse $findocResponse): void self::assertGreaterThan(0, $totalAmount->value); } - public function testExtractSplitsFromPDFCorrectly(): void + public function testExtractSplitsFromPdfCorrectly(): void { $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/split/default_sample.pdf'); $splitParams = new SplitParameters($this->splitModelId); diff --git a/tests/V2/Input/LocalResponseV2Test.php b/tests/V2/Input/LocalResponseV2Test.php index 2d3dc131..1109af1f 100644 --- a/tests/V2/Input/LocalResponseV2Test.php +++ b/tests/V2/Input/LocalResponseV2Test.php @@ -25,7 +25,6 @@ protected function assertLocalResponse(LocalResponse $localResponse): void $signature = "e51bdf80f1a08ed44ee161100fc30a25cb35b4ede671b0a575dc9064a3f5dbf1"; $reflectedLocalResponse = new ReflectionClass($localResponse); $reflectedFile = $reflectedLocalResponse->getProperty('file'); - $reflectedFile->setAccessible(true); self::assertNotNull($reflectedFile); self::assertFalse($localResponse->isValidHMACSignature($fakeHMACSigning, "fake HMAC signature")); self::assertSame($signature, $localResponse->getHmacSignature($fakeHMACSigning)); diff --git a/tests/V2/Parsing/ExtractionResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php index d80503a1..b06d6522 100644 --- a/tests/V2/Parsing/ExtractionResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -252,7 +252,7 @@ public function testStandardFieldTypesMustExposeCorrectTypes(): void self::assertInstanceOf(ObjectField::class, $fieldObject); $fieldObjectFields = $fieldObject->fields; self::assertCount(2, $fieldObjectFields); - foreach ($fieldObjectFields as $fieldName => $subField) { + foreach ($fieldObjectFields as $subField) { self::assertInstanceOf(SimpleField::class, $subField); } diff --git a/tests/V2/Product/OCRFunctional.php b/tests/V2/Product/OcrFunctional.php similarity index 75% rename from tests/V2/Product/OCRFunctional.php rename to tests/V2/Product/OcrFunctional.php index 25517311..ed870e60 100644 --- a/tests/V2/Product/OCRFunctional.php +++ b/tests/V2/Product/OcrFunctional.php @@ -6,14 +6,14 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; -use Mindee\V2\Product\OCR\OCRResponse; -use Mindee\V2\Product\OCR\Params\OCRParameters; +use Mindee\V2\Product\Ocr\OcrResponse; +use Mindee\V2\Product\Ocr\Params\OcrParameters; use PHPUnit\Framework\TestCase; use TestingUtilities; require_once(__DIR__ . "/../../TestingUtilities.php"); -class OCRFunctional extends TestCase +class OcrFunctional extends TestCase { private Client $client; private string $ocrModelId; @@ -27,17 +27,17 @@ protected function setUp(): void } /** - * Tests the success of the OCR process using a default sample file. + * Tests the success of the Ocr process using a default sample file. * */ - public function testOCRDefaultSampleMustSucceed(): void + public function testOcrDefaultSampleMustSucceed(): void { $inputSource = new PathInput( TestingUtilities::getV2ProductDir() . '/ocr/default_sample.jpg' ); - $productParams = new OCRParameters($this->ocrModelId); - $response = $this->client->enqueueAndGetResult(OCRResponse::class, $inputSource, $productParams); + $productParams = new OcrParameters($this->ocrModelId); + $response = $this->client->enqueueAndGetResult(OcrResponse::class, $inputSource, $productParams); self::assertNotNull($response); self::assertNotNull($response->inference); diff --git a/tests/V2/Product/OCRTest.php b/tests/V2/Product/OcrTest.php similarity index 88% rename from tests/V2/Product/OCRTest.php rename to tests/V2/Product/OcrTest.php index 3ff0a7ff..66d9a667 100644 --- a/tests/V2/Product/OCRTest.php +++ b/tests/V2/Product/OcrTest.php @@ -6,14 +6,14 @@ use PHPUnit\Framework\TestCase; use TestingUtilities; -use Mindee\V2\Product\OCR\OCRResponse; +use Mindee\V2\Product\Ocr\OcrResponse; require_once(__DIR__ . "/../../TestingUtilities.php"); /** - * OCR unit tests. + * Ocr unit tests. */ -class OCRTest extends TestCase +class OcrTest extends TestCase { /** * Load a JSON sample and return its decoded contents. @@ -41,12 +41,12 @@ private function assertInferenceResponse(mixed $response): void } /** - * Should correctly map properties when reading a single OCR JSON. + * Should correctly map properties when reading a single Ocr JSON. */ - public function testOCRWhenSingleMustHaveValidProperties(): void + public function testOcrWhenSingleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_single.json"); - $response = new OCRResponse($jsonSample); + $response = new OcrResponse($jsonSample); $this->assertInferenceResponse($response); @@ -76,12 +76,12 @@ public function testOCRWhenSingleMustHaveValidProperties(): void } /** - * Should correctly map properties when reading a multiple OCR JSON. + * Should correctly map properties when reading a multiple Ocr JSON. */ - public function testOCRWhenMultipleMustHaveValidProperties(): void + public function testOcrWhenMultipleMustHaveValidProperties(): void { $jsonSample = self::getInference("ocr/ocr_multiple.json"); - $response = new OCRResponse($jsonSample); + $response = new OcrResponse($jsonSample); $this->assertInferenceResponse($response); From 48925ea326e1bfb2a5ccc53ebe6283de94cf59d1 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Wed, 27 May 2026 15:59:39 +0200 Subject: [PATCH 06/11] :recycle: cleanup lingering issues (#190) --- bin/DocumentCommandConfig.php | 2 +- bin/MindeeCLICommand.php | 25 ++--- bin/MindeeCLIDocuments.php | 2 +- bin/cli.php | 2 +- docs/code_samples/bank_account_details_v1.txt | 3 +- docs/code_samples/bank_account_details_v2.txt | 3 +- docs/code_samples/bank_check_v1.txt | 3 +- docs/code_samples/barcode_reader_v1.txt | 3 +- docs/code_samples/bill_of_lading_v1_async.txt | 3 +- docs/code_samples/business_card_v1_async.txt | 3 +- docs/code_samples/carte_grise_v1.txt | 3 +- docs/code_samples/cropper_v1.txt | 3 +- docs/code_samples/custom_v1.txt | 2 +- docs/code_samples/default.txt | 3 +- docs/code_samples/default_async.txt | 3 +- docs/code_samples/delivery_notes_v1_async.txt | 3 +- docs/code_samples/driver_license_v1_async.txt | 3 +- .../code_samples/energy_bill_fra_v1_async.txt | 3 +- docs/code_samples/expense_receipts_v5.txt | 3 +- .../expense_receipts_v5_async.txt | 3 +- docs/code_samples/financial_document_v1.txt | 3 +- .../financial_document_v1_async.txt | 3 +- .../french_healthcard_v1_async.txt | 3 +- docs/code_samples/idcard_fr_v1.txt | 3 +- docs/code_samples/idcard_fr_v2.txt | 3 +- docs/code_samples/ind_passport_v1_async.txt | 3 +- .../international_id_v2_async.txt | 3 +- .../invoice_splitter_v1_async.txt | 3 +- docs/code_samples/invoices_v4.txt | 3 +- docs/code_samples/invoices_v4_async.txt | 3 +- .../multi_receipts_detector_v1.txt | 3 +- .../code_samples/nutrition_facts_v1_async.txt | 3 +- docs/code_samples/passport_v1.txt | 3 +- docs/code_samples/payslip_fra_v3_async.txt | 3 +- docs/code_samples/resume_v1_async.txt | 3 +- .../us_healthcare_cards_v1_async.txt | 3 +- docs/code_samples/us_mail_v3_async.txt | 3 +- docs/code_samples/workflow_execution.txt | 2 +- docs/code_samples/workflow_polling.txt | 2 +- src/Error/MindeeHttpClientException.php | 12 -- src/Error/MindeeHttpServerException.php | 17 --- .../MindeeV1ClientException.php} | 6 +- .../MindeeV1HttpException.php} | 11 +- src/Error/{ => V2}/MindeeV2HttpException.php | 7 +- .../{ => V2}/MindeeV2HttpUnknownException.php | 4 +- src/{Extraction => Image}/ExtractedImage.php | 6 +- src/{Extraction => Image}/ImageExtractor.php | 6 +- src/Input/FileInput.php | 2 - src/{Extraction => Pdf}/ExtractedPdf.php | 2 +- src/{Extraction => Pdf}/PdfExtractor.php | 8 +- src/V1/Client.php | 105 ++---------------- src/V1/Image/ImageExtractor.php | 2 +- src/V2/Client.php | 19 +--- src/V2/FileOperations/Crop.php | 4 +- src/V2/FileOperations/CropFiles.php | 4 +- src/V2/FileOperations/Split.php | 4 +- src/V2/FileOperations/SplitFiles.php | 4 +- src/V2/Http/MindeeApiV2.php | 8 +- src/V2/Parsing/{ => Error}/ErrorItem.php | 2 +- src/V2/Parsing/{ => Error}/ErrorResponse.php | 2 +- .../Parsing/{ => Inference}/BaseInference.php | 5 +- .../Parsing/Inference/Field/SimpleField.php | 25 +++++ src/V2/Parsing/{ => Job}/Job.php | 3 +- src/V2/Parsing/{ => Job}/JobResponse.php | 2 +- src/V2/Parsing/{ => Job}/JobWebhook.php | 3 +- .../ClassificationInference.php | 2 +- src/V2/Product/Crop/CropInference.php | 2 +- .../Extraction/ExtractionInference.php | 2 +- src/V2/Product/Ocr/OcrInference.php | 2 +- src/V2/Product/Split/SplitInference.php | 2 +- tests/ClientTest.php | 37 +++--- .../DependencyCheckerNoExtendedTestPdf.php | 11 +- tests/Input/LocalInputSourceTest.php | 27 +++-- tests/Input/UrlInputSourceTest.php | 6 +- .../V1/CLI/MindeeCLICommandTestFunctional.php | 2 +- tests/V1/Error/MindeeHttpExceptionTest.php | 33 +++--- .../ImageExtractorTest.php | 2 +- ...ceSplitterAutoExtractionTestFunctional.php | 4 +- .../V1/Input/UrlInputSourceTestFunctional.php | 9 +- .../Extras/ExtrasIntegrationFunctional.php | 5 +- .../{Extraction => Pdf}/PdfExtractorTest.php | 4 +- tests/V1/Workflow/WorkflowTestFunctional.php | 3 +- tests/V2/ClientV2Test.php | 8 +- tests/V2/ClientV2TestFunctional.php | 8 +- tests/V2/Parsing/ExtractionResponseTest.php | 40 ++++--- tests/V2/Parsing/JobResponseTest.php | 6 +- tests/resources | 2 +- 87 files changed, 282 insertions(+), 341 deletions(-) delete mode 100644 src/Error/MindeeHttpClientException.php delete mode 100644 src/Error/MindeeHttpServerException.php rename src/Error/{MindeeClientException.php => V1/MindeeV1ClientException.php} (52%) rename src/Error/{MindeeHttpException.php => V1/MindeeV1HttpException.php} (95%) rename src/Error/{ => V2}/MindeeV2HttpException.php (89%) rename src/Error/{ => V2}/MindeeV2HttpUnknownException.php (89%) rename src/{Extraction => Image}/ExtractedImage.php (99%) rename src/{Extraction => Image}/ImageExtractor.php (99%) rename src/{Extraction => Pdf}/ExtractedPdf.php (98%) rename src/{Extraction => Pdf}/PdfExtractor.php (99%) rename src/V2/Parsing/{ => Error}/ErrorItem.php (94%) rename src/V2/Parsing/{ => Error}/ErrorResponse.php (97%) rename src/V2/Parsing/{ => Inference}/BaseInference.php (88%) rename src/V2/Parsing/{ => Job}/Job.php (97%) rename src/V2/Parsing/{ => Job}/JobResponse.php (94%) rename src/V2/Parsing/{ => Job}/JobWebhook.php (94%) rename tests/V1/{Extraction => Image}/ImageExtractorTest.php (99%) rename tests/V1/{Extraction => Image}/InvoiceSplitterAutoExtractionTestFunctional.php (97%) rename tests/V1/{Extraction => Pdf}/PdfExtractorTest.php (98%) diff --git a/bin/DocumentCommandConfig.php b/bin/DocumentCommandConfig.php index 5bea3c95..1ec30794 100644 --- a/bin/DocumentCommandConfig.php +++ b/bin/DocumentCommandConfig.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\CLI; +namespace Mindee\Cli; /** * Document configuration class for CLI usage. diff --git a/bin/MindeeCLICommand.php b/bin/MindeeCLICommand.php index 23c358ad..c2e0636d 100644 --- a/bin/MindeeCLICommand.php +++ b/bin/MindeeCLICommand.php @@ -2,9 +2,10 @@ declare(strict_types=1); -namespace Mindee\CLI; +namespace Mindee\Cli; -use Mindee\Error\MindeeHttpException; +use Exception; +use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\InputSource; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; @@ -19,7 +20,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Exception; use function count; use function in_array; @@ -253,7 +253,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $filePathOrUrl = $input->getArgument('file_path_or_url'); - $file = $this->getFileSource($filePathOrUrl, $client, $output); + $file = $this->getFileSource($filePathOrUrl, $output); if (!$file) { return Command::FAILURE; } @@ -347,7 +347,7 @@ private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputI $pagesRemove = $input->getOption('pages_remove'); $pagesKeep = $input->getOption('pages_keep'); if ($pagesKeep && $pagesRemove) { - $output->writeln("Page cut & page keep operations are mutually exclusive."); + $output->writeln("Page cut and page keep operations are mutually exclusive."); return true; } return false; @@ -357,21 +357,20 @@ private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputI * Retrieves a source file from a URL or a path. * * @param string $filePathOrUrl Path of the file, or URL if it's remote. - * @param Client $client Mindee Client. * @param OutputInterface $output Output interface of the CLI. * @return PathInput|UrlInputSource|null A valid InputSource. */ - private function getFileSource(string $filePathOrUrl, Client $client, OutputInterface $output) + private function getFileSource(string $filePathOrUrl, OutputInterface $output): PathInput|UrlInputSource|null { - if (substr($filePathOrUrl, 0, 8) !== 'https://') { + if (!str_starts_with($filePathOrUrl, 'https://')) { if (@file_exists($filePathOrUrl) || @file_get_contents($filePathOrUrl)) { - return $client->sourceFromPath($filePathOrUrl); + return new PathInput($filePathOrUrl); } else { $output->writeln("Invalid path or url provided '$filePathOrUrl'."); return null; } } - return $client->sourceFromUrl($filePathOrUrl); + return new UrlInputSource($filePathOrUrl); } /** @@ -493,7 +492,7 @@ private function executePrediction( $debug = $input->getOption('debug'); try { $result = $this->runClientPrediction($client, $product, $file, $predictMethodOptions, $isAsync, $debug); - } catch (MindeeHttpException $e) { + } catch (MindeeV1HttpException $e) { $output->writeln($e->getMessage()); return Command::FAILURE; } catch (Exception $e) { @@ -524,7 +523,7 @@ private function runClientPrediction( PredictMethodOptions $predictMethodOptions, bool $isAsync, bool $debug - ) { + ): AsyncPredictResponse|PredictResponse|string { if ($debug) { return "Command executed successfully."; } @@ -544,7 +543,7 @@ private function runClientPrediction( * @return integer Command execution code return. */ private function outputResult( - $result, + PredictResponse|AsyncPredictResponse|string $result, ?string $outputType, OutputInterface $output ): int { diff --git a/bin/MindeeCLIDocuments.php b/bin/MindeeCLIDocuments.php index d2041c43..5ce217ab 100644 --- a/bin/MindeeCLIDocuments.php +++ b/bin/MindeeCLIDocuments.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\CLI; +namespace Mindee\Cli; use Mindee\V1\Product\BarcodeReader\BarcodeReaderV1; use Mindee\V1\Product\BillOfLading\BillOfLadingV1; diff --git a/bin/cli.php b/bin/cli.php index 29c185f9..859d9766 100755 --- a/bin/cli.php +++ b/bin/cli.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\CLI; +namespace Mindee\Cli; require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/MindeeCLIDocuments.php'; diff --git a/docs/code_samples/bank_account_details_v1.txt b/docs/code_samples/bank_account_details_v1.txt index af944d38..eaf56aa0 100644 --- a/docs/code_samples/bank_account_details_v1.txt +++ b/docs/code_samples/bank_account_details_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankAccountDetailsV1::class, $inputSource); diff --git a/docs/code_samples/bank_account_details_v2.txt b/docs/code_samples/bank_account_details_v2.txt index 6dd87cf4..b3f4ce74 100644 --- a/docs/code_samples/bank_account_details_v2.txt +++ b/docs/code_samples/bank_account_details_v2.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankAccountDetailsV2::class, $inputSource); diff --git a/docs/code_samples/bank_check_v1.txt b/docs/code_samples/bank_check_v1.txt index 2dd0bf71..48c14547 100644 --- a/docs/code_samples/bank_check_v1.txt +++ b/docs/code_samples/bank_check_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BankCheckV1::class, $inputSource); diff --git a/docs/code_samples/barcode_reader_v1.txt b/docs/code_samples/barcode_reader_v1.txt index 4cc5924a..2075e019 100644 --- a/docs/code_samples/barcode_reader_v1.txt +++ b/docs/code_samples/barcode_reader_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(BarcodeReaderV1::class, $inputSource); diff --git a/docs/code_samples/bill_of_lading_v1_async.txt b/docs/code_samples/bill_of_lading_v1_async.txt index 8d1e4d2f..b277246d 100644 --- a/docs/code_samples/bill_of_lading_v1_async.txt +++ b/docs/code_samples/bill_of_lading_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(BillOfLadingV1::class, $inputSource); diff --git a/docs/code_samples/business_card_v1_async.txt b/docs/code_samples/business_card_v1_async.txt index cac0c8ce..bd9a62a5 100644 --- a/docs/code_samples/business_card_v1_async.txt +++ b/docs/code_samples/business_card_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(BusinessCardV1::class, $inputSource); diff --git a/docs/code_samples/carte_grise_v1.txt b/docs/code_samples/carte_grise_v1.txt index 53779d73..585489aa 100644 --- a/docs/code_samples/carte_grise_v1.txt +++ b/docs/code_samples/carte_grise_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(CarteGriseV1::class, $inputSource); diff --git a/docs/code_samples/cropper_v1.txt b/docs/code_samples/cropper_v1.txt index 684decd9..99fdf2bd 100644 --- a/docs/code_samples/cropper_v1.txt +++ b/docs/code_samples/cropper_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(CropperV1::class, $inputSource); diff --git a/docs/code_samples/custom_v1.txt b/docs/code_samples/custom_v1.txt index 4a19629d..3cacc1d4 100644 --- a/docs/code_samples/custom_v1.txt +++ b/docs/code_samples/custom_v1.txt @@ -14,7 +14,7 @@ use Mindee\V1\ClientOptions\PredictMethodOptions; $mindeeClient = new Client("my-api-key"); // Load a file from disk -$inputSource = $mindeeClient->sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/default.txt b/docs/code_samples/default.txt index b6e7b3c4..b917270c 100644 --- a/docs/code_samples/default.txt +++ b/docs/code_samples/default.txt @@ -1,6 +1,7 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/default_async.txt b/docs/code_samples/default_async.txt index c1f5e632..d05972b7 100644 --- a/docs/code_samples/default_async.txt +++ b/docs/code_samples/default_async.txt @@ -1,6 +1,7 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Create a custom endpoint $customEndpoint = $mindeeClient->createEndpoint( diff --git a/docs/code_samples/delivery_notes_v1_async.txt b/docs/code_samples/delivery_notes_v1_async.txt index e3f7862a..d6716398 100644 --- a/docs/code_samples/delivery_notes_v1_async.txt +++ b/docs/code_samples/delivery_notes_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(DeliveryNoteV1::class, $inputSource); diff --git a/docs/code_samples/driver_license_v1_async.txt b/docs/code_samples/driver_license_v1_async.txt index 1c4d22c6..126c06da 100644 --- a/docs/code_samples/driver_license_v1_async.txt +++ b/docs/code_samples/driver_license_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(DriverLicenseV1::class, $inputSource); diff --git a/docs/code_samples/energy_bill_fra_v1_async.txt b/docs/code_samples/energy_bill_fra_v1_async.txt index 2369c300..35d624a6 100644 --- a/docs/code_samples/energy_bill_fra_v1_async.txt +++ b/docs/code_samples/energy_bill_fra_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(EnergyBillV1::class, $inputSource); diff --git a/docs/code_samples/expense_receipts_v5.txt b/docs/code_samples/expense_receipts_v5.txt index e8d5dcfc..09c31587 100644 --- a/docs/code_samples/expense_receipts_v5.txt +++ b/docs/code_samples/expense_receipts_v5.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(ReceiptV5::class, $inputSource); diff --git a/docs/code_samples/expense_receipts_v5_async.txt b/docs/code_samples/expense_receipts_v5_async.txt index c91066d8..49254892 100644 --- a/docs/code_samples/expense_receipts_v5_async.txt +++ b/docs/code_samples/expense_receipts_v5_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(ReceiptV5::class, $inputSource); diff --git a/docs/code_samples/financial_document_v1.txt b/docs/code_samples/financial_document_v1.txt index d18d8911..71a2087d 100644 --- a/docs/code_samples/financial_document_v1.txt +++ b/docs/code_samples/financial_document_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(FinancialDocumentV1::class, $inputSource); diff --git a/docs/code_samples/financial_document_v1_async.txt b/docs/code_samples/financial_document_v1_async.txt index 6b9ea7d4..045a5572 100644 --- a/docs/code_samples/financial_document_v1_async.txt +++ b/docs/code_samples/financial_document_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(FinancialDocumentV1::class, $inputSource); diff --git a/docs/code_samples/french_healthcard_v1_async.txt b/docs/code_samples/french_healthcard_v1_async.txt index 15d41073..1ee85173 100644 --- a/docs/code_samples/french_healthcard_v1_async.txt +++ b/docs/code_samples/french_healthcard_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(HealthCardV1::class, $inputSource); diff --git a/docs/code_samples/idcard_fr_v1.txt b/docs/code_samples/idcard_fr_v1.txt index e55fafe7..574c3e21 100644 --- a/docs/code_samples/idcard_fr_v1.txt +++ b/docs/code_samples/idcard_fr_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(IdCardV1::class, $inputSource); diff --git a/docs/code_samples/idcard_fr_v2.txt b/docs/code_samples/idcard_fr_v2.txt index 35187fd0..19c20c15 100644 --- a/docs/code_samples/idcard_fr_v2.txt +++ b/docs/code_samples/idcard_fr_v2.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(IdCardV2::class, $inputSource); diff --git a/docs/code_samples/ind_passport_v1_async.txt b/docs/code_samples/ind_passport_v1_async.txt index 7739a3cd..40523afe 100644 --- a/docs/code_samples/ind_passport_v1_async.txt +++ b/docs/code_samples/ind_passport_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(IndianPassportV1::class, $inputSource); diff --git a/docs/code_samples/international_id_v2_async.txt b/docs/code_samples/international_id_v2_async.txt index 82f8c7d6..d3924b9f 100644 --- a/docs/code_samples/international_id_v2_async.txt +++ b/docs/code_samples/international_id_v2_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InternationalIdV2::class, $inputSource); diff --git a/docs/code_samples/invoice_splitter_v1_async.txt b/docs/code_samples/invoice_splitter_v1_async.txt index 6fdeaf4e..0cca340d 100644 --- a/docs/code_samples/invoice_splitter_v1_async.txt +++ b/docs/code_samples/invoice_splitter_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InvoiceSplitterV1::class, $inputSource); diff --git a/docs/code_samples/invoices_v4.txt b/docs/code_samples/invoices_v4.txt index 4d6206a5..ecb488a2 100644 --- a/docs/code_samples/invoices_v4.txt +++ b/docs/code_samples/invoices_v4.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(InvoiceV4::class, $inputSource); diff --git a/docs/code_samples/invoices_v4_async.txt b/docs/code_samples/invoices_v4_async.txt index e8ef2341..b2d9d9bd 100644 --- a/docs/code_samples/invoices_v4_async.txt +++ b/docs/code_samples/invoices_v4_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(InvoiceV4::class, $inputSource); diff --git a/docs/code_samples/multi_receipts_detector_v1.txt b/docs/code_samples/multi_receipts_detector_v1.txt index c8c11e31..31ba3e57 100644 --- a/docs/code_samples/multi_receipts_detector_v1.txt +++ b/docs/code_samples/multi_receipts_detector_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(MultiReceiptsDetectorV1::class, $inputSource); diff --git a/docs/code_samples/nutrition_facts_v1_async.txt b/docs/code_samples/nutrition_facts_v1_async.txt index 765f097c..197344e8 100644 --- a/docs/code_samples/nutrition_facts_v1_async.txt +++ b/docs/code_samples/nutrition_facts_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(NutritionFactsLabelV1::class, $inputSource); diff --git a/docs/code_samples/passport_v1.txt b/docs/code_samples/passport_v1.txt index 6968280c..24b47060 100644 --- a/docs/code_samples/passport_v1.txt +++ b/docs/code_samples/passport_v1.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file $apiResponse = $mindeeClient->parse(PassportV1::class, $inputSource); diff --git a/docs/code_samples/payslip_fra_v3_async.txt b/docs/code_samples/payslip_fra_v3_async.txt index 8e6c9f89..d185d728 100644 --- a/docs/code_samples/payslip_fra_v3_async.txt +++ b/docs/code_samples/payslip_fra_v3_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(PayslipV3::class, $inputSource); diff --git a/docs/code_samples/resume_v1_async.txt b/docs/code_samples/resume_v1_async.txt index 36d9c8b4..5efcda28 100644 --- a/docs/code_samples/resume_v1_async.txt +++ b/docs/code_samples/resume_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(ResumeV1::class, $inputSource); diff --git a/docs/code_samples/us_healthcare_cards_v1_async.txt b/docs/code_samples/us_healthcare_cards_v1_async.txt index bedbf8f2..d0f21100 100644 --- a/docs/code_samples/us_healthcare_cards_v1_async.txt +++ b/docs/code_samples/us_healthcare_cards_v1_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(HealthcareCardV1::class, $inputSource); diff --git a/docs/code_samples/us_mail_v3_async.txt b/docs/code_samples/us_mail_v3_async.txt index 3cc99840..442e74a3 100644 --- a/docs/code_samples/us_mail_v3_async.txt +++ b/docs/code_samples/us_mail_v3_async.txt @@ -1,13 +1,14 @@ sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Parse the file asynchronously $apiResponse = $mindeeClient->enqueueAndParse(UsMailV3::class, $inputSource); diff --git a/docs/code_samples/workflow_execution.txt b/docs/code_samples/workflow_execution.txt index cf8ca9be..ab95020c 100644 --- a/docs/code_samples/workflow_execution.txt +++ b/docs/code_samples/workflow_execution.txt @@ -10,7 +10,7 @@ $workflowId = "workflow-id"; $mindeeClient = new Client("my-api-key"); // Load a file from disk -$inputSource = $mindeeClient->sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); // Send the file to the workflow diff --git a/docs/code_samples/workflow_polling.txt b/docs/code_samples/workflow_polling.txt index 3271bdaa..5b542eb2 100644 --- a/docs/code_samples/workflow_polling.txt +++ b/docs/code_samples/workflow_polling.txt @@ -11,7 +11,7 @@ $workflowId = "workflow-id"; $mindeeClient = new Client("my-api-key"); // Load a file from disk -$inputSource = $mindeeClient->sourceFromPath("/path/to/the/file.ext"); +$inputSource = new PathInput("/path/to/the/file.ext"); $customEndpoint = $mindeeClient->createEndpoint( "my-endpoint", diff --git a/src/Error/MindeeHttpClientException.php b/src/Error/MindeeHttpClientException.php deleted file mode 100644 index f105efc2..00000000 --- a/src/Error/MindeeHttpClientException.php +++ /dev/null @@ -1,12 +0,0 @@ -= 400 && $code <= 499) { - return new MindeeHttpClientException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } if ($code >= 500 && $code <= 599) { - return new MindeeHttpClientException($errorObj, $url, $code); + return new self($errorObj, $url, $code); } return new self($errorObj, $url, $code); diff --git a/src/Error/MindeeV2HttpException.php b/src/Error/V2/MindeeV2HttpException.php similarity index 89% rename from src/Error/MindeeV2HttpException.php rename to src/Error/V2/MindeeV2HttpException.php index 75f23d01..21be8d06 100644 --- a/src/Error/MindeeV2HttpException.php +++ b/src/Error/V2/MindeeV2HttpException.php @@ -2,10 +2,11 @@ declare(strict_types=1); -namespace Mindee\Error; +namespace Mindee\Error\V2; -use Mindee\V2\Parsing\ErrorItem; -use Mindee\V2\Parsing\ErrorResponse; +use Mindee\Error\MindeeException; +use Mindee\V2\Parsing\Error\ErrorItem; +use Mindee\V2\Parsing\Error\ErrorResponse; /** * Exceptions relating to HTTP errors for the V2 API. diff --git a/src/Error/MindeeV2HttpUnknownException.php b/src/Error/V2/MindeeV2HttpUnknownException.php similarity index 89% rename from src/Error/MindeeV2HttpUnknownException.php rename to src/Error/V2/MindeeV2HttpUnknownException.php index 3ab851fc..66bc0c84 100644 --- a/src/Error/MindeeV2HttpUnknownException.php +++ b/src/Error/V2/MindeeV2HttpUnknownException.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace Mindee\Error; +namespace Mindee\Error\V2; -use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\Error\ErrorResponse; /** * Unknown HTTP error for the V2 API. diff --git a/src/Extraction/ExtractedImage.php b/src/Image/ExtractedImage.php similarity index 99% rename from src/Extraction/ExtractedImage.php rename to src/Image/ExtractedImage.php index 5ba66a81..794cc2d7 100644 --- a/src/Extraction/ExtractedImage.php +++ b/src/Image/ExtractedImage.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Mindee\Extraction; +namespace Mindee\Image; +use Imagick; +use ImagickException; use Mindee\Dependency\DependencyChecker; use Mindee\Error\MindeeUnhandledException; use Mindee\Input\BytesInput; -use Imagick; -use ImagickException; use function in_array; diff --git a/src/Extraction/ImageExtractor.php b/src/Image/ImageExtractor.php similarity index 99% rename from src/Extraction/ImageExtractor.php rename to src/Image/ImageExtractor.php index 764922e4..6d72ebb6 100644 --- a/src/Extraction/ImageExtractor.php +++ b/src/Image/ImageExtractor.php @@ -2,9 +2,11 @@ declare(strict_types=1); -namespace Mindee\Extraction; +namespace Mindee\Image; use Exception; +use Imagick; +use ImagickException; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeGeometryException; @@ -16,8 +18,6 @@ use Mindee\Geometry\Polygon; use Mindee\Input\LocalInputSource; use Mindee\V1\Parsing\Standard\BaseField; -use Imagick; -use ImagickException; use function count; use function sprintf; diff --git a/src/Input/FileInput.php b/src/Input/FileInput.php index f2bbff0e..5ea83d4c 100644 --- a/src/Input/FileInput.php +++ b/src/Input/FileInput.php @@ -4,8 +4,6 @@ namespace Mindee\Input; -use Mindee\Error\ErrorCode; -use Mindee\Error\MindeeSourceException; use CURLFile; /** diff --git a/src/Extraction/ExtractedPdf.php b/src/Pdf/ExtractedPdf.php similarity index 98% rename from src/Extraction/ExtractedPdf.php rename to src/Pdf/ExtractedPdf.php index ba738442..d23f3f67 100644 --- a/src/Extraction/ExtractedPdf.php +++ b/src/Pdf/ExtractedPdf.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\Extraction; +namespace Mindee\Pdf; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; diff --git a/src/Extraction/PdfExtractor.php b/src/Pdf/PdfExtractor.php similarity index 99% rename from src/Extraction/PdfExtractor.php rename to src/Pdf/PdfExtractor.php index 25bf10cb..d819bda9 100644 --- a/src/Extraction/PdfExtractor.php +++ b/src/Pdf/PdfExtractor.php @@ -2,8 +2,11 @@ declare(strict_types=1); -namespace Mindee\Extraction; +namespace Mindee\Pdf; +use Imagick; +use ImagickException; +use InvalidArgumentException; use Mindee\Dependency\DependencyChecker; use Mindee\Error\MindeePdfException; use Mindee\Input\LocalInputSource; @@ -13,9 +16,6 @@ use setasign\Fpdi\PdfParser\Filter\FilterException; use setasign\Fpdi\PdfParser\PdfParserException; use setasign\Fpdi\PdfReader\PdfReaderException; -use Imagick; -use ImagickException; -use InvalidArgumentException; use function count; use function is_array; diff --git a/src/V1/Client.php b/src/V1/Client.php index b187b962..21b8a02a 100644 --- a/src/V1/Client.php +++ b/src/V1/Client.php @@ -10,24 +10,18 @@ namespace Mindee\V1; -use CURLFile; use Exception; use Mindee\ClientOptions\PollingOptions; use Mindee\CustomSleepMixin; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; -use Mindee\Error\MindeeClientException; use Mindee\Error\MindeeException; -use Mindee\Error\MindeeHttpException; -use Mindee\Input\Base64Input; -use Mindee\Input\BytesInput; -use Mindee\Input\FileInput; +use Mindee\Error\V1\MindeeV1ClientException; +use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\LocalResponse; use Mindee\Input\PageOptions; -use Mindee\Input\PathInput; -use Mindee\Input\UrlInputSource; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\WorkflowOptions; use Mindee\V1\Http\Endpoint; @@ -41,9 +35,6 @@ use Mindee\V1\Product\Generated\GeneratedV1; use ReflectionClass; use ReflectionException; -use SplFileObject; - -use function strlen; /** * Main entrypoint for Mindee operations. @@ -73,78 +64,6 @@ public function __construct(?string $apiKey = null) $this->apiKey = $apiKey ?: getenv('MINDEE_API_KEY'); } - /** - * Load a document from an absolute path, as a string. - * - * @param string $filePath Path of the file. - * @param boolean $fixPdf Whether the PDF should be fixed or not. - */ - public function sourceFromPath(string $filePath, bool $fixPdf = false): PathInput - { - $input = new PathInput($filePath); - if ($fixPdf) { - $input->fixPdf(); - } - return $input; - } - - /** - * Load a document from a normal PHP file object. - * - * @param SplFileObject|CURLFile|string|resource $file File object as created from the file() function. - * @param boolean $fixPdf Whether the PDF should be fixed or not. - */ - public function sourceFromFile(mixed $file, bool $fixPdf = false): FileInput - { - $input = new FileInput($file); - if ($fixPdf) { - $input->fixPdf(); - } - return $input; - } - - /** - * Load a document from raw bytes. - * - * @param string $fileBytes File object in raw bytes. - * @param string $fileName File name, mandatory. - * @param boolean $fixPdf Whether the PDF should be fixed or not. - */ - public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPdf = false): BytesInput - { - $input = new BytesInput($fileBytes, $fileName); - if ($fixPdf) { - $input->fixPdf(); - } - return $input; - } - - /** - * Load a document from a base64 encoded string. - * - * @param string $fileB64 File object in Base64. - * @param string $fileName File name, mandatory. - * @param boolean $fixPdf Whether the PDF should be fixed or not. - */ - public function sourceFromB64String(string $fileB64, string $fileName, bool $fixPdf = false): Base64Input - { - $input = new Base64Input($fileB64, $fileName); - if ($fixPdf) { - $input->fixPdf(); - } - return $input; - } - - /** - * Load a document from an URL. - * - * @param string $url File URL. Must start with "https://". - */ - public function sourceFromUrl(string $url): UrlInputSource - { - return new UrlInputSource($url); - } - /** * Builds a custom endpoint. * @@ -216,12 +135,12 @@ private function constructOTSEndpoint(string $product): 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. + * @throws MindeeV1ClientException Throws if a custom endpoint name isn't provided. */ public function createEndpoint(string $endpointName, string $accountName, ?string $version = null): Endpoint { if (mb_strlen($endpointName, "UTF-8") === 0) { - throw new MindeeClientException( + throw new MindeeV1ClientException( "Custom endpoint requires a valid 'endpoint_name'.", ErrorCode::USER_INPUT_ERROR ); @@ -251,7 +170,7 @@ private function cutDocPages(LocalInputSource $inputDoc, PageOptions $pageOption * @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. + * @throws MindeeV1HttpException Throws if the API sent an error. */ private function makeParseQueuedRequest( string $predictionType, @@ -260,7 +179,7 @@ private function makeParseQueuedRequest( ): AsyncPredictResponse { $queuedResponse = ResponseValidation::cleanRequestData($endpoint->documentQueueReqGet($queueId)); if (!ResponseValidation::isValidAsyncResponse($queuedResponse)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $endpoint->settings->endpointName, $queuedResponse ); @@ -274,7 +193,7 @@ private function makeParseQueuedRequest( * @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 MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ private function makeEnqueueRequest( @@ -299,7 +218,7 @@ private function makeEnqueueRequest( ) ); if (!ResponseValidation::isValidAsyncResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $options->endpoint->settings->endpointName, $response ); @@ -314,7 +233,7 @@ private function makeEnqueueRequest( * @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 MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if the API sent an error, * or if the prediction type isn't recognized or if a field can't be deserialized. */ @@ -341,7 +260,7 @@ private function makeWorkflowExecutionRequest( $options->workflowOptions )); if (!ResponseValidation::isValidWorkflowResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( "workflows/$workflowId/executions", $response ); @@ -363,7 +282,7 @@ private function makeWorkflowExecutionRequest( * @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 MindeeV1HttpException Throws if the API sent an error. * @throws MindeeApiException Throws if one attempts to edit remote resources. */ private function makeParseRequest( @@ -386,7 +305,7 @@ private function makeParseRequest( $options, )); if (!ResponseValidation::isValidSyncResponse($response)) { - throw MindeeHttpException::handleError( + throw MindeeV1HttpException::handleError( $options->endpoint->settings->endpointName, $response ); diff --git a/src/V1/Image/ImageExtractor.php b/src/V1/Image/ImageExtractor.php index 04ae6de3..aa8a88d7 100644 --- a/src/V1/Image/ImageExtractor.php +++ b/src/V1/Image/ImageExtractor.php @@ -4,7 +4,7 @@ namespace Mindee\V1\Image; -use Mindee\Extraction\ImageExtractor as BaseImageExtractor; +use Mindee\Image\ImageExtractor as BaseImageExtractor; /** * Wrapper class for V1 of the BaseImageExtractor. diff --git a/src/V2/Client.php b/src/V2/Client.php index 649bb553..5b0e57d6 100644 --- a/src/V2/Client.php +++ b/src/V2/Client.php @@ -11,8 +11,7 @@ use Mindee\V2\ClientOptions\BaseParameters; use Mindee\V2\Http\MindeeApiV2; use Mindee\V2\Parsing\Inference\BaseResponse; -use Mindee\V2\Parsing\JobResponse; -use Mindee\V2\Product\Extraction\Params\ExtractionParameters; +use Mindee\V2\Parsing\Job\JobResponse; /** * Mindee Client V2. @@ -36,22 +35,6 @@ public function __construct(?string $apiKey = null) $this->mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); } - /** - * Send the document to an asynchronous endpoint and return its ID in the queue. - * - * @param InputSource $inputSource File to parse. - * @param ExtractionParameters $params Parameters relating to prediction options. - * @return JobResponse A JobResponse containing the job (queue) corresponding to a document. - * @throws MindeeException Throws if the input document is not provided. - * @category Asynchronous - */ - public function enqueueInference( - InputSource $inputSource, - ExtractionParameters $params - ): JobResponse { - return $this->enqueue($inputSource, $params); - } - /** * Send the document to an asynchronous endpoint and return its ID in the queue. * @param InputSource $inputSource File to parse. diff --git a/src/V2/FileOperations/Crop.php b/src/V2/FileOperations/Crop.php index 1240d982..2004e009 100644 --- a/src/V2/FileOperations/Crop.php +++ b/src/V2/FileOperations/Crop.php @@ -4,8 +4,8 @@ namespace Mindee\V2\FileOperations; -use Mindee\Extraction\ExtractedImage; -use Mindee\Extraction\ImageExtractor; +use Mindee\Image\ExtractedImage; +use Mindee\Image\ImageExtractor; use Mindee\Input\LocalInputSource; use Mindee\V2\Product\Crop\CropItem; diff --git a/src/V2/FileOperations/CropFiles.php b/src/V2/FileOperations/CropFiles.php index 9f522535..c493a1c9 100644 --- a/src/V2/FileOperations/CropFiles.php +++ b/src/V2/FileOperations/CropFiles.php @@ -4,10 +4,10 @@ namespace Mindee\V2\FileOperations; -use Mindee\Error\MindeeException; -use Mindee\Extraction\ExtractedImage; use ArrayObject; use ImagickException; +use Mindee\Error\MindeeException; +use Mindee\Image\ExtractedImage; use function sprintf; diff --git a/src/V2/FileOperations/Split.php b/src/V2/FileOperations/Split.php index a8a55689..eff71136 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -5,9 +5,9 @@ namespace Mindee\V2\FileOperations; use Mindee\Error\MindeeInputException; -use Mindee\Extraction\ExtractedPdf; -use Mindee\Extraction\PdfExtractor; use Mindee\Input\LocalInputSource; +use Mindee\Pdf\ExtractedPdf; +use Mindee\Pdf\PdfExtractor; /** * V2 Split operation. diff --git a/src/V2/FileOperations/SplitFiles.php b/src/V2/FileOperations/SplitFiles.php index 20a8146c..a8c2b1bd 100644 --- a/src/V2/FileOperations/SplitFiles.php +++ b/src/V2/FileOperations/SplitFiles.php @@ -4,10 +4,10 @@ namespace Mindee\V2\FileOperations; -use Mindee\Error\MindeeException; -use Mindee\Extraction\ExtractedPdf; use ArrayObject; use Exception; +use Mindee\Error\MindeeException; +use Mindee\Pdf\ExtractedPdf; use function sprintf; diff --git a/src/V2/Http/MindeeApiV2.php b/src/V2/Http/MindeeApiV2.php index 34e86328..2d3fbfa1 100644 --- a/src/V2/Http/MindeeApiV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -13,15 +13,15 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeException; -use Mindee\Error\MindeeV2HttpException; -use Mindee\Error\MindeeV2HttpUnknownException; +use Mindee\Error\V2\MindeeV2HttpException; +use Mindee\Error\V2\MindeeV2HttpUnknownException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\UrlInputSource; use Mindee\V2\ClientOptions\BaseParameters; -use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\Error\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; -use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Parsing\Job\JobResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; diff --git a/src/V2/Parsing/ErrorItem.php b/src/V2/Parsing/Error/ErrorItem.php similarity index 94% rename from src/V2/Parsing/ErrorItem.php rename to src/V2/Parsing/Error/ErrorItem.php index 13e0fe52..2c85757d 100644 --- a/src/V2/Parsing/ErrorItem.php +++ b/src/V2/Parsing/Error/ErrorItem.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Error; /** * Explicit details on a problem. diff --git a/src/V2/Parsing/ErrorResponse.php b/src/V2/Parsing/Error/ErrorResponse.php similarity index 97% rename from src/V2/Parsing/ErrorResponse.php rename to src/V2/Parsing/Error/ErrorResponse.php index fd1236f1..9279eb70 100644 --- a/src/V2/Parsing/ErrorResponse.php +++ b/src/V2/Parsing/Error/ErrorResponse.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Error; use function is_array; diff --git a/src/V2/Parsing/BaseInference.php b/src/V2/Parsing/Inference/BaseInference.php similarity index 88% rename from src/V2/Parsing/BaseInference.php rename to src/V2/Parsing/Inference/BaseInference.php index 5d39473a..38844531 100644 --- a/src/V2/Parsing/BaseInference.php +++ b/src/V2/Parsing/Inference/BaseInference.php @@ -2,12 +2,9 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Inference; use Mindee\Parsing\SummaryHelper; -use Mindee\V2\Parsing\Inference\InferenceFile; -use Mindee\V2\Parsing\Inference\InferenceJob; -use Mindee\V2\Parsing\Inference\InferenceModel; use Stringable; /** diff --git a/src/V2/Parsing/Inference/Field/SimpleField.php b/src/V2/Parsing/Inference/Field/SimpleField.php index 1ba0d69d..a63fe087 100644 --- a/src/V2/Parsing/Inference/Field/SimpleField.php +++ b/src/V2/Parsing/Inference/Field/SimpleField.php @@ -32,6 +32,7 @@ public function __construct(array $rawResponse, int $indentLevel = 0) } /** + * @return string String representation. */ public function __toString(): string { @@ -43,4 +44,28 @@ public function __toString(): string } return $this->value !== null ? (string) $this->value : ''; } + + /** + * @return string|null String representation of the field value. + */ + public function getStringValue(): ?string + { + return null !== $this->value ? (string) $this->value : null; + } + + /** + * @return float|null Float representation of the field value. + */ + public function getFloatValue(): ?float + { + return null !== $this->value ? (float) $this->value : null; + } + + /** + * @return boolean|null Boolean representation of the field value. + */ + public function getBoolValue(): ?bool + { + return null !== $this->value ? (bool) $this->value : null; + } } diff --git a/src/V2/Parsing/Job.php b/src/V2/Parsing/Job/Job.php similarity index 97% rename from src/V2/Parsing/Job.php rename to src/V2/Parsing/Job/Job.php index 3957e17f..982853c4 100644 --- a/src/V2/Parsing/Job.php +++ b/src/V2/Parsing/Job/Job.php @@ -2,10 +2,11 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Job; use DateTime; use Exception; +use Mindee\V2\Parsing\Error\ErrorResponse; use function array_key_exists; diff --git a/src/V2/Parsing/JobResponse.php b/src/V2/Parsing/Job/JobResponse.php similarity index 94% rename from src/V2/Parsing/JobResponse.php rename to src/V2/Parsing/Job/JobResponse.php index 21a8fc0d..babc7259 100644 --- a/src/V2/Parsing/JobResponse.php +++ b/src/V2/Parsing/Job/JobResponse.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Job; use Mindee\V2\Parsing\Inference\BaseResponse; diff --git a/src/V2/Parsing/JobWebhook.php b/src/V2/Parsing/Job/JobWebhook.php similarity index 94% rename from src/V2/Parsing/JobWebhook.php rename to src/V2/Parsing/Job/JobWebhook.php index 3205c2ce..e12d5ccf 100644 --- a/src/V2/Parsing/JobWebhook.php +++ b/src/V2/Parsing/Job/JobWebhook.php @@ -2,10 +2,11 @@ declare(strict_types=1); -namespace Mindee\V2\Parsing; +namespace Mindee\V2\Parsing\Job; use DateTime; use Exception; +use Mindee\V2\Parsing\Error\ErrorResponse; /** * JobWebhook information. diff --git a/src/V2/Product/Classification/ClassificationInference.php b/src/V2/Product/Classification/ClassificationInference.php index 3d34cf36..58fefb3a 100644 --- a/src/V2/Product/Classification/ClassificationInference.php +++ b/src/V2/Product/Classification/ClassificationInference.php @@ -5,7 +5,7 @@ namespace Mindee\V2\Product\Classification; use Mindee\Parsing\SummaryHelper; -use Mindee\V2\Parsing\BaseInference; +use Mindee\V2\Parsing\Inference\BaseInference; /** * Classification inference result. diff --git a/src/V2/Product/Crop/CropInference.php b/src/V2/Product/Crop/CropInference.php index b0472c24..d83717be 100644 --- a/src/V2/Product/Crop/CropInference.php +++ b/src/V2/Product/Crop/CropInference.php @@ -4,7 +4,7 @@ namespace Mindee\V2\Product\Crop; -use Mindee\V2\Parsing\BaseInference; +use Mindee\V2\Parsing\Inference\BaseInference; /** * The inference result for a crop utility request. diff --git a/src/V2/Product/Extraction/ExtractionInference.php b/src/V2/Product/Extraction/ExtractionInference.php index 2ef76ce2..bf4b5fb7 100644 --- a/src/V2/Product/Extraction/ExtractionInference.php +++ b/src/V2/Product/Extraction/ExtractionInference.php @@ -5,7 +5,7 @@ namespace Mindee\V2\Product\Extraction; use Mindee\Parsing\SummaryHelper; -use Mindee\V2\Parsing\BaseInference; +use Mindee\V2\Parsing\Inference\BaseInference; use Mindee\V2\Parsing\Inference\InferenceActiveOptions; /** diff --git a/src/V2/Product/Ocr/OcrInference.php b/src/V2/Product/Ocr/OcrInference.php index cfe2fc9d..d5dbaa44 100644 --- a/src/V2/Product/Ocr/OcrInference.php +++ b/src/V2/Product/Ocr/OcrInference.php @@ -4,7 +4,7 @@ namespace Mindee\V2\Product\Ocr; -use Mindee\V2\Parsing\BaseInference; +use Mindee\V2\Parsing\Inference\BaseInference; /** * Response for an Ocr utility inference. diff --git a/src/V2/Product/Split/SplitInference.php b/src/V2/Product/Split/SplitInference.php index bf72acc4..3acdab73 100644 --- a/src/V2/Product/Split/SplitInference.php +++ b/src/V2/Product/Split/SplitInference.php @@ -4,7 +4,7 @@ namespace Mindee\V2\Product\Split; -use Mindee\V2\Parsing\BaseInference; +use Mindee\V2\Parsing\Inference\BaseInference; /** * The inference result for a split utility request. diff --git a/tests/ClientTest.php b/tests/ClientTest.php index f85c1176..262dd542 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -4,10 +4,12 @@ use Mindee\ClientOptions\PollingOptions; use Mindee\Error\MindeeApiException; -use Mindee\Error\MindeeHttpClientException; -use Mindee\Error\MindeeHttpException; +use Mindee\Error\MindeeMimeTypeException; +use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\LocalResponse; use Mindee\Input\PageOptions; +use Mindee\Input\PathInput; +use Mindee\Input\UrlInputSource; use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\Product\Generated\GeneratedV1; @@ -16,7 +18,6 @@ use Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1; use Mindee\V1\Product\Receipt\ReceiptV5; use PHPUnit\Framework\TestCase; -use Mindee\Error\MindeeMimeTypeException; class ClientTest extends TestCase { @@ -52,17 +53,17 @@ protected function tearDown(): void public function testParsePathWithoutToken(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->emptyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->emptyClient->parse(InvoiceV4::class, $inputDoc); } public function testParsePathWithEnvToken(): void { - $this->expectException(MindeeHttpException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->envClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->envClient->parse(InvoiceV4::class, $inputDoc); } @@ -70,25 +71,25 @@ public function testParsePathWithWrongFileType(): void { $this->expectException(MindeeMimeTypeException::class); - $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/receipt.txt"); + new PathInput(TestingUtilities::getFileTypesDir() . "/receipt.txt"); } public function testParsePathWithWrongToken(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); - $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $this->dummyClient->parse(InvoiceV4::class, $inputDoc); } public function testInterfaceVersion(): void { $dummyEndpoint = $this->dummyClient->createEndpoint("dummy", "dummy", "1.1"); - $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); $predictOptions = new PredictMethodOptions(); self::assertSame("1.1", $dummyEndpoint->settings->version); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse( GeneratedV1::class, $inputDoc, @@ -98,8 +99,8 @@ public function testInterfaceVersion(): void public function testCutOptions(): void { - $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); - $this->expectException(MindeeHttpClientException::class); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf"); + $this->expectException(MindeeV1HttpException::class); $pageOptions = new PageOptions(range(0, 4)); $this->dummyClient->parse(ReceiptV5::class, $inputDoc, null, $pageOptions); self::assertSame(5, $inputDoc->getPageCount()); @@ -125,7 +126,7 @@ public function testPredictOptionsWrongInputType(): void self::assertFalse($pageOptions->isEmpty()); $predictOptions = new PredictMethodOptions(); $predictOptions->setPageOptions($pageOptions); - $urlInputSource = $this->dummyClient->sourceFromUrl("https://dummy"); + $urlInputSource = new UrlInputSource("https://dummy"); $this->expectException(MindeeApiException::class); $this->dummyClient->parse(InvoiceV4::class, $urlInputSource, $predictOptions); $this->expectException(MindeeApiException::class); @@ -136,10 +137,10 @@ public function testPredictOptionsValidInputType(): void { $predictOptions = new PredictMethodOptions(); self::assertTrue($predictOptions->pageOptions->isEmpty()); - $inputDoc = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); - $this->expectException(MindeeHttpClientException::class); + $inputDoc = new PathInput(TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf"); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse(InvoiceV4::class, $inputDoc, $predictOptions); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceSplitterV1::class, $inputDoc, $predictOptions); } diff --git a/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php index 89873d95..09431aae 100644 --- a/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php +++ b/tests/Dependencies/DependencyCheckerNoExtendedTestPdf.php @@ -4,16 +4,15 @@ namespace Dependencies; +use Imagick; use Mindee\Error\MindeeUnhandledException; -use Mindee\Extraction\ExtractedImage; -use Mindee\Extraction\ExtractedPdf; -use Mindee\V1\Image\ImageExtractor; -use Mindee\Extraction\PdfExtractor; +use Mindee\Image\ExtractedImage; use Mindee\Input\PathInput; +use Mindee\Pdf\ExtractedPdf; +use Mindee\Pdf\PdfExtractor; +use Mindee\V1\Image\ImageExtractor; use PHPUnit\Framework\TestCase; use TestingUtilities; -use Imagick; -use stdClass; require_once(__DIR__ . "/../TestingUtilities.php"); diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 51637a4a..3a8daa95 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -217,29 +217,32 @@ public function testShouldNotRaiseMimeErrorForBrokenFixablePdf(): void { $this->expectNotToPerformAssertions(); - $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf', true); + $pathInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_fixable.pdf'); + $pathInput->fixPdf(); } public function testShouldRaiseErrorForBrokenUnfixablePdf(): void { $this->expectException(MindeeSourceException::class); - $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf', true); + $pathInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_unfixable.pdf'); + $pathInput->fixPdf(); } public function testShouldSendCorrectResultsForBrokenFixableInvoicePdf(): void { - $sourceDocOriginal = $this->dummyClient->sourceFromPath( + $sourceDocOriginal = new PathInput( TestingUtilities::getV1DataDir() . '/products/invoices/invoice.pdf' ); - $sourceDocFixed = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf', true); + $sourceDocFixed = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/broken_invoice.pdf'); + $sourceDocFixed->fixPdf(); self::assertSame($sourceDocFixed->readContents()[1], $sourceDocOriginal->readContents()[1]); } public function testImageQualityCompressionFromInputSource(): void { - $receiptInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $receiptInput->compress(80); file_put_contents( TestingUtilities::getRootDataDir() . "/output/compress_indirect.jpg", @@ -252,7 +255,7 @@ public function testImageQualityCompressionFromInputSource(): void public function testDirectImageQualityCompression(): void { - $receiptInput = $this->dummyClient->sourceFromPath(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $receiptInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $sizeOriginal = filesize(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); $compresses = [ 100 => ImageCompressor::compress($receiptInput->fileObject, 100), @@ -287,9 +290,9 @@ public function testDirectImageQualityCompression(): void 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'); + $imageInput = new PathInput(TestingUtilities::getFileTypesDir() . '/receipt.jpg'); + $pdfEmptyInput = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); + $pdfSourceText = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/multipage.pdf'); self::assertTrue($pdfSourceText->hasSourceText(), "Source text should be properly detected."); self::assertFalse($pdfEmptyInput->hasSourceText(), "Empty PDFs should not have source text detected."); self::assertFalse($imageInput->hasSourceText(), "An image should not have any text."); @@ -297,7 +300,7 @@ public function testPdfSourceText(): void public function testCompressPdfFromInputSource(): void { - $pdfInput = $this->dummyClient->sourceFromPath( + $pdfInput = new PathInput( TestingUtilities::getFileTypesDir() . "/pdf/not_blank_image_only.pdf" ); self::assertFalse($pdfInput->hasSourceText()); @@ -321,7 +324,7 @@ public function testCompressPdfFromInputSource(): void public function testCompressPdfFromCompressor(): void { - $pdfInput = $this->dummyClient->sourceFromPath( + $pdfInput = new PathInput( TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf' ); $sizeOriginal = filesize(TestingUtilities::getV1DataDir() . '/products/invoice_splitter/default_sample.pdf'); @@ -357,7 +360,7 @@ public function testCompressPdfFromCompressor(): void public function testSourceTextPdfCompression(): void { - $pdfInput = $this->dummyClient->sourceFromPath( + $pdfInput = new PathInput( TestingUtilities::getFileTypesDir() . "/pdf/multipage.pdf" ); diff --git a/tests/Input/UrlInputSourceTest.php b/tests/Input/UrlInputSourceTest.php index 272a9611..c8ce60b5 100644 --- a/tests/Input/UrlInputSourceTest.php +++ b/tests/Input/UrlInputSourceTest.php @@ -29,7 +29,7 @@ protected function tearDown(): void public function testInputFromHttpShouldNotThrow(): void { - $inputDoc = $this->dummyClient->sourceFromUrl("https://example.com/invoice.pdf"); + $inputDoc = new UrlInputSource("https://example.com/invoice.pdf"); self::assertInstanceOf(UrlInputSource::class, $inputDoc); } @@ -42,7 +42,7 @@ public function testInputFromHttpShouldThrow(): void public function testDownloadFileFails(): void { $dummyAddress = "addressthatdoesntworkforcipurposes"; - $urlSource = $this->dummyClient->sourceFromUrl("https://$dummyAddress"); + $urlSource = new UrlInputSource("https://$dummyAddress"); $this->expectException(MindeeSourceException::class); $this->expectExceptionMessage("Failed to download file: Could not resolve host: $dummyAddress"); $urlSource->asLocalInputSource("test.pdf"); @@ -50,7 +50,7 @@ public function testDownloadFileFails(): void public function testInvalidFileName(): void { - $urlSource = $this->dummyClient->sourceFromUrl("https://addressthatdoesntworkforcipurposes"); + $urlSource = new UrlInputSource("https://addressthatdoesntworkforcipurposes"); $this->expectException(MindeeSourceException::class); $this->expectExceptionMessage("Filename must end with an extension."); $urlSource->asLocalInputSource("toto"); diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/CLI/MindeeCLICommandTestFunctional.php index ec066319..f5169c14 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/CLI/MindeeCLICommandTestFunctional.php @@ -9,7 +9,7 @@ require_once(__DIR__ . "/../../TestingUtilities.php"); require_once(__DIR__ . "/MindeeCLITestingUtilities.php"); -use Mindee\CLI\MindeeCLIDocuments; +use Mindee\Cli\MindeeCLIDocuments; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/V1/Error/MindeeHttpExceptionTest.php b/tests/V1/Error/MindeeHttpExceptionTest.php index 16cd1eb7..e5db2bc3 100644 --- a/tests/V1/Error/MindeeHttpExceptionTest.php +++ b/tests/V1/Error/MindeeHttpExceptionTest.php @@ -4,8 +4,7 @@ namespace V1\Error; -use Mindee\Error\MindeeHttpClientException; -use Mindee\Error\MindeeHttpException; +use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\PathInput; use Mindee\V1\Client; use Mindee\V1\Product\Invoice\InvoiceV4; @@ -22,32 +21,32 @@ protected function setUp(): void { $this->errorDir = TestingUtilities::getV1DataDir() . "/errors/"; $this->dummyClient = new Client("dummy-key"); - $this->dummyFile = $this->dummyClient->sourceFromPath( + $this->dummyFile = new PathInput( TestingUtilities::getFileTypesDir() . "/pdf/blank.pdf" ); } public function testHttpClientErrorShouldRaise(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->parse(InvoiceV4::class, $this->dummyFile); } public function testHttpEnqueueClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } public function testHttpParseClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueue(InvoiceV4::class, $this->dummyFile); } public function testHttpEnqueueAndParseClientException(): void { - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); $this->dummyClient->enqueueAndParse(InvoiceV4::class, $this->dummyFile); } @@ -55,12 +54,12 @@ 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); + $error400 = MindeeV1HttpException::handleError("dummy-url", $errorObj); self::assertSame(400, $error400->statusCode); self::assertSame("SomeCode", $error400->apiCode); self::assertSame("Some scary message here", $error400->apiMessage); self::assertNull($error400->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); throw $error400; } @@ -68,12 +67,12 @@ 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); + $error401 = MindeeV1HttpException::handleError("dummy-url", $errorObj); self::assertSame(401, $error401->statusCode); self::assertSame("Unauthorized", $error401->apiCode); self::assertSame("Authorization required", $error401->apiMessage); self::assertSame("Invalid token provided", $error401->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); throw $error401; } @@ -81,12 +80,12 @@ 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); + $error429 = MindeeV1HttpException::handleError("dummy-url", $errorObj); self::assertSame(429, $error429->statusCode); self::assertSame("TooManyRequests", $error429->apiCode); self::assertSame("Too many requests", $error429->apiMessage); self::assertSame("Too Many Requests.", $error429->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); throw $error429; } @@ -94,24 +93,24 @@ 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); + $error500 = MindeeV1HttpException::handleError("dummy-url", $errorObj); self::assertSame(500, $error500->statusCode); self::assertSame("failure", $error500->apiCode); self::assertSame("Inference failed", $error500->apiMessage); self::assertSame("Can not run prediction: ", $error500->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); throw $error500; } public function testHttp500HTMLError(): void { $errorRefContents = file_get_contents($this->errorDir . "error_50x.html"); - $error500 = MindeeHttpException::handleError("dummy-url", ["data" => $errorRefContents, "code" => 500]); + $error500 = MindeeV1HttpException::handleError("dummy-url", ["data" => $errorRefContents, "code" => 500]); self::assertSame(500, $error500->statusCode); self::assertSame("UnknownError", $error500->apiCode); self::assertSame("Server sent back an unexpected reply.", $error500->apiMessage); self::assertSame($errorRefContents, $error500->apiDetails); - $this->expectException(MindeeHttpClientException::class); + $this->expectException(MindeeV1HttpException::class); throw $error500; } } diff --git a/tests/V1/Extraction/ImageExtractorTest.php b/tests/V1/Image/ImageExtractorTest.php similarity index 99% rename from tests/V1/Extraction/ImageExtractorTest.php rename to tests/V1/Image/ImageExtractorTest.php index a2a1e3fc..bdba2ce1 100644 --- a/tests/V1/Extraction/ImageExtractorTest.php +++ b/tests/V1/Image/ImageExtractorTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace V1\Extraction; +namespace V1\Image; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; diff --git a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php similarity index 97% rename from tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php rename to tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php index 5ee29e77..6d52da49 100644 --- a/tests/V1/Extraction/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace V1\Extraction; +namespace V1\Image; -use Mindee\Extraction\PdfExtractor; use Mindee\Input\PathInput; +use Mindee\Pdf\PdfExtractor; use Mindee\V1\Client; use Mindee\V1\Parsing\Common\Document; use Mindee\V1\Product\Invoice\InvoiceV4; diff --git a/tests/V1/Input/UrlInputSourceTestFunctional.php b/tests/V1/Input/UrlInputSourceTestFunctional.php index d95ec9c9..fae63720 100644 --- a/tests/V1/Input/UrlInputSourceTestFunctional.php +++ b/tests/V1/Input/UrlInputSourceTestFunctional.php @@ -4,6 +4,7 @@ namespace V1\Input; +use Mindee\Input\UrlInputSource; use Mindee\V1\Client; use Mindee\V1\Product\Invoice\InvoiceV4; use PHPUnit\Framework\TestCase; @@ -30,7 +31,7 @@ public static function tearDownAfterClass(): void public function testLoadLocalFile(): void { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); + $urlSource = new UrlInputSource($this->referenceFilePath); $localSource = $urlSource->asLocalInputSource(); $result = $this->client->parse(InvoiceV4::class, $localSource); self::assertSame(1, $result->document->nPages); @@ -39,7 +40,7 @@ public function testLoadLocalFile(): void public function testCustomFileName(): void { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); + $urlSource = new UrlInputSource($this->referenceFilePath); $localSource = $urlSource->asLocalInputSource("customName.pdf"); $result = $this->client->parse(InvoiceV4::class, $localSource); self::assertSame(1, $result->document->nPages); @@ -48,14 +49,14 @@ public function testCustomFileName(): void public function testSaveFile(): void { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); + $urlSource = new UrlInputSource($this->referenceFilePath); $urlSource->saveToFile($this->outputFilePath); self::assertFileExists($this->outputFilePath . "blank_1.pdf"); } public function testSaveFileWithFilename(): void { - $urlSource = $this->client->sourceFromUrl($this->referenceFilePath); + $urlSource = new UrlInputSource($this->referenceFilePath); $urlSource->saveToFile($this->outputFilePath, "customFileName.pdf"); self::assertFileExists($this->outputFilePath . "customFileName.pdf"); } diff --git a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php index 60654471..9e6e7301 100644 --- a/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php +++ b/tests/V1/Parsing/Common/Extras/ExtrasIntegrationFunctional.php @@ -4,6 +4,7 @@ namespace V1\Parsing\Common\Extras; +use Mindee\Input\PathInput; use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\PredictOptions; @@ -26,7 +27,7 @@ protected function setUp(): void public function testShouldSendCropperExtra(): void { - $sample = $this->client->sourceFromPath( + $sample = new PathInput( TestingUtilities::getV1DataDir() . "/products/invoices/default_sample.jpg" ); $predictOptions = new PredictOptions(); @@ -42,7 +43,7 @@ public function testShouldSendCropperExtra(): void public function testShouldSendFullTextOcrExtra(): void { - $sample = $this->client->sourceFromPath( + $sample = new PathInput( TestingUtilities::getV1DataDir() . "/products/international_id/default_sample.jpg" ); $predictOptions = new PredictOptions(); diff --git a/tests/V1/Extraction/PdfExtractorTest.php b/tests/V1/Pdf/PdfExtractorTest.php similarity index 98% rename from tests/V1/Extraction/PdfExtractorTest.php rename to tests/V1/Pdf/PdfExtractorTest.php index 9c2d6ef2..f9858b16 100644 --- a/tests/V1/Extraction/PdfExtractorTest.php +++ b/tests/V1/Pdf/PdfExtractorTest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace V1\Extraction; +namespace V1\Pdf; -use Mindee\Extraction\PdfExtractor; use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; +use Mindee\Pdf\PdfExtractor; use Mindee\V1\Client; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; diff --git a/tests/V1/Workflow/WorkflowTestFunctional.php b/tests/V1/Workflow/WorkflowTestFunctional.php index df4ad42d..089b360f 100644 --- a/tests/V1/Workflow/WorkflowTestFunctional.php +++ b/tests/V1/Workflow/WorkflowTestFunctional.php @@ -4,6 +4,7 @@ namespace V1\Workflow; +use Mindee\Input\PathInput; use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\WorkflowOptions; @@ -25,7 +26,7 @@ protected function setUp(): void $this->mindeeClient = new Client(); $this->workflowId = getenv('WORKFLOW_ID') ?: ''; $this->predictionType = FinancialDocumentV1::class; - $this->inputSource = $this->mindeeClient->sourceFromPath( + $this->inputSource = new PathInput( TestingUtilities::getV1DataDir() . "/products/financial_document/default_sample.jpg" ); } diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index 83993d69..ec3cc973 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -10,7 +10,7 @@ use Mindee\Input\PathInput; use Mindee\V2\Client; use Mindee\V2\Http\MindeeApiV2; -use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Parsing\Job\JobResponse; use Mindee\V2\Product\Extraction\ExtractionResponse; use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\MockObject\MockObject; @@ -46,10 +46,10 @@ public function testEnqueuePostAsync(): void $input = new PathInput(TestingUtilities::getFileTypesDir() . '/pdf/blank_1.pdf'); $params = new ExtractionParameters('dummy-model-id', textContext: 'dummy text context'); - $response = $mindeeClient->enqueueInference($input, $params); + $response = $mindeeClient->enqueue($input, $params); self::assertNotNull($response, 'enqueue() must return a response'); - self::assertInstanceOf(JobResponse::class, $response); + self::assertEmpty($response->job->error); } public function testDocumentGetJobAsync(): void @@ -132,7 +132,7 @@ public function testInferenceLoadsLocally(): void 'Model Id mismatch' ); - $supplierName = $loaded->inference->result->fields['supplier_name']->value ?? null; + $supplierName = $loaded->inference->result->fields['supplier_name']->getStringValue(); self::assertSame( 'John Smith', $supplierName, diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index 6c26449e..578ea599 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -4,7 +4,7 @@ namespace V2; -use Mindee\Error\MindeeV2HttpException; +use Mindee\Error\V2\MindeeV2HttpException; use Mindee\Input\PathInput; use Mindee\Input\UrlInputSource; use Mindee\V2\Client; @@ -103,7 +103,7 @@ public function testInvalidUUIDMustThrowError(): void $inferenceParams = new ExtractionParameters('INVALID MODEL ID'); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { self::assertStringStartsWith('422-', $e->errorCode); self::assertNotEmpty($e->title); @@ -118,7 +118,7 @@ public function testUnknownModelMustThrowError(): void $inferenceParams = new ExtractionParameters('fc405e37-4ba4-4d03-aeba-533a8d1f0f21', textContext: 'this is invalid'); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { self::assertStringStartsWith('404-', $e->errorCode); self::assertNotEmpty($e->title); @@ -154,7 +154,7 @@ public function testInvalidWebhookIDsMustThrowError(): void ); try { - $this->mindeeClient->enqueueInference($source, $inferenceParams); + $this->mindeeClient->enqueue($source, $inferenceParams); } catch (MindeeV2HttpException $e) { self::assertStringStartsWith('422-', $e->errorCode); self::assertNotEmpty($e->title); diff --git a/tests/V2/Parsing/ExtractionResponseTest.php b/tests/V2/Parsing/ExtractionResponseTest.php index b06d6522..ad6e85b8 100644 --- a/tests/V2/Parsing/ExtractionResponseTest.php +++ b/tests/V2/Parsing/ExtractionResponseTest.php @@ -6,13 +6,13 @@ use Mindee\Geometry\Point; use Mindee\Input\LocalResponse; -use Mindee\V2\Parsing\ErrorItem; -use Mindee\V2\Parsing\ErrorResponse; +use Mindee\V2\Parsing\Error\ErrorItem; +use Mindee\V2\Parsing\Error\ErrorResponse; use Mindee\V2\Parsing\Inference\Field\FieldConfidence; use Mindee\V2\Parsing\Inference\Field\ListField; use Mindee\V2\Parsing\Inference\Field\ObjectField; use Mindee\V2\Parsing\Inference\Field\SimpleField; -use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Parsing\Job\JobResponse; use Mindee\V2\Product\Extraction\ExtractionResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; @@ -57,6 +57,7 @@ public function testAsyncPredictWhenEmptyMustHaveValidProperties(): void ); $totalAmount = $fields->getSimpleField('total_amount'); self::assertEmpty($totalAmount->value); + self::assertNull($totalAmount->getFloatValue()); self::assertInstanceOf( ListField::class, @@ -119,7 +120,7 @@ public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void $date = $fields->get('date'); self::assertInstanceOf(SimpleField::class, $date); - self::assertSame('2019-11-02', $date->value, "'date' value mismatch"); + self::assertSame('2019-11-02', $date->getStringValue(), "'date' value mismatch"); $taxes = $fields->getListField('taxes'); self::assertNotNull($taxes, "'taxes' field must exist"); @@ -132,7 +133,7 @@ public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void $baseTax = $taxItemObj->fields->get('base'); self::assertInstanceOf(SimpleField::class, $baseTax); - self::assertSame(31.5, $baseTax->value, "'taxes.base' value mismatch"); + self::assertSame(31.5, $baseTax->getFloatValue(), "'taxes.base' value mismatch"); self::assertNotNull((string) $taxes, "'taxes'.__toString() must not be null"); $supplierAddress = $fields->getObjectField('supplier_address'); @@ -142,7 +143,7 @@ public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void $country = $supplierAddress->fields->get('country'); self::assertNotNull($country, "'supplier_address.country' must exist"); self::assertInstanceOf(SimpleField::class, $country); - self::assertSame('USA', $country->value, 'Country mismatch'); + self::assertSame('USA', $country->getStringValue(), 'Country mismatch'); self::assertSame('USA', (string) $country, "'country'.__toString() mismatch"); self::assertNotNull((string) $supplierAddress, "'supplier_address'.__toString() must not be null"); @@ -150,7 +151,7 @@ public function testAsyncPredictWhenCompleteMustExposeAllProperties(): void self::assertInstanceOf(ObjectField::class, $customerAddr); $city = $customerAddr->fields->get('city'); self::assertInstanceOf(SimpleField::class, $city); - self::assertSame('New York', $city->value, 'City mismatch'); + self::assertSame('New York', $city->getStringValue(), 'City mismatch'); self::assertNull($inference->result->options ?? null, 'Options must be null'); } @@ -196,7 +197,7 @@ public function testDeepNestedFieldsMustExposeCorrectTypes(): void self::assertInstanceOf(ObjectField::class, $firstItem); $deepSimple = $firstItem->fields->get('sub_object_object_sub_object_list_simple'); self::assertInstanceOf(SimpleField::class, $deepSimple); - self::assertSame('value_9', $deepSimple->value); + self::assertSame('value_9', $deepSimple->getStringValue()); } /** @@ -212,27 +213,30 @@ public function testStandardFieldTypesMustExposeCorrectTypes(): void $fieldSimpleString = $fields->get('field_simple_string'); self::assertInstanceOf(SimpleField::class, $fieldSimpleString); - self::assertIsString($fieldSimpleString->value); + self::assertIsString($fieldSimpleString->getStringValue()); $fieldSimpleFloat = $fields->get('field_simple_float'); self::assertInstanceOf(SimpleField::class, $fieldSimpleFloat); - self::assertIsFloat($fieldSimpleFloat->value); + self::assertIsFloat($fieldSimpleFloat->getFloatValue()); $fieldSimpleInt = $fields->get('field_simple_int'); self::assertInstanceOf(SimpleField::class, $fieldSimpleInt); - self::assertIsFloat($fieldSimpleInt->value); + self::assertIsFloat($fieldSimpleInt->getFloatValue()); $fieldSimpleZero = $fields->get('field_simple_zero'); self::assertInstanceOf(SimpleField::class, $fieldSimpleZero); - self::assertIsFloat($fieldSimpleZero->value); + self::assertIsFloat($fieldSimpleZero->getFloatValue()); $fieldSimpleBool = $fields->get('field_simple_bool'); self::assertInstanceOf(SimpleField::class, $fieldSimpleBool); - self::assertIsBool($fieldSimpleBool->value); + self::assertIsBool($fieldSimpleBool->getBoolValue()); $fieldSimpleNull = $fields->get('field_simple_null'); self::assertInstanceOf(SimpleField::class, $fieldSimpleNull); self::assertNull($fieldSimpleNull->value); + self::assertNull($fieldSimpleNull->getStringValue()); + self::assertNull($fieldSimpleNull->getFloatValue()); + self::assertNull($fieldSimpleNull->getBoolValue()); $fieldSimpleList = $fields->get('field_simple_list'); self::assertInstanceOf(ListField::class, $fieldSimpleList); @@ -241,11 +245,11 @@ public function testStandardFieldTypesMustExposeCorrectTypes(): void $firstSimpleItem = $simpleItems[0]; self::assertInstanceOf(SimpleField::class, $firstSimpleItem); - self::assertIsString($firstSimpleItem->value); + self::assertIsString($firstSimpleItem->getStringValue()); foreach ($fieldSimpleList->items as $item) { self::assertInstanceOf(SimpleField::class, $item); - self::assertIsString($item->value); + self::assertIsString($item->getStringValue()); } $fieldObject = $fields->get('field_object'); @@ -258,7 +262,7 @@ public function testStandardFieldTypesMustExposeCorrectTypes(): void $subfield1 = $fieldObjectFields->getSimpleField('subfield_1'); self::assertInstanceOf(SimpleField::class, $subfield1); - self::assertIsString($subfield1->value); + self::assertIsString($subfield1->getStringValue()); $fieldObjectList = $fields->get('field_object_list'); self::assertInstanceOf(ListField::class, $fieldObjectList); @@ -270,13 +274,13 @@ public function testStandardFieldTypesMustExposeCorrectTypes(): void $firstObjectSubfield = $firstObjectItem->fields->get('subfield_1'); self::assertInstanceOf(SimpleField::class, $firstObjectSubfield); - self::assertIsString($firstObjectSubfield->value); + self::assertIsString($firstObjectSubfield->getStringValue()); foreach ($fieldObjectList->items as $item) { self::assertInstanceOf(ObjectField::class, $item); $subfield = $item->fields->get('subfield_1'); self::assertInstanceOf(SimpleField::class, $subfield); - self::assertIsString($subfield->value); + self::assertIsString($subfield->getStringValue()); } } diff --git a/tests/V2/Parsing/JobResponseTest.php b/tests/V2/Parsing/JobResponseTest.php index 1bd8e662..9cba008f 100644 --- a/tests/V2/Parsing/JobResponseTest.php +++ b/tests/V2/Parsing/JobResponseTest.php @@ -5,9 +5,9 @@ namespace V2\Parsing; use DateTime; -use Mindee\V2\Parsing\ErrorItem; -use Mindee\V2\Parsing\ErrorResponse; -use Mindee\V2\Parsing\JobResponse; +use Mindee\V2\Parsing\Error\ErrorItem; +use Mindee\V2\Parsing\Error\ErrorResponse; +use Mindee\V2\Parsing\Job\JobResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/resources b/tests/resources index 315efcc3..13093f3a 160000 --- a/tests/resources +++ b/tests/resources @@ -1 +1 @@ -Subproject commit 315efcc302efacfb75a6b101788058658e8c37e4 +Subproject commit 13093f3a48de212ef26889df71199c1a2a9d1478 From a57bd2f3f09b8b2402a7750642f85f540c60c087 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Thu, 28 May 2026 10:01:41 +0200 Subject: [PATCH 07/11] :recycle: :boom: :tumbler_glass: apply more fixes and add whisky (#191) --- .github/workflows/_static-analysis.yml | 8 ------ ...deeCLICommand.php => MindeeCliCommand.php} | 2 +- ...LIDocuments.php => MindeeCliDocuments.php} | 2 +- bin/cli.php | 6 ++--- composer.json | 26 ++++++++++++++----- phpstan.neon | 4 +++ src/V1/Http/BaseApi.php | 2 +- src/V1/Http/BaseEndpoint.php | 2 +- src/V1/Http/MindeeApi.php | 2 +- src/V1/Http/MindeeWorkflowApi.php | 2 +- src/V2/Http/MindeeApiV2.php | 8 +++--- .../MindeeCliCommandTest.php} | 12 ++++----- .../MindeeCliCommandTestFunctional.php} | 14 +++++----- .../MindeeCliTestingUtilities.php} | 4 +-- whisky.json | 11 ++++++++ 15 files changed, 63 insertions(+), 42 deletions(-) rename bin/{MindeeCLICommand.php => MindeeCliCommand.php} (99%) rename bin/{MindeeCLIDocuments.php => MindeeCliDocuments.php} (99%) create mode 100644 phpstan.neon rename tests/V1/{CLI/MindeeCLICommandTest.php => Cli/MindeeCliCommandTest.php} (79%) rename tests/V1/{CLI/MindeeCLICommandTestFunctional.php => Cli/MindeeCliCommandTestFunctional.php} (84%) rename tests/V1/{CLI/MindeeCLITestingUtilities.php => Cli/MindeeCliTestingUtilities.php} (92%) create mode 100644 whisky.json diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index aaadd839..3058f84a 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -34,11 +34,3 @@ jobs: - name: Run lint run: | composer lint - - - name: Run PHPStan - run: | - composer phpstan - - - name: Run Rector - run: | - composer rector:check diff --git a/bin/MindeeCLICommand.php b/bin/MindeeCliCommand.php similarity index 99% rename from bin/MindeeCLICommand.php rename to bin/MindeeCliCommand.php index c2e0636d..3476f4e8 100644 --- a/bin/MindeeCLICommand.php +++ b/bin/MindeeCliCommand.php @@ -33,7 +33,7 @@ /** * Configuration Class for CLI. */ -class MindeeCLICommand extends Command +class MindeeCliCommand extends Command { /** * @var array $documentList Array of document configurations. diff --git a/bin/MindeeCLIDocuments.php b/bin/MindeeCliDocuments.php similarity index 99% rename from bin/MindeeCLIDocuments.php rename to bin/MindeeCliDocuments.php index 5ce217ab..20d72da3 100644 --- a/bin/MindeeCLIDocuments.php +++ b/bin/MindeeCliDocuments.php @@ -34,7 +34,7 @@ /** * Document specifications for CLI usage. */ -class MindeeCLIDocuments +class MindeeCliDocuments { /** * @return array Specifications for each Mindee Document, for CLI usage. diff --git a/bin/cli.php b/bin/cli.php index 859d9766..c64c6ea8 100755 --- a/bin/cli.php +++ b/bin/cli.php @@ -5,14 +5,14 @@ namespace Mindee\Cli; require __DIR__ . '/../vendor/autoload.php'; -require __DIR__ . '/MindeeCLIDocuments.php'; -require __DIR__ . '/MindeeCLICommand.php'; +require __DIR__ . '/MindeeCliDocuments.php'; +require __DIR__ . '/MindeeCliCommand.php'; use Symfony\Component\Console\Application; use Exception; $cli = new Application(); -$mindeeCommand = new MindeeCLICommand(MindeeCLIDocuments::getSpecs()); +$mindeeCommand = new MindeeCliCommand(MindeeCliDocuments::getSpecs()); $cli->add($mindeeCommand); try { $cli->add($mindeeCommand); diff --git a/composer.json b/composer.json index f18cb53b..6cdf6d7e 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,8 @@ "madewithlove/license-checker": "^v1.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-deprecation-rules": "^2.0", - "rector/rector": "^2.4" + "rector/rector": "^2.4", + "projektgopher/whisky": "^0.7.4" }, "suggest": { "ext-imagick": "Required for PDF rasterization and image processing features", @@ -35,10 +36,23 @@ "bin/cli.php" ], "scripts": { - "lint": "php-cs-fixer fix --dry-run --diff", - "phpstan": "phpstan analyse src --level 6", - "format": "php-cs-fixer fix", - "rector": "rector process src tests", - "rector:check": "rector process src tests --dry-run" + "lint:cs-fixer": "php-cs-fixer fix --dry-run --diff", + "lint:rector": "rector process src tests --dry-run", + "lint:phpstan": "phpstan analyse", + "lint": [ + "@lint:phpstan", + "@lint:cs-fixer", + "@lint:rector" + ], + "format:cs-fixer": "php-cs-fixer fix", + "format:rector": "rector process src tests", + "format": [ + "@format:cs-fixer", + "@format:rector" + ], + "test:unit": "phpunit -c tests/phpunit.xml", + "test:functional": "phpunit -c tests/functional.xml", + "test:smoke:v1": "./tests/test_v1_code_samples.sh", + "test:smoke:v2": "./tests/test_v2_code_samples.sh" } } diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..6e451faa --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,4 @@ +parameters: + level: 6 + paths: + - src diff --git a/src/V1/Http/BaseApi.php b/src/V1/Http/BaseApi.php index fafb1b4f..a16a91c8 100644 --- a/src/V1/Http/BaseApi.php +++ b/src/V1/Http/BaseApi.php @@ -21,7 +21,7 @@ /** * Default URL prefix for API calls. */ -const BASE_URL_DEFAULT = 'https://api.mindee.net/v1'; +const BASE_URL_DEFAULT = 'https://api.mindee.net'; /** * Default key name for CURL request timeout in environment variables. diff --git a/src/V1/Http/BaseEndpoint.php b/src/V1/Http/BaseEndpoint.php index 1439f57e..da2b61d6 100644 --- a/src/V1/Http/BaseEndpoint.php +++ b/src/V1/Http/BaseEndpoint.php @@ -64,7 +64,7 @@ public function setFinalCurlOpts( ?string $workflowId = null ): array { if (isset($workflowId)) { - $url = $this->settings->baseUrl . "/workflows/" . $workflowId . $suffix; + $url = $this->settings->baseUrl . "/v1/workflows/" . $workflowId . $suffix; } else { $url = $this->settings->urlRoot . $suffix; } diff --git a/src/V1/Http/MindeeApi.php b/src/V1/Http/MindeeApi.php index af0b7f06..57983b22 100644 --- a/src/V1/Http/MindeeApi.php +++ b/src/V1/Http/MindeeApi.php @@ -58,6 +58,6 @@ public function __construct( $this->urlRoot = rtrim( $this->baseUrl, "/" - ) . "/products/$this->accountName/$this->endpointName/v$this->version"; + ) . "/v1/products/$this->accountName/$this->endpointName/v$this->version"; } } diff --git a/src/V1/Http/MindeeWorkflowApi.php b/src/V1/Http/MindeeWorkflowApi.php index bff07d07..d74f271e 100644 --- a/src/V1/Http/MindeeWorkflowApi.php +++ b/src/V1/Http/MindeeWorkflowApi.php @@ -36,6 +36,6 @@ public function __construct( $this->urlRoot = rtrim( $this->baseUrl, "/" - ) . "/workflows/$this->workflowId/executions"; + ) . "/v1/workflows/$this->workflowId/executions"; } } diff --git a/src/V2/Http/MindeeApiV2.php b/src/V2/Http/MindeeApiV2.php index 2d3fbfa1..4aa728c1 100644 --- a/src/V2/Http/MindeeApiV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -50,7 +50,7 @@ /** * Default URL prefix for API calls. */ -const API_V2_BASE_URL_DEFAULT = 'https://api-v2.mindee.net/v2'; +const API_V2_BASE_URL_DEFAULT = 'https://api-v2.mindee.net'; /** * Default key name for CURL request timeout in environment variables. @@ -241,7 +241,7 @@ private function processJobResponse(array $result): JobResponse */ public function reqGetJob(string $jobId): JobResponse { - $response = $this->sendGetRequest($this->baseUrl . "/jobs/$jobId"); + $response = $this->sendGetRequest($this->baseUrl . "/v2/jobs/$jobId"); return $this->processJobResponse($response); } @@ -268,7 +268,7 @@ public function reqGetResult( $e ); } - $url = $this->baseUrl . "/products/{$slugProperty->getValue()}/results/$resultId"; + $url = $this->baseUrl . "/v2/products/{$slugProperty->getValue()}/results/$resultId"; $response = $this->sendGetRequest($url); return $this->processResponse($responseClass, $response); } @@ -352,7 +352,7 @@ private function documentEnqueuePost( $inputSource->checkNeedsFix(); $postFields['file'] = $inputSource->fileObject; } - $url = $this->baseUrl . "/products/{$params::$slug}/enqueue"; + $url = $this->baseUrl . "/v2/products/{$params::$slug}/enqueue"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); $resp = [ diff --git a/tests/V1/CLI/MindeeCLICommandTest.php b/tests/V1/Cli/MindeeCliCommandTest.php similarity index 79% rename from tests/V1/CLI/MindeeCLICommandTest.php rename to tests/V1/Cli/MindeeCliCommandTest.php index 9d9cde6e..f88b449e 100644 --- a/tests/V1/CLI/MindeeCLICommandTest.php +++ b/tests/V1/Cli/MindeeCliCommandTest.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace V1\CLI; +namespace V1\Cli; use PHPUnit\Framework\TestCase; use TestingUtilities; -require_once(__DIR__ . "/MindeeCLITestingUtilities.php"); +require_once(__DIR__ . "/MindeeCliTestingUtilities.php"); -class MindeeCLICommandTest extends TestCase +class MindeeCliCommandTest extends TestCase { private string $apiKey; private string $filePath; @@ -22,21 +22,21 @@ protected function setUp(): void public function testInvalidFilePath(): void { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); + $cmdOutput = MindeeCliTestingUtilities::executeTest(["financial-document", "invalid-file-path", "-k", $this->apiKey, "-D"]); self::assertSame(1, $cmdOutput["code"]); self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid path or url provided 'invalid-file-path'.")); } public function testInvalidKey(): void { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["financial-document", $this->filePath, "-k", "invalid-key"]); + $cmdOutput = MindeeCliTestingUtilities::executeTest(["financial-document", $this->filePath, "-k", "invalid-key"]); self::assertSame(1, $cmdOutput["code"]); self::assertTrue(str_contains(implode(" ", $cmdOutput["output"]), "Invalid token provided")); } public function testInvalidProduct(): void { - $cmdOutput = MindeeCLITestingUtilities::executeTest(["invalid-product", $this->filePath, "-k", "invalid-key", "-D"]); + $cmdOutput = MindeeCliTestingUtilities::executeTest(["invalid-product", $this->filePath, "-k", "invalid-key", "-D"]); self::assertSame(1, $cmdOutput["code"]); self::assertTrue(str_contains((string) $cmdOutput["output"][0], "Invalid product: invalid-product")); } diff --git a/tests/V1/CLI/MindeeCLICommandTestFunctional.php b/tests/V1/Cli/MindeeCliCommandTestFunctional.php similarity index 84% rename from tests/V1/CLI/MindeeCLICommandTestFunctional.php rename to tests/V1/Cli/MindeeCliCommandTestFunctional.php index f5169c14..59b6de26 100644 --- a/tests/V1/CLI/MindeeCLICommandTestFunctional.php +++ b/tests/V1/Cli/MindeeCliCommandTestFunctional.php @@ -2,18 +2,18 @@ declare(strict_types=1); -namespace V1\CLI; +namespace V1\Cli; require_once(__DIR__ . "/../../../vendor/autoload.php"); -require_once(__DIR__ . "/../../../bin/MindeeCLIDocuments.php"); +require_once(__DIR__ . "/../../../bin/MindeeCliDocuments.php"); require_once(__DIR__ . "/../../TestingUtilities.php"); -require_once(__DIR__ . "/MindeeCLITestingUtilities.php"); +require_once(__DIR__ . "/MindeeCliTestingUtilities.php"); -use Mindee\Cli\MindeeCLIDocuments; +use Mindee\Cli\MindeeCliDocuments; use PHPUnit\Framework\TestCase; use TestingUtilities; -class MindeeCLICommandTestFunctional extends TestCase +class MindeeCliCommandTestFunctional extends TestCase { private string $apiKey; @@ -32,7 +32,7 @@ private function runValidCall($productName, $async = false, $initialArgs = []): if ($async) { $args[] = "-A"; } - return MindeeCLITestingUtilities::executeTest($args); + return MindeeCliTestingUtilities::executeTest($args); } @@ -41,7 +41,7 @@ public static function provideProductCases(): iterable $data = []; $data[] = ["generated", true, ["-a", "mindee", "-e", "invoice_splitter", "-d", "1"]]; /** @phpstan-ignore-next-line */ - foreach (MindeeCLIDocuments::getSpecs() as $productName => $productSpecs) { + foreach (MindeeCliDocuments::getSpecs() as $productName => $productSpecs) { if ($productName !== "custom" && $productName !== "generated") { if ($productSpecs->isSync) { $data[] = [$productName, false]; diff --git a/tests/V1/CLI/MindeeCLITestingUtilities.php b/tests/V1/Cli/MindeeCliTestingUtilities.php similarity index 92% rename from tests/V1/CLI/MindeeCLITestingUtilities.php rename to tests/V1/Cli/MindeeCliTestingUtilities.php index b6247db1..34e8a257 100644 --- a/tests/V1/CLI/MindeeCLITestingUtilities.php +++ b/tests/V1/Cli/MindeeCliTestingUtilities.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace V1\CLI; +namespace V1\Cli; -class MindeeCLITestingUtilities +class MindeeCliTestingUtilities { public static function executeTest($args, $mute = false) { diff --git a/whisky.json b/whisky.json new file mode 100644 index 00000000..a601d98e --- /dev/null +++ b/whisky.json @@ -0,0 +1,11 @@ +{ + "disabled": [], + "hooks": { + "pre-commit": [ + "composer lint" + ], + "pre-push": [ + "composer test:unit" + ] + } +} From 8c733a5f4778baaa883be618c010189fbd3241a6 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Thu, 28 May 2026 14:47:27 +0200 Subject: [PATCH 08/11] :coffin: remove support for unused V1 products (#192) --- bin/MindeeCliDocuments.php | 63 ---- docs/code_samples/bill_of_lading_v1_async.txt | 16 - docs/code_samples/delivery_notes_v1_async.txt | 16 - .../code_samples/energy_bill_fra_v1_async.txt | 16 - .../french_healthcard_v1_async.txt | 16 - docs/code_samples/ind_passport_v1_async.txt | 16 - .../code_samples/nutrition_facts_v1_async.txt | 16 - docs/code_samples/payslip_fra_v3_async.txt | 16 - .../us_healthcare_cards_v1_async.txt | 16 - docs/code_samples/us_mail_v3_async.txt | 16 - .../Product/BillOfLading/BillOfLadingV1.php | 42 --- .../BillOfLading/BillOfLadingV1Carrier.php | 79 ----- .../BillOfLadingV1CarrierItem.php | 104 ------ .../BillOfLadingV1CarrierItems.php | 74 ----- .../BillOfLading/BillOfLadingV1Consignee.php | 85 ----- .../BillOfLading/BillOfLadingV1Document.php | 173 ---------- .../BillOfLadingV1NotifyParty.php | 86 ----- .../BillOfLading/BillOfLadingV1Shipper.php | 86 ----- .../Product/DeliveryNote/DeliveryNoteV1.php | 42 --- .../DeliveryNote/DeliveryNoteV1Document.php | 121 ------- src/V1/Product/Fr/EnergyBill/EnergyBillV1.php | 42 --- .../Fr/EnergyBill/EnergyBillV1Document.php | 212 ------------ .../EnergyBill/EnergyBillV1EnergyConsumer.php | 72 ---- .../EnergyBill/EnergyBillV1EnergySupplier.php | 72 ---- .../Fr/EnergyBill/EnergyBillV1EnergyUsage.php | 119 ------- .../EnergyBill/EnergyBillV1EnergyUsages.php | 78 ----- .../Fr/EnergyBill/EnergyBillV1MeterDetail.php | 79 ----- .../EnergyBill/EnergyBillV1Subscription.php | 104 ------ .../EnergyBill/EnergyBillV1Subscriptions.php | 74 ----- .../EnergyBillV1TaxesAndContribution.php | 104 ------ .../EnergyBillV1TaxesAndContributions.php | 74 ----- src/V1/Product/Fr/HealthCard/HealthCardV1.php | 42 --- .../Fr/HealthCard/HealthCardV1Document.php | 88 ----- src/V1/Product/Fr/Payslip/PayslipV3.php | 42 --- .../Fr/Payslip/PayslipV3BankAccountDetail.php | 79 ----- .../Product/Fr/Payslip/PayslipV3Document.php | 138 -------- .../Product/Fr/Payslip/PayslipV3Employee.php | 107 ------ .../Product/Fr/Payslip/PayslipV3Employer.php | 107 ------ .../Fr/Payslip/PayslipV3Employment.php | 107 ------ .../Fr/Payslip/PayslipV3PaidTimeOff.php | 97 ------ .../Fr/Payslip/PayslipV3PaidTimeOffs.php | 72 ---- .../Product/Fr/Payslip/PayslipV3PayDetail.php | 138 -------- .../Product/Fr/Payslip/PayslipV3PayPeriod.php | 93 ------ .../Fr/Payslip/PayslipV3SalaryDetail.php | 98 ------ .../Fr/Payslip/PayslipV3SalaryDetails.php | 72 ---- .../Ind/IndianPassport/IndianPassportV1.php | 42 --- .../IndianPassportV1Document.php | 313 ------------------ .../NutritionFactsLabelV1.php | 42 --- .../NutritionFactsLabelV1AddedSugar.php | 82 ----- .../NutritionFactsLabelV1Calorie.php | 82 ----- .../NutritionFactsLabelV1Cholesterol.php | 82 ----- .../NutritionFactsLabelV1DietaryFiber.php | 82 ----- .../NutritionFactsLabelV1Document.php | 216 ------------ .../NutritionFactsLabelV1Nutrient.php | 97 ------ .../NutritionFactsLabelV1Nutrients.php | 72 ---- .../NutritionFactsLabelV1Protein.php | 82 ----- .../NutritionFactsLabelV1SaturatedFat.php | 82 ----- .../NutritionFactsLabelV1ServingSize.php | 73 ---- .../NutritionFactsLabelV1Sodium.php | 89 ----- ...NutritionFactsLabelV1TotalCarbohydrate.php | 82 ----- .../NutritionFactsLabelV1TotalFat.php | 82 ----- .../NutritionFactsLabelV1TotalSugar.php | 83 ----- .../NutritionFactsLabelV1TransFat.php | 82 ----- .../Us/HealthcareCard/HealthcareCardV1.php | 42 --- .../HealthcareCard/HealthcareCardV1Copay.php | 74 ----- .../HealthcareCard/HealthcareCardV1Copays.php | 66 ---- .../HealthcareCardV1Document.php | 209 ------------ src/V1/Product/Us/UsMail/UsMailV3.php | 42 --- src/V1/Product/Us/UsMail/UsMailV3Document.php | 102 ------ .../Us/UsMail/UsMailV3RecipientAddress.php | 115 ------- .../Us/UsMail/UsMailV3RecipientAddresses.php | 78 ----- .../Us/UsMail/UsMailV3SenderAddress.php | 93 ------ .../BillOfLading/BillOfLadingV1Test.php | 61 ---- .../DeliveryNote/DeliveryNoteV1Test.php | 46 --- .../Fr/EnergyBill/EnergyBillV1Test.php | 57 ---- .../Fr/HealthCard/HealthCardV1Test.php | 43 --- tests/V1/Product/Fr/Payslip/PayslipV3Test.php | 80 ----- .../IndianPassport/IndianPassportV1Test.php | 60 ---- .../NutritionFactsLabelV1Test.php | 77 ----- .../HealthcareCard/HealthcareCardV1Test.php | 53 --- tests/V1/Product/Us/UsMail/UsMailV3Test.php | 48 --- 81 files changed, 6520 deletions(-) delete mode 100644 docs/code_samples/bill_of_lading_v1_async.txt delete mode 100644 docs/code_samples/delivery_notes_v1_async.txt delete mode 100644 docs/code_samples/energy_bill_fra_v1_async.txt delete mode 100644 docs/code_samples/french_healthcard_v1_async.txt delete mode 100644 docs/code_samples/ind_passport_v1_async.txt delete mode 100644 docs/code_samples/nutrition_facts_v1_async.txt delete mode 100644 docs/code_samples/payslip_fra_v3_async.txt delete mode 100644 docs/code_samples/us_healthcare_cards_v1_async.txt delete mode 100644 docs/code_samples/us_mail_v3_async.txt delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1Document.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php delete mode 100644 src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php delete mode 100644 src/V1/Product/DeliveryNote/DeliveryNoteV1.php delete mode 100644 src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php delete mode 100644 src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php delete mode 100644 src/V1/Product/Fr/HealthCard/HealthCardV1.php delete mode 100644 src/V1/Product/Fr/HealthCard/HealthCardV1Document.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3Document.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3Employee.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3Employer.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3Employment.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php delete mode 100644 src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php delete mode 100644 src/V1/Product/Ind/IndianPassport/IndianPassportV1.php delete mode 100644 src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php delete mode 100644 src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php delete mode 100644 src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php delete mode 100644 src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php delete mode 100644 src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php delete mode 100644 src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php delete mode 100644 src/V1/Product/Us/UsMail/UsMailV3.php delete mode 100644 src/V1/Product/Us/UsMail/UsMailV3Document.php delete mode 100644 src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php delete mode 100644 src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php delete mode 100644 src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php delete mode 100644 tests/V1/Product/BillOfLading/BillOfLadingV1Test.php delete mode 100644 tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php delete mode 100644 tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php delete mode 100644 tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php delete mode 100644 tests/V1/Product/Fr/Payslip/PayslipV3Test.php delete mode 100644 tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php delete mode 100644 tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php delete mode 100644 tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php delete mode 100644 tests/V1/Product/Us/UsMail/UsMailV3Test.php diff --git a/bin/MindeeCliDocuments.php b/bin/MindeeCliDocuments.php index 20d72da3..08550a2c 100644 --- a/bin/MindeeCliDocuments.php +++ b/bin/MindeeCliDocuments.php @@ -5,31 +5,22 @@ namespace Mindee\Cli; use Mindee\V1\Product\BarcodeReader\BarcodeReaderV1; -use Mindee\V1\Product\BillOfLading\BillOfLadingV1; use Mindee\V1\Product\BusinessCard\BusinessCardV1; use Mindee\V1\Product\Cropper\CropperV1; -use Mindee\V1\Product\DeliveryNote\DeliveryNoteV1; use Mindee\V1\Product\DriverLicense\DriverLicenseV1; use Mindee\V1\Product\FinancialDocument\FinancialDocumentV1; use Mindee\V1\Product\Fr\BankAccountDetails\BankAccountDetailsV2; use Mindee\V1\Product\Fr\CarteGrise\CarteGriseV1; -use Mindee\V1\Product\Fr\EnergyBill\EnergyBillV1; -use Mindee\V1\Product\Fr\HealthCard\HealthCardV1; use Mindee\V1\Product\Fr\IdCard\IdCardV2; -use Mindee\V1\Product\Fr\Payslip\PayslipV3; use Mindee\V1\Product\Generated\GeneratedV1; -use Mindee\V1\Product\Ind\IndianPassport\IndianPassportV1; use Mindee\V1\Product\InternationalId\InternationalIdV2; use Mindee\V1\Product\Invoice\InvoiceV4; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use Mindee\V1\Product\MultiReceiptsDetector\MultiReceiptsDetectorV1; -use Mindee\V1\Product\NutritionFactsLabel\NutritionFactsLabelV1; use Mindee\V1\Product\Passport\PassportV1; use Mindee\V1\Product\Receipt\ReceiptV5; use Mindee\V1\Product\Resume\ResumeV1; use Mindee\V1\Product\Us\BankCheck\BankCheckV1; -use Mindee\V1\Product\Us\HealthcareCard\HealthcareCardV1; -use Mindee\V1\Product\Us\UsMail\UsMailV3; /** * Document specifications for CLI usage. @@ -55,12 +46,6 @@ public static function getSpecs(): array true, false ), - "bill-of-lading" => new DocumentCommandConfig( - "Bill of Lading", - BillOfLadingV1::class, - false, - true - ), "business-card" => new DocumentCommandConfig( "Business Card", BusinessCardV1::class, @@ -73,12 +58,6 @@ public static function getSpecs(): array true, false ), - "delivery-note" => new DocumentCommandConfig( - "Delivery note", - DeliveryNoteV1::class, - false, - true - ), "driver-license" => new DocumentCommandConfig( "Driver License", DriverLicenseV1::class, @@ -103,36 +82,12 @@ public static function getSpecs(): array true, false ), - "fr-energy-bill" => new DocumentCommandConfig( - "FR Energy Bill", - EnergyBillV1::class, - false, - true - ), - "fr-health-card" => new DocumentCommandConfig( - "FR Health Card", - HealthCardV1::class, - false, - true - ), "fr-carte-nationale-d-identite" => new DocumentCommandConfig( "FR Carte Nationale d'Identité", IdCardV2::class, true, false ), - "fr-payslip" => new DocumentCommandConfig( - "FR Payslip", - PayslipV3::class, - false, - true - ), - "ind-passport-india" => new DocumentCommandConfig( - "IND Passport - India", - IndianPassportV1::class, - false, - true - ), "international-id" => new DocumentCommandConfig( "International ID", InternationalIdV2::class, @@ -157,12 +112,6 @@ public static function getSpecs(): array true, false ), - "nutrition-facts-label" => new DocumentCommandConfig( - "Nutrition Facts Label", - NutritionFactsLabelV1::class, - false, - true - ), "passport" => new DocumentCommandConfig( "Passport", PassportV1::class, @@ -187,18 +136,6 @@ public static function getSpecs(): array true, false ), - "us-healthcare-card" => new DocumentCommandConfig( - "US Healthcare Card", - HealthcareCardV1::class, - false, - true - ), - "us-us-mail" => new DocumentCommandConfig( - "US US Mail", - UsMailV3::class, - false, - true - ), ]; } } diff --git a/docs/code_samples/bill_of_lading_v1_async.txt b/docs/code_samples/bill_of_lading_v1_async.txt deleted file mode 100644 index b277246d..00000000 --- a/docs/code_samples/bill_of_lading_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(BillOfLadingV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/delivery_notes_v1_async.txt b/docs/code_samples/delivery_notes_v1_async.txt deleted file mode 100644 index d6716398..00000000 --- a/docs/code_samples/delivery_notes_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(DeliveryNoteV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/energy_bill_fra_v1_async.txt b/docs/code_samples/energy_bill_fra_v1_async.txt deleted file mode 100644 index 35d624a6..00000000 --- a/docs/code_samples/energy_bill_fra_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(EnergyBillV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/french_healthcard_v1_async.txt b/docs/code_samples/french_healthcard_v1_async.txt deleted file mode 100644 index 1ee85173..00000000 --- a/docs/code_samples/french_healthcard_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(HealthCardV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/ind_passport_v1_async.txt b/docs/code_samples/ind_passport_v1_async.txt deleted file mode 100644 index 40523afe..00000000 --- a/docs/code_samples/ind_passport_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(IndianPassportV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/nutrition_facts_v1_async.txt b/docs/code_samples/nutrition_facts_v1_async.txt deleted file mode 100644 index 197344e8..00000000 --- a/docs/code_samples/nutrition_facts_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(NutritionFactsLabelV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/payslip_fra_v3_async.txt b/docs/code_samples/payslip_fra_v3_async.txt deleted file mode 100644 index d185d728..00000000 --- a/docs/code_samples/payslip_fra_v3_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(PayslipV3::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/us_healthcare_cards_v1_async.txt b/docs/code_samples/us_healthcare_cards_v1_async.txt deleted file mode 100644 index d0f21100..00000000 --- a/docs/code_samples/us_healthcare_cards_v1_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(HealthcareCardV1::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/docs/code_samples/us_mail_v3_async.txt b/docs/code_samples/us_mail_v3_async.txt deleted file mode 100644 index 442e74a3..00000000 --- a/docs/code_samples/us_mail_v3_async.txt +++ /dev/null @@ -1,16 +0,0 @@ -enqueueAndParse(UsMailV3::class, $inputSource); - -echo $apiResponse->document; \ No newline at end of file diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1.php b/src/V1/Product/BillOfLading/BillOfLadingV1.php deleted file mode 100644 index aadf37d8..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new BillOfLadingV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(BillOfLadingV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php b/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php deleted file mode 100644 index 59e75647..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Carrier.php +++ /dev/null @@ -1,79 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->name = $rawPrediction["name"] ?? null; - $this->professionalNumber = $rawPrediction["professional_number"] ?? null; - $this->scac = $rawPrediction["scac"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["professionalNumber"] = SummaryHelperV1::formatForDisplay($this->professionalNumber); - $outArr["scac"] = SummaryHelperV1::formatForDisplay($this->scac); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Professional Number: " . $printable["professionalNumber"]; - $outStr .= "\n :SCAC: " . $printable["scac"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php deleted file mode 100644 index 2df1d83a..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItem.php +++ /dev/null @@ -1,104 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->grossWeight = isset($rawPrediction["gross_weight"]) - ? (float) ($rawPrediction["gross_weight"]) : null; - $this->measurement = isset($rawPrediction["measurement"]) - ? (float) ($rawPrediction["measurement"]) : null; - $this->measurementUnit = $rawPrediction["measurement_unit"] ?? null; - $this->quantity = isset($rawPrediction["quantity"]) - ? (float) ($rawPrediction["quantity"]) : null; - $this->weightUnit = $rawPrediction["weight_unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); - $outArr["grossWeight"] = SummaryHelperV1::formatFloat($this->grossWeight); - $outArr["measurement"] = SummaryHelperV1::formatFloat($this->measurement); - $outArr["measurementUnit"] = SummaryHelperV1::formatForDisplay($this->measurementUnit); - $outArr["quantity"] = SummaryHelperV1::formatFloat($this->quantity); - $outArr["weightUnit"] = SummaryHelperV1::formatForDisplay($this->weightUnit); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["description"], 36); - $outStr .= SummaryHelperV1::padString($printable["grossWeight"], 12); - $outStr .= SummaryHelperV1::padString($printable["measurement"], 11); - $outStr .= SummaryHelperV1::padString($printable["measurementUnit"], 16); - $outStr .= SummaryHelperV1::padString($printable["quantity"], 8); - $outStr .= SummaryHelperV1::padString($printable["weightUnit"], 11); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php b/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php deleted file mode 100644 index 73d953af..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1CarrierItems.php +++ /dev/null @@ -1,74 +0,0 @@ - - */ -class BillOfLadingV1CarrierItems extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new BillOfLadingV1CarrierItem($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function carrierItemsSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 38); - $outStr .= "+" . str_repeat($char, 14); - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 18); - $outStr .= "+" . str_repeat($char, 10); - $outStr .= "+" . str_repeat($char, 13); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::carrierItemsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::carrierItemsSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | Gross Weight"; - $outStr .= " | Measurement"; - $outStr .= " | Measurement Unit"; - $outStr .= " | Quantity"; - $outStr .= " | Weight Unit"; - $outStr .= " |\n" . self::carrierItemsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php b/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php deleted file mode 100644 index be1fa8ba..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Consignee.php +++ /dev/null @@ -1,85 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php b/src/V1/Product/BillOfLading/BillOfLadingV1Document.php deleted file mode 100644 index 89cbed52..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Document.php +++ /dev/null @@ -1,173 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["bill_of_lading_number"])) { - throw new MindeeUnsetException(); - } - $this->billOfLadingNumber = new StringField( - $rawPrediction["bill_of_lading_number"], - $pageId - ); - if (!isset($rawPrediction["carrier"])) { - throw new MindeeUnsetException(); - } - $this->carrier = new BillOfLadingV1Carrier( - $rawPrediction["carrier"], - $pageId - ); - if (!isset($rawPrediction["carrier_items"])) { - throw new MindeeUnsetException(); - } - $this->carrierItems = new BillOfLadingV1CarrierItems( - $rawPrediction["carrier_items"], - $pageId - ); - if (!isset($rawPrediction["consignee"])) { - throw new MindeeUnsetException(); - } - $this->consignee = new BillOfLadingV1Consignee( - $rawPrediction["consignee"], - $pageId - ); - if (!isset($rawPrediction["date_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->dateOfIssue = new DateField( - $rawPrediction["date_of_issue"], - $pageId - ); - if (!isset($rawPrediction["departure_date"])) { - throw new MindeeUnsetException(); - } - $this->departureDate = new DateField( - $rawPrediction["departure_date"], - $pageId - ); - if (!isset($rawPrediction["notify_party"])) { - throw new MindeeUnsetException(); - } - $this->notifyParty = new BillOfLadingV1NotifyParty( - $rawPrediction["notify_party"], - $pageId - ); - if (!isset($rawPrediction["place_of_delivery"])) { - throw new MindeeUnsetException(); - } - $this->placeOfDelivery = new StringField( - $rawPrediction["place_of_delivery"], - $pageId - ); - if (!isset($rawPrediction["port_of_discharge"])) { - throw new MindeeUnsetException(); - } - $this->portOfDischarge = new StringField( - $rawPrediction["port_of_discharge"], - $pageId - ); - if (!isset($rawPrediction["port_of_loading"])) { - throw new MindeeUnsetException(); - } - $this->portOfLoading = new StringField( - $rawPrediction["port_of_loading"], - $pageId - ); - if (!isset($rawPrediction["shipper"])) { - throw new MindeeUnsetException(); - } - $this->shipper = new BillOfLadingV1Shipper( - $rawPrediction["shipper"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $shipperToFieldList = $this->shipper->toFieldList(); - $consigneeToFieldList = $this->consignee->toFieldList(); - $notifyPartyToFieldList = $this->notifyParty->toFieldList(); - $carrierToFieldList = $this->carrier->toFieldList(); - $carrierItemsSummary = (string) ($this->carrierItems); - - $outStr = ":Bill of Lading Number: $this->billOfLadingNumber -:Shipper: $shipperToFieldList -:Consignee: $consigneeToFieldList -:Notify Party: $notifyPartyToFieldList -:Carrier: $carrierToFieldList -:Items: $carrierItemsSummary -:Port of Loading: $this->portOfLoading -:Port of Discharge: $this->portOfDischarge -:Place of Delivery: $this->placeOfDelivery -:Date of issue: $this->dateOfIssue -:Departure Date: $this->departureDate -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php b/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php deleted file mode 100644 index d27b5bf4..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1NotifyParty.php +++ /dev/null @@ -1,86 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php b/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php deleted file mode 100644 index a893209b..00000000 --- a/src/V1/Product/BillOfLading/BillOfLadingV1Shipper.php +++ /dev/null @@ -1,86 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->email = $rawPrediction["email"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phone = $rawPrediction["phone"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["email"] = SummaryHelperV1::formatForDisplay($this->email); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phone"] = SummaryHelperV1::formatForDisplay($this->phone); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Email: " . $printable["email"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone: " . $printable["phone"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1.php deleted file mode 100644 index a25d325a..00000000 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new DeliveryNoteV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(DeliveryNoteV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php b/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php deleted file mode 100644 index f8c8d78c..00000000 --- a/src/V1/Product/DeliveryNote/DeliveryNoteV1Document.php +++ /dev/null @@ -1,121 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["customer_address"])) { - throw new MindeeUnsetException(); - } - $this->customerAddress = new StringField( - $rawPrediction["customer_address"], - $pageId - ); - if (!isset($rawPrediction["customer_name"])) { - throw new MindeeUnsetException(); - } - $this->customerName = new StringField( - $rawPrediction["customer_name"], - $pageId - ); - if (!isset($rawPrediction["delivery_date"])) { - throw new MindeeUnsetException(); - } - $this->deliveryDate = new DateField( - $rawPrediction["delivery_date"], - $pageId - ); - if (!isset($rawPrediction["delivery_number"])) { - throw new MindeeUnsetException(); - } - $this->deliveryNumber = new StringField( - $rawPrediction["delivery_number"], - $pageId - ); - if (!isset($rawPrediction["supplier_address"])) { - throw new MindeeUnsetException(); - } - $this->supplierAddress = new StringField( - $rawPrediction["supplier_address"], - $pageId - ); - if (!isset($rawPrediction["supplier_name"])) { - throw new MindeeUnsetException(); - } - $this->supplierName = new StringField( - $rawPrediction["supplier_name"], - $pageId - ); - if (!isset($rawPrediction["total_amount"])) { - throw new MindeeUnsetException(); - } - $this->totalAmount = new AmountField( - $rawPrediction["total_amount"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - - $outStr = ":Delivery Date: $this->deliveryDate -:Delivery Number: $this->deliveryNumber -:Supplier Name: $this->supplierName -:Supplier Address: $this->supplierAddress -:Customer Name: $this->customerName -:Customer Address: $this->customerAddress -:Total Amount: $this->totalAmount -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php deleted file mode 100644 index dce12ef9..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new EnergyBillV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(EnergyBillV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php deleted file mode 100644 index d1c7cbd2..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Document.php +++ /dev/null @@ -1,212 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["contract_id"])) { - throw new MindeeUnsetException(); - } - $this->contractId = new StringField( - $rawPrediction["contract_id"], - $pageId - ); - if (!isset($rawPrediction["delivery_point"])) { - throw new MindeeUnsetException(); - } - $this->deliveryPoint = new StringField( - $rawPrediction["delivery_point"], - $pageId - ); - if (!isset($rawPrediction["due_date"])) { - throw new MindeeUnsetException(); - } - $this->dueDate = new DateField( - $rawPrediction["due_date"], - $pageId - ); - if (!isset($rawPrediction["energy_consumer"])) { - throw new MindeeUnsetException(); - } - $this->energyConsumer = new EnergyBillV1EnergyConsumer( - $rawPrediction["energy_consumer"], - $pageId - ); - if (!isset($rawPrediction["energy_supplier"])) { - throw new MindeeUnsetException(); - } - $this->energySupplier = new EnergyBillV1EnergySupplier( - $rawPrediction["energy_supplier"], - $pageId - ); - if (!isset($rawPrediction["energy_usage"])) { - throw new MindeeUnsetException(); - } - $this->energyUsage = new EnergyBillV1EnergyUsages( - $rawPrediction["energy_usage"], - $pageId - ); - if (!isset($rawPrediction["invoice_date"])) { - throw new MindeeUnsetException(); - } - $this->invoiceDate = new DateField( - $rawPrediction["invoice_date"], - $pageId - ); - if (!isset($rawPrediction["invoice_number"])) { - throw new MindeeUnsetException(); - } - $this->invoiceNumber = new StringField( - $rawPrediction["invoice_number"], - $pageId - ); - if (!isset($rawPrediction["meter_details"])) { - throw new MindeeUnsetException(); - } - $this->meterDetails = new EnergyBillV1MeterDetail( - $rawPrediction["meter_details"], - $pageId - ); - if (!isset($rawPrediction["subscription"])) { - throw new MindeeUnsetException(); - } - $this->subscription = new EnergyBillV1Subscriptions( - $rawPrediction["subscription"], - $pageId - ); - if (!isset($rawPrediction["taxes_and_contributions"])) { - throw new MindeeUnsetException(); - } - $this->taxesAndContributions = new EnergyBillV1TaxesAndContributions( - $rawPrediction["taxes_and_contributions"], - $pageId - ); - if (!isset($rawPrediction["total_amount"])) { - throw new MindeeUnsetException(); - } - $this->totalAmount = new AmountField( - $rawPrediction["total_amount"], - $pageId - ); - if (!isset($rawPrediction["total_before_taxes"])) { - throw new MindeeUnsetException(); - } - $this->totalBeforeTaxes = new AmountField( - $rawPrediction["total_before_taxes"], - $pageId - ); - if (!isset($rawPrediction["total_taxes"])) { - throw new MindeeUnsetException(); - } - $this->totalTaxes = new AmountField( - $rawPrediction["total_taxes"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $energySupplierToFieldList = $this->energySupplier->toFieldList(); - $energyConsumerToFieldList = $this->energyConsumer->toFieldList(); - $subscriptionSummary = (string) ($this->subscription); - $energyUsageSummary = (string) ($this->energyUsage); - $taxesAndContributionsSummary = (string) ($this->taxesAndContributions); - $meterDetailsToFieldList = $this->meterDetails->toFieldList(); - - $outStr = ":Invoice Number: $this->invoiceNumber -:Contract ID: $this->contractId -:Delivery Point: $this->deliveryPoint -:Invoice Date: $this->invoiceDate -:Due Date: $this->dueDate -:Total Before Taxes: $this->totalBeforeTaxes -:Total Taxes: $this->totalTaxes -:Total Amount: $this->totalAmount -:Energy Supplier: $energySupplierToFieldList -:Energy Consumer: $energyConsumerToFieldList -:Subscription: $subscriptionSummary -:Energy Usage: $energyUsageSummary -:Taxes and Contributions: $taxesAndContributionsSummary -:Meter Details: $meterDetailsToFieldList -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php deleted file mode 100644 index 7d4edd8b..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyConsumer.php +++ /dev/null @@ -1,72 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Name: " . $printable["name"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php deleted file mode 100644 index fbd394a3..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergySupplier.php +++ /dev/null @@ -1,72 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Name: " . $printable["name"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php deleted file mode 100644 index 8587380c..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsage.php +++ /dev/null @@ -1,119 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->consumption = isset($rawPrediction["consumption"]) - ? (float) ($rawPrediction["consumption"]) : null; - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) - ? (float) ($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) - ? (float) ($rawPrediction["total"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - $this->unitPrice = isset($rawPrediction["unit_price"]) - ? (float) ($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["consumption"] = SummaryHelperV1::formatFloat($this->consumption); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["consumption"], 11); - $outStr .= SummaryHelperV1::padString($printable["description"], 36); - $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); - $outStr .= SummaryHelperV1::padString($printable["total"], 9); - $outStr .= SummaryHelperV1::padString($printable["unit"], 15); - $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php deleted file mode 100644 index 9dc7dbfe..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1EnergyUsages.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -class EnergyBillV1EnergyUsages extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new EnergyBillV1EnergyUsage($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function energyUsageSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 38); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 10); - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 17); - $outStr .= "+" . str_repeat($char, 12); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::energyUsageSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::energyUsageSeparator('-') . "\n "; - $outStr .= " | Consumption"; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit of Measure"; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::energyUsageSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php deleted file mode 100644 index 00dd1112..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1MeterDetail.php +++ /dev/null @@ -1,79 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->meterNumber = $rawPrediction["meter_number"] ?? null; - $this->meterType = $rawPrediction["meter_type"] ?? null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["meterNumber"] = SummaryHelperV1::formatForDisplay($this->meterNumber); - $outArr["meterType"] = SummaryHelperV1::formatForDisplay($this->meterType); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Meter Number: " . $printable["meterNumber"]; - $outStr .= "\n :Meter Type: " . $printable["meterType"]; - $outStr .= "\n :Unit of Power: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php deleted file mode 100644 index aa106d59..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscription.php +++ /dev/null @@ -1,104 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) - ? (float) ($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) - ? (float) ($rawPrediction["total"]) : null; - $this->unitPrice = isset($rawPrediction["unit_price"]) - ? (float) ($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["description"], 36); - $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); - $outStr .= SummaryHelperV1::padString($printable["total"], 9); - $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php deleted file mode 100644 index 040ca44e..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1Subscriptions.php +++ /dev/null @@ -1,74 +0,0 @@ - - */ -class EnergyBillV1Subscriptions extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new EnergyBillV1Subscription($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function subscriptionSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 38); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 10); - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 12); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::subscriptionSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::subscriptionSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::subscriptionSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php deleted file mode 100644 index b7119cbe..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContribution.php +++ /dev/null @@ -1,104 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->description = $rawPrediction["description"] ?? null; - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->taxRate = isset($rawPrediction["tax_rate"]) - ? (float) ($rawPrediction["tax_rate"]) : null; - $this->total = isset($rawPrediction["total"]) - ? (float) ($rawPrediction["total"]) : null; - $this->unitPrice = isset($rawPrediction["unit_price"]) - ? (float) ($rawPrediction["unit_price"]) : null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate, 10); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["taxRate"] = SummaryHelperV1::formatFloat($this->taxRate); - $outArr["total"] = SummaryHelperV1::formatFloat($this->total); - $outArr["unitPrice"] = SummaryHelperV1::formatFloat($this->unitPrice); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["description"], 36); - $outStr .= SummaryHelperV1::padString($printable["endDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["startDate"], 10); - $outStr .= SummaryHelperV1::padString($printable["taxRate"], 8); - $outStr .= SummaryHelperV1::padString($printable["total"], 9); - $outStr .= SummaryHelperV1::padString($printable["unitPrice"], 10); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php b/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php deleted file mode 100644 index 4604115a..00000000 --- a/src/V1/Product/Fr/EnergyBill/EnergyBillV1TaxesAndContributions.php +++ /dev/null @@ -1,74 +0,0 @@ - - */ -class EnergyBillV1TaxesAndContributions extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new EnergyBillV1TaxesAndContribution($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function taxesAndContributionsSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 38); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 12); - $outStr .= "+" . str_repeat($char, 10); - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 12); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::taxesAndContributionsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::taxesAndContributionsSeparator('-') . "\n "; - $outStr .= " | Description "; - $outStr .= " | End Date "; - $outStr .= " | Start Date"; - $outStr .= " | Tax Rate"; - $outStr .= " | Total "; - $outStr .= " | Unit Price"; - $outStr .= " |\n" . self::taxesAndContributionsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1.php b/src/V1/Product/Fr/HealthCard/HealthCardV1.php deleted file mode 100644 index c4cfa24d..00000000 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new HealthCardV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(HealthCardV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php b/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php deleted file mode 100644 index 94fbb8e2..00000000 --- a/src/V1/Product/Fr/HealthCard/HealthCardV1Document.php +++ /dev/null @@ -1,88 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["given_names"])) { - throw new MindeeUnsetException(); - } - $this->givenNames = array_map( - static fn($prediction) => new StringField($prediction, $pageId), - $rawPrediction["given_names"] - ); - if (!isset($rawPrediction["issuance_date"])) { - throw new MindeeUnsetException(); - } - $this->issuanceDate = new DateField( - $rawPrediction["issuance_date"], - $pageId - ); - if (!isset($rawPrediction["social_security"])) { - throw new MindeeUnsetException(); - } - $this->socialSecurity = new StringField( - $rawPrediction["social_security"], - $pageId - ); - if (!isset($rawPrediction["surname"])) { - throw new MindeeUnsetException(); - } - $this->surname = new StringField( - $rawPrediction["surname"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $givenNames = implode( - "\n ", - $this->givenNames - ); - - $outStr = ":Given Name(s): $givenNames -:Surname: $this->surname -:Social Security Number: $this->socialSecurity -:Issuance Date: $this->issuanceDate -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3.php b/src/V1/Product/Fr/Payslip/PayslipV3.php deleted file mode 100644 index 643cd7b2..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new PayslipV3Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(PayslipV3Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php deleted file mode 100644 index ead83953..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3BankAccountDetail.php +++ /dev/null @@ -1,79 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->bankName = $rawPrediction["bank_name"] ?? null; - $this->iban = $rawPrediction["iban"] ?? null; - $this->swift = $rawPrediction["swift"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["bankName"] = SummaryHelperV1::formatForDisplay($this->bankName); - $outArr["iban"] = SummaryHelperV1::formatForDisplay($this->iban); - $outArr["swift"] = SummaryHelperV1::formatForDisplay($this->swift); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Bank Name: " . $printable["bankName"]; - $outStr .= "\n :IBAN: " . $printable["iban"]; - $outStr .= "\n :SWIFT: " . $printable["swift"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Document.php b/src/V1/Product/Fr/Payslip/PayslipV3Document.php deleted file mode 100644 index aee6b047..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3Document.php +++ /dev/null @@ -1,138 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["bank_account_details"])) { - throw new MindeeUnsetException(); - } - $this->bankAccountDetails = new PayslipV3BankAccountDetail( - $rawPrediction["bank_account_details"], - $pageId - ); - if (!isset($rawPrediction["employee"])) { - throw new MindeeUnsetException(); - } - $this->employee = new PayslipV3Employee( - $rawPrediction["employee"], - $pageId - ); - if (!isset($rawPrediction["employer"])) { - throw new MindeeUnsetException(); - } - $this->employer = new PayslipV3Employer( - $rawPrediction["employer"], - $pageId - ); - if (!isset($rawPrediction["employment"])) { - throw new MindeeUnsetException(); - } - $this->employment = new PayslipV3Employment( - $rawPrediction["employment"], - $pageId - ); - if (!isset($rawPrediction["paid_time_off"])) { - throw new MindeeUnsetException(); - } - $this->paidTimeOff = new PayslipV3PaidTimeOffs( - $rawPrediction["paid_time_off"], - $pageId - ); - if (!isset($rawPrediction["pay_detail"])) { - throw new MindeeUnsetException(); - } - $this->payDetail = new PayslipV3PayDetail( - $rawPrediction["pay_detail"], - $pageId - ); - if (!isset($rawPrediction["pay_period"])) { - throw new MindeeUnsetException(); - } - $this->payPeriod = new PayslipV3PayPeriod( - $rawPrediction["pay_period"], - $pageId - ); - if (!isset($rawPrediction["salary_details"])) { - throw new MindeeUnsetException(); - } - $this->salaryDetails = new PayslipV3SalaryDetails( - $rawPrediction["salary_details"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $payPeriodToFieldList = $this->payPeriod->toFieldList(); - $employeeToFieldList = $this->employee->toFieldList(); - $employerToFieldList = $this->employer->toFieldList(); - $bankAccountDetailsToFieldList = $this->bankAccountDetails->toFieldList(); - $employmentToFieldList = $this->employment->toFieldList(); - $salaryDetailsSummary = (string) ($this->salaryDetails); - $payDetailToFieldList = $this->payDetail->toFieldList(); - $paidTimeOffSummary = (string) ($this->paidTimeOff); - - $outStr = ":Pay Period: $payPeriodToFieldList -:Employee: $employeeToFieldList -:Employer: $employerToFieldList -:Bank Account Details: $bankAccountDetailsToFieldList -:Employment: $employmentToFieldList -:Salary Details: $salaryDetailsSummary -:Pay Detail: $payDetailToFieldList -:Paid Time Off: $paidTimeOffSummary -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php b/src/V1/Product/Fr/Payslip/PayslipV3Employee.php deleted file mode 100644 index 2cc9ae3b..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employee.php +++ /dev/null @@ -1,107 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->dateOfBirth = $rawPrediction["date_of_birth"] ?? null; - $this->firstName = $rawPrediction["first_name"] ?? null; - $this->lastName = $rawPrediction["last_name"] ?? null; - $this->phoneNumber = $rawPrediction["phone_number"] ?? null; - $this->registrationNumber = $rawPrediction["registration_number"] ?? null; - $this->socialSecurityNumber = $rawPrediction["social_security_number"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["dateOfBirth"] = SummaryHelperV1::formatForDisplay($this->dateOfBirth); - $outArr["firstName"] = SummaryHelperV1::formatForDisplay($this->firstName); - $outArr["lastName"] = SummaryHelperV1::formatForDisplay($this->lastName); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["registrationNumber"] = SummaryHelperV1::formatForDisplay($this->registrationNumber); - $outArr["socialSecurityNumber"] = SummaryHelperV1::formatForDisplay($this->socialSecurityNumber); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Date of Birth: " . $printable["dateOfBirth"]; - $outStr .= "\n :First Name: " . $printable["firstName"]; - $outStr .= "\n :Last Name: " . $printable["lastName"]; - $outStr .= "\n :Phone Number: " . $printable["phoneNumber"]; - $outStr .= "\n :Registration Number: " . $printable["registrationNumber"]; - $outStr .= "\n :Social Security Number: " . $printable["socialSecurityNumber"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php b/src/V1/Product/Fr/Payslip/PayslipV3Employer.php deleted file mode 100644 index 9b34639e..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employer.php +++ /dev/null @@ -1,107 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->address = $rawPrediction["address"] ?? null; - $this->companyId = $rawPrediction["company_id"] ?? null; - $this->companySite = $rawPrediction["company_site"] ?? null; - $this->nafCode = $rawPrediction["naf_code"] ?? null; - $this->name = $rawPrediction["name"] ?? null; - $this->phoneNumber = $rawPrediction["phone_number"] ?? null; - $this->urssafNumber = $rawPrediction["urssaf_number"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["address"] = SummaryHelperV1::formatForDisplay($this->address); - $outArr["companyId"] = SummaryHelperV1::formatForDisplay($this->companyId); - $outArr["companySite"] = SummaryHelperV1::formatForDisplay($this->companySite); - $outArr["nafCode"] = SummaryHelperV1::formatForDisplay($this->nafCode); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name); - $outArr["phoneNumber"] = SummaryHelperV1::formatForDisplay($this->phoneNumber); - $outArr["urssafNumber"] = SummaryHelperV1::formatForDisplay($this->urssafNumber); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Address: " . $printable["address"]; - $outStr .= "\n :Company ID: " . $printable["companyId"]; - $outStr .= "\n :Company Site: " . $printable["companySite"]; - $outStr .= "\n :NAF Code: " . $printable["nafCode"]; - $outStr .= "\n :Name: " . $printable["name"]; - $outStr .= "\n :Phone Number: " . $printable["phoneNumber"]; - $outStr .= "\n :URSSAF Number: " . $printable["urssafNumber"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php b/src/V1/Product/Fr/Payslip/PayslipV3Employment.php deleted file mode 100644 index 27390d5f..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3Employment.php +++ /dev/null @@ -1,107 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->category = $rawPrediction["category"] ?? null; - $this->coefficient = $rawPrediction["coefficient"] ?? null; - $this->collectiveAgreement = $rawPrediction["collective_agreement"] ?? null; - $this->jobTitle = $rawPrediction["job_title"] ?? null; - $this->positionLevel = $rawPrediction["position_level"] ?? null; - $this->seniorityDate = $rawPrediction["seniority_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["category"] = SummaryHelperV1::formatForDisplay($this->category); - $outArr["coefficient"] = SummaryHelperV1::formatForDisplay($this->coefficient); - $outArr["collectiveAgreement"] = SummaryHelperV1::formatForDisplay($this->collectiveAgreement); - $outArr["jobTitle"] = SummaryHelperV1::formatForDisplay($this->jobTitle); - $outArr["positionLevel"] = SummaryHelperV1::formatForDisplay($this->positionLevel); - $outArr["seniorityDate"] = SummaryHelperV1::formatForDisplay($this->seniorityDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Category: " . $printable["category"]; - $outStr .= "\n :Coefficient: " . $printable["coefficient"]; - $outStr .= "\n :Collective Agreement: " . $printable["collectiveAgreement"]; - $outStr .= "\n :Job Title: " . $printable["jobTitle"]; - $outStr .= "\n :Position Level: " . $printable["positionLevel"]; - $outStr .= "\n :Seniority Date: " . $printable["seniorityDate"]; - $outStr .= "\n :Start Date: " . $printable["startDate"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php deleted file mode 100644 index fa691052..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOff.php +++ /dev/null @@ -1,97 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->accrued = isset($rawPrediction["accrued"]) - ? (float) ($rawPrediction["accrued"]) : null; - $this->period = $rawPrediction["period"] ?? null; - $this->ptoType = $rawPrediction["pto_type"] ?? null; - $this->remaining = isset($rawPrediction["remaining"]) - ? (float) ($rawPrediction["remaining"]) : null; - $this->used = isset($rawPrediction["used"]) - ? (float) ($rawPrediction["used"]) : null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["accrued"] = SummaryHelperV1::formatFloat($this->accrued); - $outArr["period"] = SummaryHelperV1::formatForDisplay($this->period, 6); - $outArr["ptoType"] = SummaryHelperV1::formatForDisplay($this->ptoType, 11); - $outArr["remaining"] = SummaryHelperV1::formatFloat($this->remaining); - $outArr["used"] = SummaryHelperV1::formatFloat($this->used); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["accrued"], 9); - $outStr .= SummaryHelperV1::padString($printable["period"], 6); - $outStr .= SummaryHelperV1::padString($printable["ptoType"], 11); - $outStr .= SummaryHelperV1::padString($printable["remaining"], 9); - $outStr .= SummaryHelperV1::padString($printable["used"], 9); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php b/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php deleted file mode 100644 index 8fc8dc9c..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3PaidTimeOffs.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class PayslipV3PaidTimeOffs extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new PayslipV3PaidTimeOff($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function paidTimeOffSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 8); - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 11); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::paidTimeOffSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::paidTimeOffSeparator('-') . "\n "; - $outStr .= " | Accrued "; - $outStr .= " | Period"; - $outStr .= " | Type "; - $outStr .= " | Remaining"; - $outStr .= " | Used "; - $outStr .= " |\n" . self::paidTimeOffSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php deleted file mode 100644 index 795781da..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayDetail.php +++ /dev/null @@ -1,138 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["grossSalary"] = SummaryHelperV1::formatFloat($this->grossSalary); - $outArr["grossSalaryYtd"] = SummaryHelperV1::formatFloat($this->grossSalaryYtd); - $outArr["incomeTaxRate"] = SummaryHelperV1::formatFloat($this->incomeTaxRate); - $outArr["incomeTaxWithheld"] = SummaryHelperV1::formatFloat($this->incomeTaxWithheld); - $outArr["netPaid"] = SummaryHelperV1::formatFloat($this->netPaid); - $outArr["netPaidBeforeTax"] = SummaryHelperV1::formatFloat($this->netPaidBeforeTax); - $outArr["netTaxable"] = SummaryHelperV1::formatFloat($this->netTaxable); - $outArr["netTaxableYtd"] = SummaryHelperV1::formatFloat($this->netTaxableYtd); - $outArr["totalCostEmployer"] = SummaryHelperV1::formatFloat($this->totalCostEmployer); - $outArr["totalTaxesAndDeductions"] = SummaryHelperV1::formatFloat($this->totalTaxesAndDeductions); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Gross Salary: " . $printable["grossSalary"]; - $outStr .= "\n :Gross Salary YTD: " . $printable["grossSalaryYtd"]; - $outStr .= "\n :Income Tax Rate: " . $printable["incomeTaxRate"]; - $outStr .= "\n :Income Tax Withheld: " . $printable["incomeTaxWithheld"]; - $outStr .= "\n :Net Paid: " . $printable["netPaid"]; - $outStr .= "\n :Net Paid Before Tax: " . $printable["netPaidBeforeTax"]; - $outStr .= "\n :Net Taxable: " . $printable["netTaxable"]; - $outStr .= "\n :Net Taxable YTD: " . $printable["netTaxableYtd"]; - $outStr .= "\n :Total Cost Employer: " . $printable["totalCostEmployer"]; - $outStr .= "\n :Total Taxes and Deductions: " . $printable["totalTaxesAndDeductions"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php b/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php deleted file mode 100644 index a3550b72..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3PayPeriod.php +++ /dev/null @@ -1,93 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->endDate = $rawPrediction["end_date"] ?? null; - $this->month = $rawPrediction["month"] ?? null; - $this->paymentDate = $rawPrediction["payment_date"] ?? null; - $this->startDate = $rawPrediction["start_date"] ?? null; - $this->year = $rawPrediction["year"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["endDate"] = SummaryHelperV1::formatForDisplay($this->endDate); - $outArr["month"] = SummaryHelperV1::formatForDisplay($this->month); - $outArr["paymentDate"] = SummaryHelperV1::formatForDisplay($this->paymentDate); - $outArr["startDate"] = SummaryHelperV1::formatForDisplay($this->startDate); - $outArr["year"] = SummaryHelperV1::formatForDisplay($this->year); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :End Date: " . $printable["endDate"]; - $outStr .= "\n :Month: " . $printable["month"]; - $outStr .= "\n :Payment Date: " . $printable["paymentDate"]; - $outStr .= "\n :Start Date: " . $printable["startDate"]; - $outStr .= "\n :Year: " . $printable["year"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php deleted file mode 100644 index 8705c39d..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetail.php +++ /dev/null @@ -1,98 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) - ? (float) ($rawPrediction["amount"]) : null; - $this->base = isset($rawPrediction["base"]) - ? (float) ($rawPrediction["base"]) : null; - $this->description = $rawPrediction["description"] ?? null; - $this->number = isset($rawPrediction["number"]) - ? (float) ($rawPrediction["number"]) : null; - $this->rate = isset($rawPrediction["rate"]) - ? (float) ($rawPrediction["rate"]) : null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["base"] = SummaryHelperV1::formatFloat($this->base); - $outArr["description"] = SummaryHelperV1::formatForDisplay($this->description, 36); - $outArr["number"] = SummaryHelperV1::formatFloat($this->number); - $outArr["rate"] = SummaryHelperV1::formatFloat($this->rate); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["amount"], 12); - $outStr .= SummaryHelperV1::padString($printable["base"], 9); - $outStr .= SummaryHelperV1::padString($printable["description"], 36); - $outStr .= SummaryHelperV1::padString($printable["number"], 6); - $outStr .= SummaryHelperV1::padString($printable["rate"], 9); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php b/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php deleted file mode 100644 index 833a56da..00000000 --- a/src/V1/Product/Fr/Payslip/PayslipV3SalaryDetails.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class PayslipV3SalaryDetails extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new PayslipV3SalaryDetail($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function salaryDetailsSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 14); - $outStr .= "+" . str_repeat($char, 11); - $outStr .= "+" . str_repeat($char, 38); - $outStr .= "+" . str_repeat($char, 8); - $outStr .= "+" . str_repeat($char, 11); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::salaryDetailsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::salaryDetailsSeparator('-') . "\n "; - $outStr .= " | Amount "; - $outStr .= " | Base "; - $outStr .= " | Description "; - $outStr .= " | Number"; - $outStr .= " | Rate "; - $outStr .= " |\n" . self::salaryDetailsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php deleted file mode 100644 index e6672a1c..00000000 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new IndianPassportV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(IndianPassportV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php b/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php deleted file mode 100644 index b23024a6..00000000 --- a/src/V1/Product/Ind/IndianPassport/IndianPassportV1Document.php +++ /dev/null @@ -1,313 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["address1"])) { - throw new MindeeUnsetException(); - } - $this->address1 = new StringField( - $rawPrediction["address1"], - $pageId - ); - if (!isset($rawPrediction["address2"])) { - throw new MindeeUnsetException(); - } - $this->address2 = new StringField( - $rawPrediction["address2"], - $pageId - ); - if (!isset($rawPrediction["address3"])) { - throw new MindeeUnsetException(); - } - $this->address3 = new StringField( - $rawPrediction["address3"], - $pageId - ); - if (!isset($rawPrediction["birth_date"])) { - throw new MindeeUnsetException(); - } - $this->birthDate = new DateField( - $rawPrediction["birth_date"], - $pageId - ); - if (!isset($rawPrediction["birth_place"])) { - throw new MindeeUnsetException(); - } - $this->birthPlace = new StringField( - $rawPrediction["birth_place"], - $pageId - ); - if (!isset($rawPrediction["country"])) { - throw new MindeeUnsetException(); - } - $this->country = new StringField( - $rawPrediction["country"], - $pageId - ); - if (!isset($rawPrediction["expiry_date"])) { - throw new MindeeUnsetException(); - } - $this->expiryDate = new DateField( - $rawPrediction["expiry_date"], - $pageId - ); - if (!isset($rawPrediction["file_number"])) { - throw new MindeeUnsetException(); - } - $this->fileNumber = new StringField( - $rawPrediction["file_number"], - $pageId - ); - if (!isset($rawPrediction["gender"])) { - throw new MindeeUnsetException(); - } - $this->gender = new ClassificationField( - $rawPrediction["gender"], - $pageId - ); - if (!isset($rawPrediction["given_names"])) { - throw new MindeeUnsetException(); - } - $this->givenNames = new StringField( - $rawPrediction["given_names"], - $pageId - ); - if (!isset($rawPrediction["id_number"])) { - throw new MindeeUnsetException(); - } - $this->idNumber = new StringField( - $rawPrediction["id_number"], - $pageId - ); - if (!isset($rawPrediction["issuance_date"])) { - throw new MindeeUnsetException(); - } - $this->issuanceDate = new DateField( - $rawPrediction["issuance_date"], - $pageId - ); - if (!isset($rawPrediction["issuance_place"])) { - throw new MindeeUnsetException(); - } - $this->issuancePlace = new StringField( - $rawPrediction["issuance_place"], - $pageId - ); - if (!isset($rawPrediction["legal_guardian"])) { - throw new MindeeUnsetException(); - } - $this->legalGuardian = new StringField( - $rawPrediction["legal_guardian"], - $pageId - ); - if (!isset($rawPrediction["mrz1"])) { - throw new MindeeUnsetException(); - } - $this->mrz1 = new StringField( - $rawPrediction["mrz1"], - $pageId - ); - if (!isset($rawPrediction["mrz2"])) { - throw new MindeeUnsetException(); - } - $this->mrz2 = new StringField( - $rawPrediction["mrz2"], - $pageId - ); - if (!isset($rawPrediction["name_of_mother"])) { - throw new MindeeUnsetException(); - } - $this->nameOfMother = new StringField( - $rawPrediction["name_of_mother"], - $pageId - ); - if (!isset($rawPrediction["name_of_spouse"])) { - throw new MindeeUnsetException(); - } - $this->nameOfSpouse = new StringField( - $rawPrediction["name_of_spouse"], - $pageId - ); - if (!isset($rawPrediction["old_passport_date_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportDateOfIssue = new DateField( - $rawPrediction["old_passport_date_of_issue"], - $pageId - ); - if (!isset($rawPrediction["old_passport_number"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportNumber = new StringField( - $rawPrediction["old_passport_number"], - $pageId - ); - if (!isset($rawPrediction["old_passport_place_of_issue"])) { - throw new MindeeUnsetException(); - } - $this->oldPassportPlaceOfIssue = new StringField( - $rawPrediction["old_passport_place_of_issue"], - $pageId - ); - if (!isset($rawPrediction["page_number"])) { - throw new MindeeUnsetException(); - } - $this->pageNumber = new ClassificationField( - $rawPrediction["page_number"], - $pageId - ); - if (!isset($rawPrediction["surname"])) { - throw new MindeeUnsetException(); - } - $this->surname = new StringField( - $rawPrediction["surname"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - - $outStr = ":Page Number: $this->pageNumber -:Country: $this->country -:ID Number: $this->idNumber -:Given Names: $this->givenNames -:Surname: $this->surname -:Birth Date: $this->birthDate -:Birth Place: $this->birthPlace -:Issuance Place: $this->issuancePlace -:Gender: $this->gender -:Issuance Date: $this->issuanceDate -:Expiry Date: $this->expiryDate -:MRZ Line 1: $this->mrz1 -:MRZ Line 2: $this->mrz2 -:Legal Guardian: $this->legalGuardian -:Name of Spouse: $this->nameOfSpouse -:Name of Mother: $this->nameOfMother -:Old Passport Date of Issue: $this->oldPassportDateOfIssue -:Old Passport Number: $this->oldPassportNumber -:Old Passport Place of Issue: $this->oldPassportPlaceOfIssue -:Address Line 1: $this->address1 -:Address Line 2: $this->address2 -:Address Line 3: $this->address3 -:File Number: $this->fileNumber -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php deleted file mode 100644 index 067048f5..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new NutritionFactsLabelV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(NutritionFactsLabelV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php deleted file mode 100644 index 45523691..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1AddedSugar.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php deleted file mode 100644 index 546a123f..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Calorie.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php deleted file mode 100644 index 6fba6887..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Cholesterol.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php deleted file mode 100644 index b86ca06f..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1DietaryFiber.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php deleted file mode 100644 index 66176a71..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Document.php +++ /dev/null @@ -1,216 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["added_sugars"])) { - throw new MindeeUnsetException(); - } - $this->addedSugars = new NutritionFactsLabelV1AddedSugar( - $rawPrediction["added_sugars"], - $pageId - ); - if (!isset($rawPrediction["calories"])) { - throw new MindeeUnsetException(); - } - $this->calories = new NutritionFactsLabelV1Calorie( - $rawPrediction["calories"], - $pageId - ); - if (!isset($rawPrediction["cholesterol"])) { - throw new MindeeUnsetException(); - } - $this->cholesterol = new NutritionFactsLabelV1Cholesterol( - $rawPrediction["cholesterol"], - $pageId - ); - if (!isset($rawPrediction["dietary_fiber"])) { - throw new MindeeUnsetException(); - } - $this->dietaryFiber = new NutritionFactsLabelV1DietaryFiber( - $rawPrediction["dietary_fiber"], - $pageId - ); - if (!isset($rawPrediction["nutrients"])) { - throw new MindeeUnsetException(); - } - $this->nutrients = new NutritionFactsLabelV1Nutrients( - $rawPrediction["nutrients"], - $pageId - ); - if (!isset($rawPrediction["protein"])) { - throw new MindeeUnsetException(); - } - $this->protein = new NutritionFactsLabelV1Protein( - $rawPrediction["protein"], - $pageId - ); - if (!isset($rawPrediction["saturated_fat"])) { - throw new MindeeUnsetException(); - } - $this->saturatedFat = new NutritionFactsLabelV1SaturatedFat( - $rawPrediction["saturated_fat"], - $pageId - ); - if (!isset($rawPrediction["serving_per_box"])) { - throw new MindeeUnsetException(); - } - $this->servingPerBox = new AmountField( - $rawPrediction["serving_per_box"], - $pageId - ); - if (!isset($rawPrediction["serving_size"])) { - throw new MindeeUnsetException(); - } - $this->servingSize = new NutritionFactsLabelV1ServingSize( - $rawPrediction["serving_size"], - $pageId - ); - if (!isset($rawPrediction["sodium"])) { - throw new MindeeUnsetException(); - } - $this->sodium = new NutritionFactsLabelV1Sodium( - $rawPrediction["sodium"], - $pageId - ); - if (!isset($rawPrediction["total_carbohydrate"])) { - throw new MindeeUnsetException(); - } - $this->totalCarbohydrate = new NutritionFactsLabelV1TotalCarbohydrate( - $rawPrediction["total_carbohydrate"], - $pageId - ); - if (!isset($rawPrediction["total_fat"])) { - throw new MindeeUnsetException(); - } - $this->totalFat = new NutritionFactsLabelV1TotalFat( - $rawPrediction["total_fat"], - $pageId - ); - if (!isset($rawPrediction["total_sugars"])) { - throw new MindeeUnsetException(); - } - $this->totalSugars = new NutritionFactsLabelV1TotalSugar( - $rawPrediction["total_sugars"], - $pageId - ); - if (!isset($rawPrediction["trans_fat"])) { - throw new MindeeUnsetException(); - } - $this->transFat = new NutritionFactsLabelV1TransFat( - $rawPrediction["trans_fat"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $servingSizeToFieldList = $this->servingSize->toFieldList(); - $caloriesToFieldList = $this->calories->toFieldList(); - $totalFatToFieldList = $this->totalFat->toFieldList(); - $saturatedFatToFieldList = $this->saturatedFat->toFieldList(); - $transFatToFieldList = $this->transFat->toFieldList(); - $cholesterolToFieldList = $this->cholesterol->toFieldList(); - $totalCarbohydrateToFieldList = $this->totalCarbohydrate->toFieldList(); - $dietaryFiberToFieldList = $this->dietaryFiber->toFieldList(); - $totalSugarsToFieldList = $this->totalSugars->toFieldList(); - $addedSugarsToFieldList = $this->addedSugars->toFieldList(); - $proteinToFieldList = $this->protein->toFieldList(); - $sodiumToFieldList = $this->sodium->toFieldList(); - $nutrientsSummary = (string) ($this->nutrients); - - $outStr = ":Serving per Box: $this->servingPerBox -:Serving Size: $servingSizeToFieldList -:Calories: $caloriesToFieldList -:Total Fat: $totalFatToFieldList -:Saturated Fat: $saturatedFatToFieldList -:Trans Fat: $transFatToFieldList -:Cholesterol: $cholesterolToFieldList -:Total Carbohydrate: $totalCarbohydrateToFieldList -:Dietary Fiber: $dietaryFiberToFieldList -:Total Sugars: $totalSugarsToFieldList -:Added Sugars: $addedSugarsToFieldList -:Protein: $proteinToFieldList -:sodium: $sodiumToFieldList -:nutrients: $nutrientsSummary -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php deleted file mode 100644 index 8d85aa46..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrient.php +++ /dev/null @@ -1,97 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->dailyValue = isset($rawPrediction["daily_value"]) - ? (float) ($rawPrediction["daily_value"]) : null; - $this->name = $rawPrediction["name"] ?? null; - $this->per100G = isset($rawPrediction["per_100g"]) - ? (float) ($rawPrediction["per_100g"]) : null; - $this->perServing = isset($rawPrediction["per_serving"]) - ? (float) ($rawPrediction["per_serving"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["name"] = SummaryHelperV1::formatForDisplay($this->name, 20); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["dailyValue"], 11); - $outStr .= SummaryHelperV1::padString($printable["name"], 20); - $outStr .= SummaryHelperV1::padString($printable["per100G"], 8); - $outStr .= SummaryHelperV1::padString($printable["perServing"], 11); - $outStr .= SummaryHelperV1::padString($printable["unit"], 4); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php deleted file mode 100644 index 82ed28cd..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Nutrients.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class NutritionFactsLabelV1Nutrients extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new NutritionFactsLabelV1Nutrient($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function nutrientsSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 22); - $outStr .= "+" . str_repeat($char, 10); - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 6); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::nutrientsSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::nutrientsSeparator('-') . "\n "; - $outStr .= " | Daily Value"; - $outStr .= " | Name "; - $outStr .= " | Per 100g"; - $outStr .= " | Per Serving"; - $outStr .= " | Unit"; - $outStr .= " |\n" . self::nutrientsSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php deleted file mode 100644 index 88e7122e..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Protein.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php deleted file mode 100644 index 7233bb43..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1SaturatedFat.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php deleted file mode 100644 index 84bc8ece..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1ServingSize.php +++ /dev/null @@ -1,73 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->amount = isset($rawPrediction["amount"]) - ? (float) ($rawPrediction["amount"]) : null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["amount"] = SummaryHelperV1::formatFloat($this->amount); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Amount: " . $printable["amount"]; - $outStr .= "\n :Unit: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php deleted file mode 100644 index 7fffe0ef..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Sodium.php +++ /dev/null @@ -1,89 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - $outStr .= "\n :Unit: " . $printable["unit"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php deleted file mode 100644 index 281b2967..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalCarbohydrate.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php deleted file mode 100644 index 5407464e..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalFat.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php deleted file mode 100644 index 0ee3b05a..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TotalSugar.php +++ /dev/null @@ -1,83 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php b/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php deleted file mode 100644 index 981dc5d8..00000000 --- a/src/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1TransFat.php +++ /dev/null @@ -1,82 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->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 as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["dailyValue"] = SummaryHelperV1::formatFloat($this->dailyValue); - $outArr["per100G"] = SummaryHelperV1::formatFloat($this->per100G); - $outArr["perServing"] = SummaryHelperV1::formatFloat($this->perServing); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :Daily Value: " . $printable["dailyValue"]; - $outStr .= "\n :Per 100g: " . $printable["per100G"]; - $outStr .= "\n :Per Serving: " . $printable["perServing"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php deleted file mode 100644 index 56e67941..00000000 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new HealthcareCardV1Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(HealthcareCardV1Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php deleted file mode 100644 index 77b066d2..00000000 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copay.php +++ /dev/null @@ -1,74 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->serviceFees = isset($rawPrediction["service_fees"]) - ? (float) ($rawPrediction["service_fees"]) : null; - $this->serviceName = $rawPrediction["service_name"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["serviceFees"] = SummaryHelperV1::formatFloat($this->serviceFees); - $outArr["serviceName"] = SummaryHelperV1::formatForDisplay($this->serviceName, 20); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["serviceFees"], 12); - $outStr .= SummaryHelperV1::padString($printable["serviceName"], 20); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php deleted file mode 100644 index 0349c0c6..00000000 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Copays.php +++ /dev/null @@ -1,66 +0,0 @@ - - */ -class HealthcareCardV1Copays extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new HealthcareCardV1Copay($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function copaysSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 14); - $outStr .= "+" . str_repeat($char, 22); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::copaysSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::copaysSeparator('-') . "\n "; - $outStr .= " | Service Fees"; - $outStr .= " | Service Name "; - $outStr .= " |\n" . self::copaysSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php b/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php deleted file mode 100644 index ca70c8ce..00000000 --- a/src/V1/Product/Us/HealthcareCard/HealthcareCardV1Document.php +++ /dev/null @@ -1,209 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["company_name"])) { - throw new MindeeUnsetException(); - } - $this->companyName = new StringField( - $rawPrediction["company_name"], - $pageId - ); - if (!isset($rawPrediction["copays"])) { - throw new MindeeUnsetException(); - } - $this->copays = new HealthcareCardV1Copays( - $rawPrediction["copays"], - $pageId - ); - if (!isset($rawPrediction["dependents"])) { - throw new MindeeUnsetException(); - } - $this->dependents = array_map( - static fn($prediction) => new StringField($prediction, $pageId), - $rawPrediction["dependents"] - ); - if (!isset($rawPrediction["enrollment_date"])) { - throw new MindeeUnsetException(); - } - $this->enrollmentDate = new DateField( - $rawPrediction["enrollment_date"], - $pageId - ); - if (!isset($rawPrediction["group_number"])) { - throw new MindeeUnsetException(); - } - $this->groupNumber = new StringField( - $rawPrediction["group_number"], - $pageId - ); - if (!isset($rawPrediction["issuer_80840"])) { - throw new MindeeUnsetException(); - } - $this->issuer80840 = new StringField( - $rawPrediction["issuer_80840"], - $pageId - ); - if (!isset($rawPrediction["member_id"])) { - throw new MindeeUnsetException(); - } - $this->memberId = new StringField( - $rawPrediction["member_id"], - $pageId - ); - if (!isset($rawPrediction["member_name"])) { - throw new MindeeUnsetException(); - } - $this->memberName = new StringField( - $rawPrediction["member_name"], - $pageId - ); - if (!isset($rawPrediction["payer_id"])) { - throw new MindeeUnsetException(); - } - $this->payerId = new StringField( - $rawPrediction["payer_id"], - $pageId - ); - if (!isset($rawPrediction["plan_name"])) { - throw new MindeeUnsetException(); - } - $this->planName = new StringField( - $rawPrediction["plan_name"], - $pageId - ); - if (!isset($rawPrediction["rx_bin"])) { - throw new MindeeUnsetException(); - } - $this->rxBin = new StringField( - $rawPrediction["rx_bin"], - $pageId - ); - if (!isset($rawPrediction["rx_grp"])) { - throw new MindeeUnsetException(); - } - $this->rxGrp = new StringField( - $rawPrediction["rx_grp"], - $pageId - ); - if (!isset($rawPrediction["rx_id"])) { - throw new MindeeUnsetException(); - } - $this->rxId = new StringField( - $rawPrediction["rx_id"], - $pageId - ); - if (!isset($rawPrediction["rx_pcn"])) { - throw new MindeeUnsetException(); - } - $this->rxPcn = new StringField( - $rawPrediction["rx_pcn"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $dependents = implode( - "\n ", - $this->dependents - ); - $copaysSummary = (string) ($this->copays); - - $outStr = ":Company Name: $this->companyName -:Plan Name: $this->planName -:Member Name: $this->memberName -:Member ID: $this->memberId -:Issuer 80840: $this->issuer80840 -:Dependents: $dependents -:Group Number: $this->groupNumber -:Payer ID: $this->payerId -:RX BIN: $this->rxBin -:RX ID: $this->rxId -:RX GRP: $this->rxGrp -:RX PCN: $this->rxPcn -:Copays: $copaysSummary -:Enrollment Date: $this->enrollmentDate -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Us/UsMail/UsMailV3.php b/src/V1/Product/Us/UsMail/UsMailV3.php deleted file mode 100644 index b95325b7..00000000 --- a/src/V1/Product/Us/UsMail/UsMailV3.php +++ /dev/null @@ -1,42 +0,0 @@ -> $rawPrediction Raw prediction from the HTTP response. - */ - public function __construct(array $rawPrediction) - { - parent::__construct($rawPrediction); - $this->prediction = new UsMailV3Document($rawPrediction['prediction']); - $this->pages = []; - foreach ($rawPrediction['pages'] as $page) { - try { - $this->pages[] = new Page(UsMailV3Document::class, $page); - } catch (MindeeUnsetException) { - } - } - } -} diff --git a/src/V1/Product/Us/UsMail/UsMailV3Document.php b/src/V1/Product/Us/UsMail/UsMailV3Document.php deleted file mode 100644 index 276893a4..00000000 --- a/src/V1/Product/Us/UsMail/UsMailV3Document.php +++ /dev/null @@ -1,102 +0,0 @@ -> $rawPrediction Raw prediction from HTTP response. - * @param integer|null $pageId Page number for multi pages document. - * @throws MindeeUnsetException Throws if a field doesn't appear in the response. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - if (!isset($rawPrediction["is_return_to_sender"])) { - throw new MindeeUnsetException(); - } - $this->isReturnToSender = new BooleanField( - $rawPrediction["is_return_to_sender"], - $pageId - ); - if (!isset($rawPrediction["recipient_addresses"])) { - throw new MindeeUnsetException(); - } - $this->recipientAddresses = new UsMailV3RecipientAddresses( - $rawPrediction["recipient_addresses"], - $pageId - ); - if (!isset($rawPrediction["recipient_names"])) { - throw new MindeeUnsetException(); - } - $this->recipientNames = array_map( - static fn($prediction) => new StringField($prediction, $pageId), - $rawPrediction["recipient_names"] - ); - if (!isset($rawPrediction["sender_address"])) { - throw new MindeeUnsetException(); - } - $this->senderAddress = new UsMailV3SenderAddress( - $rawPrediction["sender_address"], - $pageId - ); - if (!isset($rawPrediction["sender_name"])) { - throw new MindeeUnsetException(); - } - $this->senderName = new StringField( - $rawPrediction["sender_name"], - $pageId - ); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - $senderAddressToFieldList = $this->senderAddress->toFieldList(); - $recipientNames = implode( - "\n ", - $this->recipientNames - ); - $recipientAddressesSummary = (string) ($this->recipientAddresses); - - $outStr = ":Sender Name: $this->senderName -:Sender Address: $senderAddressToFieldList -:Recipient Names: $recipientNames -:Recipient Addresses: $recipientAddressesSummary -:Return to Sender: $this->isReturnToSender -"; - return SummaryHelperV1::cleanOutString($outStr); - } -} diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php deleted file mode 100644 index 872ae58c..00000000 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddress.php +++ /dev/null @@ -1,115 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->city = $rawPrediction["city"] ?? null; - $this->complete = $rawPrediction["complete"] ?? null; - $this->isAddressChange = $rawPrediction["is_address_change"] ?? null; - $this->postalCode = $rawPrediction["postal_code"] ?? null; - $this->privateMailboxNumber = $rawPrediction["private_mailbox_number"] ?? null; - $this->state = $rawPrediction["state"] ?? null; - $this->street = $rawPrediction["street"] ?? null; - $this->unit = $rawPrediction["unit"] ?? null; - } - - /** - * Return values for printing inside an RST table. - * @return array - */ - private function tablePrintableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city, 15); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete, 35); - $outArr["isAddressChange"] = SummaryHelperV1::formatForDisplay($this->isAddressChange); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["privateMailboxNumber"] = SummaryHelperV1::formatForDisplay($this->privateMailboxNumber); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street, 25); - $outArr["unit"] = SummaryHelperV1::formatForDisplay($this->unit, 15); - return $outArr; - } - - /** - * Output in a format suitable for inclusion in an rST table. - * - */ - public function toTableLine(): string - { - $printable = $this->tablePrintableValues(); - $outStr = "| "; - $outStr .= SummaryHelperV1::padString($printable["city"], 15); - $outStr .= SummaryHelperV1::padString($printable["complete"], 35); - $outStr .= SummaryHelperV1::padString($printable["isAddressChange"], 17); - $outStr .= SummaryHelperV1::padString($printable["postalCode"], 11); - $outStr .= SummaryHelperV1::padString($printable["privateMailboxNumber"], 22); - $outStr .= SummaryHelperV1::padString($printable["state"], 5); - $outStr .= SummaryHelperV1::padString($printable["street"], 25); - $outStr .= SummaryHelperV1::padString($printable["unit"], 15); - return rtrim(SummaryHelperV1::cleanOutString($outStr)); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toTableLine()); - } -} diff --git a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php b/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php deleted file mode 100644 index 652430f4..00000000 --- a/src/V1/Product/Us/UsMail/UsMailV3RecipientAddresses.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -class UsMailV3RecipientAddresses extends ArrayObject implements Stringable -{ - /** - * @param array> $rawPrediction Raw prediction array. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, ?int $pageId = null) - { - $entries = []; - foreach ($rawPrediction as $entry) { - $entries[] = new UsMailV3RecipientAddress($entry, $pageId); - } - parent::__construct($entries); - } - - /** - * Creates a line of rST table-compliant string separators. - * - * @param string $char Character to use as a separator. - */ - public static function recipientAddressesSeparator(string $char): string - { - $outStr = " "; - $outStr .= "+" . str_repeat($char, 17); - $outStr .= "+" . str_repeat($char, 37); - $outStr .= "+" . str_repeat($char, 19); - $outStr .= "+" . str_repeat($char, 13); - $outStr .= "+" . str_repeat($char, 24); - $outStr .= "+" . str_repeat($char, 7); - $outStr .= "+" . str_repeat($char, 27); - $outStr .= "+" . str_repeat($char, 17); - return $outStr . "+"; - } - - - /** - * String representation. - * - */ - public function __toString(): string - { - $lines = ""; - $iterator = $this->getIterator(); - if (!$iterator->valid()) { - return ""; - } - while ($iterator->valid()) { - $entry = $iterator->current(); - $lines .= "\n " . $entry->toTableLine() . "\n" . self::recipientAddressesSeparator('-'); - $iterator->next(); - } - $outStr = "\n" . self::recipientAddressesSeparator('-') . "\n "; - $outStr .= " | City "; - $outStr .= " | Complete Address "; - $outStr .= " | Is Address Change"; - $outStr .= " | Postal Code"; - $outStr .= " | Private Mailbox Number"; - $outStr .= " | State"; - $outStr .= " | Street "; - $outStr .= " | Unit "; - $outStr .= " |\n" . self::recipientAddressesSeparator('='); - $outStr .= $lines; - return $outStr; - } -} diff --git a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php b/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php deleted file mode 100644 index 3414229a..00000000 --- a/src/V1/Product/Us/UsMail/UsMailV3SenderAddress.php +++ /dev/null @@ -1,93 +0,0 @@ -> $rawPrediction Array containing the JSON document response. - * @param integer|null $pageId Page number for multi pages document. - */ - public function __construct(array $rawPrediction, public ?int $pageId) - { - $this->setConfidence($rawPrediction); - $this->setPosition($rawPrediction); - $this->city = $rawPrediction["city"] ?? null; - $this->complete = $rawPrediction["complete"] ?? null; - $this->postalCode = $rawPrediction["postal_code"] ?? null; - $this->state = $rawPrediction["state"] ?? null; - $this->street = $rawPrediction["street"] ?? null; - } - - /** - * Return values for printing as an array. - * @return array - */ - private function printableValues(): array - { - $outArr = []; - $outArr["city"] = SummaryHelperV1::formatForDisplay($this->city); - $outArr["complete"] = SummaryHelperV1::formatForDisplay($this->complete); - $outArr["postalCode"] = SummaryHelperV1::formatForDisplay($this->postalCode); - $outArr["state"] = SummaryHelperV1::formatForDisplay($this->state); - $outArr["street"] = SummaryHelperV1::formatForDisplay($this->street); - return $outArr; - } - /** - * Output in a format suitable for inclusion in a field list. - * - */ - public function toFieldList(): string - { - $printable = $this->printableValues(); - $outStr = ""; - $outStr .= "\n :City: " . $printable["city"]; - $outStr .= "\n :Complete Address: " . $printable["complete"]; - $outStr .= "\n :Postal Code: " . $printable["postalCode"]; - $outStr .= "\n :State: " . $printable["state"]; - $outStr .= "\n :Street: " . $printable["street"]; - return rtrim($outStr); - } - - /** - * @return string String representation. - */ - public function __toString(): string - { - return SummaryHelperV1::cleanOutString($this->toFieldList()); - } -} diff --git a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php b/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php deleted file mode 100644 index a4e68e53..00000000 --- a/tests/V1/Product/BillOfLading/BillOfLadingV1Test.php +++ /dev/null @@ -1,61 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/DeliveryNote/DeliveryNoteV1Test.php b/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php deleted file mode 100644 index da3ab166..00000000 --- a/tests/V1/Product/DeliveryNote/DeliveryNoteV1Test.php +++ /dev/null @@ -1,46 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/Fr/EnergyBill/EnergyBillV1Test.php b/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php deleted file mode 100644 index 08b37113..00000000 --- a/tests/V1/Product/Fr/EnergyBill/EnergyBillV1Test.php +++ /dev/null @@ -1,57 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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 deleted file mode 100644 index cd38fe07..00000000 --- a/tests/V1/Product/Fr/HealthCard/HealthCardV1Test.php +++ /dev/null @@ -1,43 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/Payslip/PayslipV3Test.php b/tests/V1/Product/Fr/Payslip/PayslipV3Test.php deleted file mode 100644 index 5c8cbb0a..00000000 --- a/tests/V1/Product/Fr/Payslip/PayslipV3Test.php +++ /dev/null @@ -1,80 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/Ind/IndianPassport/IndianPassportV1Test.php b/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php deleted file mode 100644 index 7b79bc5f..00000000 --- a/tests/V1/Product/Ind/IndianPassport/IndianPassportV1Test.php +++ /dev/null @@ -1,60 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/NutritionFactsLabel/NutritionFactsLabelV1Test.php b/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php deleted file mode 100644 index 2972b3b1..00000000 --- a/tests/V1/Product/NutritionFactsLabel/NutritionFactsLabelV1Test.php +++ /dev/null @@ -1,77 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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/Us/HealthcareCard/HealthcareCardV1Test.php b/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php deleted file mode 100644 index a276fa84..00000000 --- a/tests/V1/Product/Us/HealthcareCard/HealthcareCardV1Test.php +++ /dev/null @@ -1,53 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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 deleted file mode 100644 index 772edbf2..00000000 --- a/tests/V1/Product/Us/UsMail/UsMailV3Test.php +++ /dev/null @@ -1,48 +0,0 @@ -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(): void - { - self::assertSame($this->completeDocReference, (string) ($this->completeDoc)); - } - - public function testEmptyDoc(): void - { - $prediction = $this->emptyDoc->inference->prediction; - 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); - } -} From f4cc0ef68bf3c0476c4f9fc45c3f92ce314c70aa Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Thu, 28 May 2026 15:59:14 +0200 Subject: [PATCH 09/11] :sparkles: add support for model search (#193) --- src/V2/Client.php | 14 +++++- src/V2/Http/MindeeApiV2.php | 43 +++++++++++++++++- src/V2/Parsing/Search/ModelWebhook.php | 43 ++++++++++++++++++ src/V2/Parsing/Search/Pagination.php | 52 ++++++++++++++++++++++ src/V2/Parsing/Search/SearchModel.php | 55 ++++++++++++++++++++++++ src/V2/Parsing/Search/SearchModels.php | 47 ++++++++++++++++++++ src/V2/Parsing/Search/SearchResponse.php | 50 +++++++++++++++++++++ tests/V2/ClientV2Test.php | 18 ++++++++ tests/V2/Parsing/SearchResponseTest.php | 44 +++++++++++++++++++ 9 files changed, 364 insertions(+), 2 deletions(-) create mode 100644 src/V2/Parsing/Search/ModelWebhook.php create mode 100644 src/V2/Parsing/Search/Pagination.php create mode 100644 src/V2/Parsing/Search/SearchModel.php create mode 100644 src/V2/Parsing/Search/SearchModels.php create mode 100644 src/V2/Parsing/Search/SearchResponse.php create mode 100644 tests/V2/Parsing/SearchResponseTest.php diff --git a/src/V2/Client.php b/src/V2/Client.php index 5b0e57d6..25de2e47 100644 --- a/src/V2/Client.php +++ b/src/V2/Client.php @@ -12,6 +12,7 @@ use Mindee\V2\Http\MindeeApiV2; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\Job\JobResponse; +use Mindee\V2\Parsing\Search\SearchResponse; /** * Mindee Client V2. @@ -32,7 +33,7 @@ class Client */ public function __construct(?string $apiKey = null) { - $this->mindeeApi = new MindeeApiV2($apiKey ?: getenv('MINDEE_V2_API_KEY')); + $this->mindeeApi = new MindeeApiV2($apiKey ?: (getenv('MINDEE_V2_API_KEY') ?: null)); } /** @@ -159,4 +160,15 @@ public function enqueueAndGetResult( . ($pollingOptions->delaySec * $retryCounter) . " seconds" ); } + + /** + * Searches for a list of available models for the given API key. + * @param string|null $modelName Optional model name to filter by. + * @param string|null $modelType Optional model type to filter by. + * @return SearchResponse The list of models matching the criteria. + */ + public function searchModels(?string $modelName = null, ?string $modelType = null): SearchResponse + { + return $this->mindeeApi->searchModels($modelName, $modelType); + } } diff --git a/src/V2/Http/MindeeApiV2.php b/src/V2/Http/MindeeApiV2.php index 4aa728c1..67c24af5 100644 --- a/src/V2/Http/MindeeApiV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -22,6 +22,7 @@ use Mindee\V2\Parsing\Error\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\Job\JobResponse; +use Mindee\V2\Parsing\Search\SearchResponse; use ReflectionClass; use ReflectionException; use ReflectionProperty; @@ -106,7 +107,7 @@ public function __construct(?string $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.', + . API_V2_KEY_ENV_NAME . ' environment variable.', ErrorCode::USER_INPUT_ERROR ); } @@ -386,4 +387,44 @@ private function checkValidResponse(array $result): void throw new MindeeV2HttpUnknownException(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); } } + + /** + * @return array> Server response. + */ + private function reqGetSearchModels(?string $modelName = null, ?string $modelType = null): array + { + $url = $this->baseUrl . "/v2/search/models"; + $params = []; + if ($modelName) { + $params['name'] = $modelName; + } + if ($modelType) { + $params['model_type'] = $modelType; + } + if (!empty($params)) { + $url .= '?' . http_build_query($params); + } + + $ch = $this->initChannel(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HTTPGET, true); + + $resp = [ + 'data' => curl_exec($ch), + 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), + ]; + curl_close($ch); + return $resp; + } + + /** + * Retrieves a list of models based on criteria. + * @param string|null $modelName Optional model name to filter by. + * @param string|null $modelType Optional model type to filter by. + * @return SearchResponse The list of models matching the criteria. + */ + public function searchModels(?string $modelName = null, ?string $modelType = null): SearchResponse + { + return $this->processResponse(SearchResponse::class, $this->reqGetSearchModels($modelName, $modelType)); + } } diff --git a/src/V2/Parsing/Search/ModelWebhook.php b/src/V2/Parsing/Search/ModelWebhook.php new file mode 100644 index 00000000..3ec8a33c --- /dev/null +++ b/src/V2/Parsing/Search/ModelWebhook.php @@ -0,0 +1,43 @@ +> $rawResponse + */ + public function __construct(array $rawResponse) + { + $this->id = $rawResponse['id']; + $this->name = $rawResponse['name']; + $this->url = $rawResponse['url']; + } + + public function __toString(): string + { + return ":Name: $this->name\n" + . ":ID: $this->id\n" + . ":URL: $this->url\n"; + } +} diff --git a/src/V2/Parsing/Search/Pagination.php b/src/V2/Parsing/Search/Pagination.php new file mode 100644 index 00000000..a3adf759 --- /dev/null +++ b/src/V2/Parsing/Search/Pagination.php @@ -0,0 +1,52 @@ +> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + $this->perPage = $rawResponse['per_page']; + $this->page = $rawResponse['page']; + $this->totalItems = $rawResponse['total_items']; + $this->totalPages = $rawResponse['total_pages']; + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return ":Per Page: $this->perPage\n" + . ":Page: $this->page\n" + . ":Total Items: $this->totalItems\n" + . ":Total Pages: $this->totalPages\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchModel.php b/src/V2/Parsing/Search/SearchModel.php new file mode 100644 index 00000000..5a9d88a0 --- /dev/null +++ b/src/V2/Parsing/Search/SearchModel.php @@ -0,0 +1,55 @@ + List of webhooks associated with the model. + */ + public array $webhooks; + + /** + * @param array> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + $this->id = $rawResponse['id']; + $this->name = $rawResponse['name']; + $this->modelType = $rawResponse['model_type']; + $this->webhooks = array_map( + static fn($webhook) => new ModelWebhook($webhook), + $rawResponse['webhooks'] ?? [] + ); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return ":Name: $this->name\n" + . ":ID: $this->id\n" + . ":Model Type: $this->modelType\n" + . ":Webhooks: " . implode(', ', array_map(static fn($webhook) => $webhook->name, $this->webhooks)) . "\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchModels.php b/src/V2/Parsing/Search/SearchModels.php new file mode 100644 index 00000000..16d72a80 --- /dev/null +++ b/src/V2/Parsing/Search/SearchModels.php @@ -0,0 +1,47 @@ + + */ +class SearchModels extends ArrayObject implements Stringable +{ + /** + * @param array>> $prediction Raw prediction. + */ + public function __construct(array $prediction) + { + $models = array_map(static fn($entry) => new SearchModel($entry), $prediction); + + parent::__construct($models); + } + + /** + * Default string representation. + */ + public function __toString(): string + { + if ($this->count() === 0) { + return "\n"; + } + + $lines = []; + foreach ($this as $model) { + $lines[] = "* :Name: " . $model->name; + $lines[] = " :ID: " . $model->id; + $lines[] = " :Model Type: " . $model->modelType; + $lines[] = " :Webhooks: " . count($model->webhooks); + } + + return implode("\n", $lines) . "\n"; + } +} diff --git a/src/V2/Parsing/Search/SearchResponse.php b/src/V2/Parsing/Search/SearchResponse.php new file mode 100644 index 00000000..6e0960ff --- /dev/null +++ b/src/V2/Parsing/Search/SearchResponse.php @@ -0,0 +1,50 @@ +> $rawResponse Raw server response array. + */ + public function __construct(array $rawResponse) + { + parent::__construct($rawResponse); + $this->models = new SearchModels($rawResponse['models']); + $this->pagination = new Pagination($rawResponse['pagination']); + } + + /** + * @return string String representation. + */ + public function __toString(): string + { + return implode("\n", [ + 'Models', + '######', + (string) $this->models, + 'Pagination Metadata', + '###################', + (string) $this->pagination, + '', + ]); + } +} diff --git a/tests/V2/ClientV2Test.php b/tests/V2/ClientV2Test.php index ec3cc973..8d4edbad 100644 --- a/tests/V2/ClientV2Test.php +++ b/tests/V2/ClientV2Test.php @@ -139,6 +139,7 @@ public function testInferenceLoadsLocally(): void 'Supplier name mismatch' ); } + public function testInvalidBaseUrlRaisesMindeeException(): void { $this->expectException(MindeeException::class); @@ -159,4 +160,21 @@ public function testInvalidBaseUrlRaisesMindeeException(): void } } } + + public function testInvalidApiKeyRaisesMindeeException(): void + { + $original = getenv('MINDEE_V2_API_KEY') ?: null; + putenv('MINDEE_V2_API_KEY='); + $this->expectException(MindeeException::class); + $this->expectExceptionMessage('Missing API key for call, check your Client configuration.You can set this using the MINDEE_V2_API_KEY environment variable.'); + try { + $client = new Client(); + } finally { + if (null === $original) { + putenv('MINDEE_V2_API_KEY'); + } else { + putenv('MINDEE_V2_API_KEY=' . $original); + } + } + } } diff --git a/tests/V2/Parsing/SearchResponseTest.php b/tests/V2/Parsing/SearchResponseTest.php new file mode 100644 index 00000000..bc3f6fce --- /dev/null +++ b/tests/V2/Parsing/SearchResponseTest.php @@ -0,0 +1,44 @@ +models); + foreach ($response->models as $model) { + self::assertInstanceOf(SearchModel::class, $model); + self::assertNotEmpty($model->id); + self::assertNotEmpty($model->name); + } + self::assertCount(2, $response->models[0]->webhooks); + self::assertEquals("https://failure.mindee.com", $response->models[0]->webhooks[0]->url); + + self::assertEquals(50, $response->pagination->perPage); + self::assertEquals(1, $response->pagination->page); + self::assertGreaterThanOrEqual(5, $response->pagination->totalItems); + self::assertEquals(1, $response->pagination->totalPages); + } +} From 30813247d17bf3a2b1f64adc45de824457871fd7 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Thu, 28 May 2026 17:21:56 +0200 Subject: [PATCH 10/11] :recycle: move more internals into v1/v2 (#194) --- bin/MindeeCliCommand.php | 2 +- src/Image/ImageExtractor.php | 84 ---------------- src/Pdf/PdfExtractor.php | 57 ++--------- src/V1/Client.php | 4 +- .../Error}/MindeeV1ClientException.php | 2 +- .../V1 => V1/Error}/MindeeV1HttpException.php | 2 +- src/V1/Image/ImageExtractor.php | 95 ++++++++++++++++++- src/V1/Pdf/PdfExtractor.php | 95 +++++++++++++++++++ .../V2 => V2/Error}/MindeeV2HttpException.php | 2 +- .../Error}/MindeeV2HttpUnknownException.php | 2 +- src/V2/Http/MindeeApiV2.php | 5 +- tests/ClientTest.php | 2 +- tests/V1/Error/MindeeHttpExceptionTest.php | 2 +- ...ceSplitterAutoExtractionTestFunctional.php | 2 +- tests/V1/Pdf/PdfExtractorTest.php | 2 +- tests/V2/ClientV2TestFunctional.php | 2 +- 16 files changed, 210 insertions(+), 150 deletions(-) rename src/{Error/V1 => V1/Error}/MindeeV1ClientException.php (89%) rename src/{Error/V1 => V1/Error}/MindeeV1HttpException.php (99%) create mode 100644 src/V1/Pdf/PdfExtractor.php rename src/{Error/V2 => V2/Error}/MindeeV2HttpException.php (97%) rename src/{Error/V2 => V2/Error}/MindeeV2HttpUnknownException.php (96%) diff --git a/bin/MindeeCliCommand.php b/bin/MindeeCliCommand.php index 3476f4e8..772f9758 100644 --- a/bin/MindeeCliCommand.php +++ b/bin/MindeeCliCommand.php @@ -5,7 +5,6 @@ namespace Mindee\Cli; use Exception; -use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\InputSource; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; @@ -13,6 +12,7 @@ use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\PredictOptions; +use Mindee\V1\Error\MindeeV1HttpException; use Mindee\V1\Parsing\Common\AsyncPredictResponse; use Mindee\V1\Parsing\Common\PredictResponse; use Symfony\Component\Console\Command\Command; diff --git a/src/Image/ImageExtractor.php b/src/Image/ImageExtractor.php index 6d72ebb6..7170dc52 100644 --- a/src/Image/ImageExtractor.php +++ b/src/Image/ImageExtractor.php @@ -9,7 +9,6 @@ use ImagickException; use Mindee\Dependency\DependencyChecker; use Mindee\Error\ErrorCode; -use Mindee\Error\MindeeGeometryException; use Mindee\Error\MindeeImageException; use Mindee\Error\MindeePdfException; use Mindee\Geometry\BBox; @@ -17,7 +16,6 @@ use Mindee\Geometry\Point; use Mindee\Geometry\Polygon; use Mindee\Input\LocalInputSource; -use Mindee\V1\Parsing\Standard\BaseField; use function count; use function sprintf; @@ -128,20 +126,6 @@ public function getPageCount(): int return count($this->pageImages); } - /** - * Extract multiple images on a given page from a list of fields having position data. - * - * @param array> $fields List of Fields to extract. - * @param integer $pageIndex The page index to extract, begins at 0. - * @param null|string $outputName The base output filename, must have an image extension. - * - * @return array a list of extracted images - */ - public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array - { - $outputName ??= $this->filename; - return $this->extractFromPage($fields, $pageIndex, $outputName); - } /** * Extracts images from a page. @@ -212,47 +196,6 @@ public function extractPolygonFromPage( return new ExtractedImage($extractedImageData, $filename, $format, $pageIndex, $index); } - /** - * Extracts a single image from a Position field. - * - * @param BaseField $field The field to extract. - * @param integer $pageIndex The page index to extract, begins at 0. - * @param integer $index The index to use for naming the extracted image. - * @param string $filename The output filename. - * @param string $format The output format. - * - * @return null|ExtractedImage The extracted image, or null if the field does not have valid position data. - * - * @throws MindeeGeometryException Throws if a field does not contain positional data. - */ - public function extractImage( - BaseField $field, - int $pageIndex, - int $index, - string $filename, - string $format - ): ?ExtractedImage { - $polygon = null; - - if (!empty($field->polygon)) { - $polygon = $field->polygon; - } elseif (!empty($field->boundingBox)) { - $polygon = $field->boundingBox; - } elseif (!empty($field->quadrangle)) { - $polygon = $field->quadrangle; - } elseif (!empty($field->rectangle)) { - $polygon = $field->rectangle; - } - - if (null === $polygon) { - throw new MindeeGeometryException( - 'Provided field has no valid position data.', - ErrorCode::GEOMETRIC_OPERATION_FAILED - ); - } - - return $this->extractPolygonFromPage($polygon, $pageIndex, $index, $filename, $format); - } /** * Getter for the local input source. @@ -262,33 +205,6 @@ public function getInputSource(): LocalInputSource return $this->inputSource; } - /** - * Extracts images from a page. - * - * @param array> $fields List of Fields to extract. - * @param integer $pageIndex The page index to extract, begins at 0. - * @param string $outputName Name of the created file. - * @param string $format The output format. - * - * @return array An array of created images - */ - protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array - { - $extractedImages = []; - - $i = 0; - foreach ($fields as $field) { - $filename = sprintf('%s_page%d-%d.%s', $outputName, $pageIndex, $i, $format); - $extractedImage = $this->extractImage($field, $pageIndex, $i, $filename, $format); - if (null !== $extractedImage) { - $extractedImages[] = $extractedImage; - } - ++$i; - } - - return $extractedImages; - } - /** * Extracts an image from a set of coordinates. * diff --git a/src/Pdf/PdfExtractor.php b/src/Pdf/PdfExtractor.php index d819bda9..7c8991a2 100644 --- a/src/Pdf/PdfExtractor.php +++ b/src/Pdf/PdfExtractor.php @@ -10,7 +10,6 @@ use Mindee\Dependency\DependencyChecker; use Mindee\Error\MindeePdfException; use Mindee\Input\LocalInputSource; -use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1InvoicePageGroups; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException; use setasign\Fpdi\PdfParser\Filter\FilterException; @@ -18,7 +17,6 @@ use setasign\Fpdi\PdfReader\PdfReaderException; use function count; -use function is_array; use function sprintf; /** @@ -39,8 +37,8 @@ class PdfExtractor /** * @param LocalInputSource $localInput Local Input, accepts all compatible formats. * - * @throws MindeePdfException Throws if PDF operations aren't supported, or if the file - * can't be read, respectively. + * @throws MindeePdfException|ImagickException Throws if PDF operations aren't supported, or if the file + * can't be read, respectively. */ public function __construct(LocalInputSource $localInput) { @@ -86,14 +84,14 @@ public function getPageCount(): int /** * Extracts sub-documents from the source document using list of page indexes. * - * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * @param array> $pageIndexes List of sub-lists of pages to keep. * * @return ExtractedPdf[] list of extracted documents * * @throws MindeePdfException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. * @throws InvalidArgumentException Throws if invalid indexes are provided. */ - public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes): array + public function extractSubDocuments(array $pageIndexes): array { $extractedPdfs = []; @@ -141,58 +139,17 @@ public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pa /** * Extracts invoices as complete PDFs from the document. * - * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * @param array> $pageIndexes List of sub-lists of pages to keep. * @param boolean $strict Whether to trust confidence scores or not. * * @return ExtractedPdf[] a list of extracted invoices */ - public function extractInvoices(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes, bool $strict = false): array + public function extractInvoices(array $pageIndexes, bool $strict = false): array { if (empty($pageIndexes)) { return []; } - if (!$strict) { - $indexes = array_map(static fn($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); - - return $this->extractSubDocuments($indexes); - } - if (is_array($pageIndexes[0])) { - return $this->extractSubDocuments($pageIndexes); - } - - $correctPageIndexes = []; - $currentList = []; - $previousConfidence = null; - - $i = 0; - foreach ($pageIndexes as $pageIndex) { - $confidence = $pageIndex->confidence; - $pageList = $pageIndex->pageIndexes; - - if ($confidence >= 0.5 && null === $previousConfidence) { - $currentList = $pageList; - } elseif ($confidence >= 0.5 && $i !== count($pageIndexes) - 1) { - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - $currentList = $pageList; - } elseif ($confidence < 0.5 && $i === count($pageIndexes) - 1) { - $currentList = array_merge($currentList, $pageList); - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - } else { - if (!empty($currentList)) { - $correctPageIndexes[] = $currentList; - } - $correctPageIndexes[] = $pageList; - } - - $previousConfidence = $confidence; - ++$i; - } - - return $this->extractSubDocuments($correctPageIndexes); + return $this->extractSubDocuments($pageIndexes); } /** diff --git a/src/V1/Client.php b/src/V1/Client.php index 21b8a02a..a5fdc433 100644 --- a/src/V1/Client.php +++ b/src/V1/Client.php @@ -16,14 +16,14 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeException; -use Mindee\Error\V1\MindeeV1ClientException; -use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\LocalResponse; use Mindee\Input\PageOptions; use Mindee\V1\ClientOptions\PredictMethodOptions; use Mindee\V1\ClientOptions\WorkflowOptions; +use Mindee\V1\Error\MindeeV1ClientException; +use Mindee\V1\Error\MindeeV1HttpException; use Mindee\V1\Http\Endpoint; use Mindee\V1\Http\MindeeApi; use Mindee\V1\Http\MindeeWorkflowApi; diff --git a/src/Error/V1/MindeeV1ClientException.php b/src/V1/Error/MindeeV1ClientException.php similarity index 89% rename from src/Error/V1/MindeeV1ClientException.php rename to src/V1/Error/MindeeV1ClientException.php index 2eba70f6..febb5c02 100644 --- a/src/Error/V1/MindeeV1ClientException.php +++ b/src/V1/Error/MindeeV1ClientException.php @@ -7,7 +7,7 @@ * Mindee Client Exceptions. */ -namespace Mindee\Error\V1; +namespace Mindee\V1\Error; use Mindee\Error\MindeeException; diff --git a/src/Error/V1/MindeeV1HttpException.php b/src/V1/Error/MindeeV1HttpException.php similarity index 99% rename from src/Error/V1/MindeeV1HttpException.php rename to src/V1/Error/MindeeV1HttpException.php index 383511ca..448800f1 100644 --- a/src/Error/V1/MindeeV1HttpException.php +++ b/src/V1/Error/MindeeV1HttpException.php @@ -7,7 +7,7 @@ * Mindee HTTP Exceptions. */ -namespace Mindee\Error\V1; +namespace Mindee\V1\Error; use Mindee\Error\ErrorCode; use Mindee\Error\MindeeException; diff --git a/src/V1/Image/ImageExtractor.php b/src/V1/Image/ImageExtractor.php index aa8a88d7..9a71af84 100644 --- a/src/V1/Image/ImageExtractor.php +++ b/src/V1/Image/ImageExtractor.php @@ -4,9 +4,102 @@ namespace Mindee\V1\Image; +use Mindee\Error\ErrorCode; +use Mindee\Error\MindeeGeometryException; +use Mindee\Geometry\Polygon; +use Mindee\Image\ExtractedImage; use Mindee\Image\ImageExtractor as BaseImageExtractor; +use Mindee\V1\Parsing\Standard\BaseField; + +use function sprintf; /** * Wrapper class for V1 of the BaseImageExtractor. */ -class ImageExtractor extends BaseImageExtractor {} +class ImageExtractor extends BaseImageExtractor +{ + /** + * Extract multiple images on a given page from a list of fields having position data. + * + * @param array> $fields List of Fields to extract. + * @param integer $pageIndex The page index to extract, begins at 0. + * @param null|string $outputName The base output filename, must have an image extension. + * + * @return array a list of extracted images + */ + public function extractImagesFromPage(array $fields, int $pageIndex, ?string $outputName = null): array + { + $outputName ??= $this->filename; + return $this->extractFromPage($fields, $pageIndex, $outputName); + } + + /** + * Extracts a single image from a Position field. + * + * @param BaseField $field The field to extract. + * @param integer $pageIndex The page index to extract, begins at 0. + * @param integer $index The index to use for naming the extracted image. + * @param string $filename The output filename. + * @param string $format The output format. + * + * @return null|ExtractedImage The extracted image, or null if the field does not have valid position data. + * + * @throws MindeeGeometryException Throws if a field does not contain positional data. + */ + public function extractImage( + BaseField $field, + int $pageIndex, + int $index, + string $filename, + string $format + ): ?ExtractedImage { + $polygon = null; + + if (!empty($field->polygon)) { + $polygon = $field->polygon; + } elseif (!empty($field->boundingBox)) { + $polygon = $field->boundingBox; + } elseif (!empty($field->quadrangle)) { + $polygon = $field->quadrangle; + } elseif (!empty($field->rectangle)) { + $polygon = $field->rectangle; + } + + if (null === $polygon) { + throw new MindeeGeometryException( + 'Provided field has no valid position data.', + ErrorCode::GEOMETRIC_OPERATION_FAILED + ); + } + + return $this->extractPolygonFromPage($polygon, $pageIndex, $index, $filename, $format); + } + + /** + * Extracts images from a page. + * + * @param array> $fields List of Fields to extract. + * @param integer $pageIndex The page index to extract, begins at 0. + * @param string $outputName Name of the created file. + * @param string $format The output format. + * + * @return array An array of created images + */ + protected function extractFromPage(array $fields, int $pageIndex, string $outputName, string $format = 'jpg'): array + { + $extractedImages = []; + + $i = 0; + foreach ($fields as $field) { + $filename = sprintf('%s_page%d-%d.%s', $outputName, $pageIndex, $i, $format); + $extractedImage = $this->extractImage($field, $pageIndex, $i, $filename, $format); + if (null !== $extractedImage) { + $extractedImages[] = $extractedImage; + } + ++$i; + } + + return $extractedImages; + } + +} diff --git a/src/V1/Pdf/PdfExtractor.php b/src/V1/Pdf/PdfExtractor.php new file mode 100644 index 00000000..ecdc9df9 --- /dev/null +++ b/src/V1/Pdf/PdfExtractor.php @@ -0,0 +1,95 @@ +>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * + * @return ExtractedPdf[] list of extracted documents + * + * @throws MindeePdfException Throws if FDPF/FPDI wasn't able to handle the pdf during the extraction. + * @throws InvalidArgumentException Throws if invalid indexes are provided. + */ + public function extractSubDocuments(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes): array + { + if (is_array($pageIndexes[0])) { + $indexes = $pageIndexes; + } else { + $indexes = array_map(static fn($pageIndex) => $pageIndex->pageIndexes, (array) $pageIndexes); + } + return parent::extractSubDocuments($indexes); + } + + + /** + * Extracts invoices as complete PDFs from the document. + * + * @param array>|InvoiceSplitterV1InvoicePageGroups $pageIndexes List of sub-lists of pages to keep. + * @param boolean $strict Whether to trust confidence scores or not. + * + * @return ExtractedPdf[] a list of extracted invoices + */ + public function extractInvoices(array|InvoiceSplitterV1InvoicePageGroups $pageIndexes, bool $strict = false): array + { + if (empty($pageIndexes)) { + return []; + } + if (!$strict) { + $indexes = array_map(static fn($invoicePageIndexes) => $invoicePageIndexes->pageIndexes, (array) $pageIndexes); + + return $this->extractSubDocuments($indexes); + } + if (is_array($pageIndexes[0])) { + return parent::extractInvoices($pageIndexes, $strict); + } + + $correctPageIndexes = []; + $currentList = []; + $previousConfidence = null; + + $i = 0; + foreach ($pageIndexes as $pageIndex) { + $confidence = $pageIndex->confidence; + $pageList = $pageIndex->pageIndexes; + + if ($confidence >= 0.5 && null === $previousConfidence) { + $currentList = $pageList; + } elseif ($confidence >= 0.5 && $i !== count($pageIndexes) - 1) { + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + $currentList = $pageList; + } elseif ($confidence < 0.5 && $i === count($pageIndexes) - 1) { + $currentList = array_merge($currentList, $pageList); + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + } else { + if (!empty($currentList)) { + $correctPageIndexes[] = $currentList; + } + $correctPageIndexes[] = $pageList; + } + + $previousConfidence = $confidence; + ++$i; + } + + return $this->extractSubDocuments($correctPageIndexes); + } +} diff --git a/src/Error/V2/MindeeV2HttpException.php b/src/V2/Error/MindeeV2HttpException.php similarity index 97% rename from src/Error/V2/MindeeV2HttpException.php rename to src/V2/Error/MindeeV2HttpException.php index 21be8d06..3fe9c708 100644 --- a/src/Error/V2/MindeeV2HttpException.php +++ b/src/V2/Error/MindeeV2HttpException.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\Error\V2; +namespace Mindee\V2\Error; use Mindee\Error\MindeeException; use Mindee\V2\Parsing\Error\ErrorItem; diff --git a/src/Error/V2/MindeeV2HttpUnknownException.php b/src/V2/Error/MindeeV2HttpUnknownException.php similarity index 96% rename from src/Error/V2/MindeeV2HttpUnknownException.php rename to src/V2/Error/MindeeV2HttpUnknownException.php index 66bc0c84..8ed4ea46 100644 --- a/src/Error/V2/MindeeV2HttpUnknownException.php +++ b/src/V2/Error/MindeeV2HttpUnknownException.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mindee\Error\V2; +namespace Mindee\V2\Error; use Mindee\V2\Parsing\Error\ErrorResponse; diff --git a/src/V2/Http/MindeeApiV2.php b/src/V2/Http/MindeeApiV2.php index 67c24af5..b1efefc4 100644 --- a/src/V2/Http/MindeeApiV2.php +++ b/src/V2/Http/MindeeApiV2.php @@ -13,12 +13,12 @@ use Mindee\Error\ErrorCode; use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeException; -use Mindee\Error\V2\MindeeV2HttpException; -use Mindee\Error\V2\MindeeV2HttpUnknownException; use Mindee\Input\InputSource; use Mindee\Input\LocalInputSource; use Mindee\Input\UrlInputSource; use Mindee\V2\ClientOptions\BaseParameters; +use Mindee\V2\Error\MindeeV2HttpException; +use Mindee\V2\Error\MindeeV2HttpUnknownException; use Mindee\V2\Parsing\Error\ErrorResponse; use Mindee\V2\Parsing\Inference\BaseResponse; use Mindee\V2\Parsing\Job\JobResponse; @@ -30,7 +30,6 @@ use function call_user_func; use function dirname; -use const Mindee\V1\Http\API_KEY_ENV_NAME; use const Mindee\VERSION; // phpcs:disable diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 262dd542..01910820 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -5,13 +5,13 @@ use Mindee\ClientOptions\PollingOptions; use Mindee\Error\MindeeApiException; use Mindee\Error\MindeeMimeTypeException; -use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\LocalResponse; use Mindee\Input\PageOptions; use Mindee\Input\PathInput; use Mindee\Input\UrlInputSource; use Mindee\V1\Client; use Mindee\V1\ClientOptions\PredictMethodOptions; +use Mindee\V1\Error\MindeeV1HttpException; use Mindee\V1\Product\Generated\GeneratedV1; use Mindee\V1\Product\Invoice\InvoiceV4; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; diff --git a/tests/V1/Error/MindeeHttpExceptionTest.php b/tests/V1/Error/MindeeHttpExceptionTest.php index e5db2bc3..de85d894 100644 --- a/tests/V1/Error/MindeeHttpExceptionTest.php +++ b/tests/V1/Error/MindeeHttpExceptionTest.php @@ -4,9 +4,9 @@ namespace V1\Error; -use Mindee\Error\V1\MindeeV1HttpException; use Mindee\Input\PathInput; use Mindee\V1\Client; +use Mindee\V1\Error\MindeeV1HttpException; use Mindee\V1\Product\Invoice\InvoiceV4; use PHPUnit\Framework\TestCase; use TestingUtilities; diff --git a/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php index 6d52da49..dcc932ff 100644 --- a/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php +++ b/tests/V1/Image/InvoiceSplitterAutoExtractionTestFunctional.php @@ -5,7 +5,7 @@ namespace V1\Image; use Mindee\Input\PathInput; -use Mindee\Pdf\PdfExtractor; +use Mindee\V1\Pdf\PdfExtractor; use Mindee\V1\Client; use Mindee\V1\Parsing\Common\Document; use Mindee\V1\Product\Invoice\InvoiceV4; diff --git a/tests/V1/Pdf/PdfExtractorTest.php b/tests/V1/Pdf/PdfExtractorTest.php index f9858b16..653b21d8 100644 --- a/tests/V1/Pdf/PdfExtractorTest.php +++ b/tests/V1/Pdf/PdfExtractorTest.php @@ -6,7 +6,7 @@ use Mindee\Input\LocalResponse; use Mindee\Input\PathInput; -use Mindee\Pdf\PdfExtractor; +use Mindee\V1\Pdf\PdfExtractor; use Mindee\V1\Client; use Mindee\V1\Product\InvoiceSplitter\InvoiceSplitterV1; use PHPUnit\Framework\TestCase; diff --git a/tests/V2/ClientV2TestFunctional.php b/tests/V2/ClientV2TestFunctional.php index 578ea599..ea23eb7d 100644 --- a/tests/V2/ClientV2TestFunctional.php +++ b/tests/V2/ClientV2TestFunctional.php @@ -4,10 +4,10 @@ namespace V2; -use Mindee\Error\V2\MindeeV2HttpException; use Mindee\Input\PathInput; use Mindee\Input\UrlInputSource; use Mindee\V2\Client; +use Mindee\V2\Error\MindeeV2HttpException; use Mindee\V2\Product\Extraction\ExtractionResponse; use Mindee\V2\Product\Extraction\Params\ExtractionParameters; use PHPUnit\Framework\TestCase; From c8eb3299dc63bdb2b57e4bda198de8708ed4d749 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 29 May 2026 10:09:45 +0200 Subject: [PATCH 11/11] :sparkles: add crop and split accessors on V2 products themselves (#195) --- src/V2/FileOperations/Crop.php | 6 +++--- src/V2/FileOperations/Split.php | 7 +++++-- src/V2/Product/Crop/CropItem.php | 13 +++++++++++++ src/V2/Product/Crop/CropResult.php | 13 +++++++++++++ src/V2/Product/Split/SplitRange.php | 15 +++++++++++++++ src/V2/Product/Split/SplitResult.php | 16 ++++++++++++++++ tests/V2/FileOperations/CropFunctional.php | 9 +++++---- tests/V2/FileOperations/CropTest.php | 4 ++-- tests/V2/FileOperations/SplitFunctional.php | 12 ++++++++---- tests/V2/FileOperations/SplitTest.php | 4 ++-- 10 files changed, 82 insertions(+), 17 deletions(-) diff --git a/src/V2/FileOperations/Crop.php b/src/V2/FileOperations/Crop.php index 2004e009..ccc3514f 100644 --- a/src/V2/FileOperations/Crop.php +++ b/src/V2/FileOperations/Crop.php @@ -28,9 +28,9 @@ public function __construct(private readonly LocalInputSource $localInput) {} * * @return ExtractedImage extracted image */ - public function extractCrop(CropItem $crop): ExtractedImage + public function extractSingleCrop(CropItem $crop): ExtractedImage { - return $this->extractCrops([$crop])[0]; + return $this->extractMultipleCrops([$crop])[0]; } /** @@ -39,7 +39,7 @@ public function extractCrop(CropItem $crop): ExtractedImage * @param CropItem[] $crops List of crops to extract. * @return CropFiles list of extracted files */ - public function extractCrops(array $crops): CropFiles + public function extractMultipleCrops(array $crops): CropFiles { $imageExtractor = new ImageExtractor($this->localInput); $extractedImages = []; diff --git a/src/V2/FileOperations/Split.php b/src/V2/FileOperations/Split.php index eff71136..8622e0bf 100644 --- a/src/V2/FileOperations/Split.php +++ b/src/V2/FileOperations/Split.php @@ -8,6 +8,7 @@ use Mindee\Input\LocalInputSource; use Mindee\Pdf\ExtractedPdf; use Mindee\Pdf\PdfExtractor; +use ImagickException; /** * V2 Split operation. @@ -44,10 +45,11 @@ public static function expandRange(int $start, int $end): array * @param int[] $split Split range to extract. * * @return ExtractedPdf 2D array of extracted pages + * @throws ImagickException Throws if the image can't be processed. */ public function extractSingleSplit(array $split): ExtractedPdf { - return $this->extractSplits([$split])[0]; + return $this->extractMultipleSplits([$split])[0]; } /** @@ -56,8 +58,9 @@ public function extractSingleSplit(array $split): ExtractedPdf * @param int[][] $splits List of split ranges to extract. * * @return SplitFiles list of extracted files + * @throws ImagickException Throws if the image can't be processed. */ - public function extractSplits(array $splits): SplitFiles + public function extractMultipleSplits(array $splits): SplitFiles { $pdfExtractor = new PdfExtractor($this->localInput); $expandedPageIndexes = array_map(static fn(array $split) => self::expandRange($split[0], $split[1]), $splits); diff --git a/src/V2/Product/Crop/CropItem.php b/src/V2/Product/Crop/CropItem.php index eba0759c..49c5622a 100644 --- a/src/V2/Product/Crop/CropItem.php +++ b/src/V2/Product/Crop/CropItem.php @@ -4,6 +4,9 @@ namespace Mindee\V2\Product\Crop; +use Mindee\Image\ExtractedImage; +use Mindee\Input\LocalInputSource; +use Mindee\V2\FileOperations\Crop; use Mindee\V2\Parsing\Inference\Field\FieldLocation; use Mindee\V2\Product\Extraction\ExtractionResponse; use Stringable; @@ -45,4 +48,14 @@ public function __toString(): string { return "* :Location: $this->location\n :Object Type: $this->objectType"; } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the crop. + * @return ExtractedImage The extracted image. + */ + public function extractFromInputSource(LocalInputSource $inputSource): ExtractedImage + { + $cropper = new Crop($inputSource); + return $cropper->extractSingleCrop($this); + } } diff --git a/src/V2/Product/Crop/CropResult.php b/src/V2/Product/Crop/CropResult.php index 0e8bdc18..ac6289e7 100644 --- a/src/V2/Product/Crop/CropResult.php +++ b/src/V2/Product/Crop/CropResult.php @@ -4,6 +4,9 @@ namespace Mindee\V2\Product\Crop; +use Mindee\Input\LocalInputSource; +use Mindee\V2\FileOperations\Crop; +use Mindee\V2\FileOperations\CropFiles; use Stringable; /** @@ -31,4 +34,14 @@ public function __toString(): string { return "Crops\n=====\n" . implode("\n", $this->crops); } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the pages. + * @return CropFiles The extracted PDFs. + */ + public function extractFromInputSource(LocalInputSource $inputSource): CropFiles + { + $cropper = new Crop($inputSource); + return $cropper->extractMultipleCrops($this->crops); + } } diff --git a/src/V2/Product/Split/SplitRange.php b/src/V2/Product/Split/SplitRange.php index 96fca6b0..e89fec53 100644 --- a/src/V2/Product/Split/SplitRange.php +++ b/src/V2/Product/Split/SplitRange.php @@ -4,6 +4,9 @@ namespace Mindee\V2\Product\Split; +use Mindee\Input\LocalInputSource; +use Mindee\Pdf\ExtractedPdf; +use Mindee\V2\FileOperations\Split; use Mindee\V2\Product\Extraction\ExtractionResponse; use Stringable; @@ -49,4 +52,16 @@ public function __toString(): string return "* :Page Range: $pageRangeStr\n :Document Type: $this->documentType"; } + + /** + * Extracts a single page from the input source based on the specified page range. + * + * @param LocalInputSource $inputSource The input source from which to extract the page. + * @return ExtractedPdf The extracted PDF. + */ + public function extractFromInputSource(LocalInputSource $inputSource): ExtractedPdf + { + $splitter = new Split($inputSource); + return $splitter->extractSingleSplit($this->pageRange); + } } diff --git a/src/V2/Product/Split/SplitResult.php b/src/V2/Product/Split/SplitResult.php index 403d7944..a34919e3 100644 --- a/src/V2/Product/Split/SplitResult.php +++ b/src/V2/Product/Split/SplitResult.php @@ -4,7 +4,12 @@ namespace Mindee\V2\Product\Split; +use Mindee\Input\LocalInputSource; +use Mindee\Pdf\ExtractedPdf; +use Mindee\V2\FileOperations\Split; +use Mindee\V2\FileOperations\SplitFiles; use Stringable; +use ImagickException; /** * Result of a split utility inference. @@ -33,4 +38,15 @@ public function __toString(): string return "Splits\n======\n$splitsStr"; } + + /** + * @param LocalInputSource $inputSource The input source from which to extract the pages. + * @return SplitFiles The extracted PDFs. + * @throws ImagickException Throws if the image can't be processed. + */ + public function extractFromInputSource(LocalInputSource $inputSource): SplitFiles + { + $splitter = new Split($inputSource); + return $splitter->extractMultipleSplits(array_map(static fn(SplitRange $split) => $split->pageRange, $this->splits)); + } } diff --git a/tests/V2/FileOperations/CropFunctional.php b/tests/V2/FileOperations/CropFunctional.php index d0ce95b8..a57b26bd 100644 --- a/tests/V2/FileOperations/CropFunctional.php +++ b/tests/V2/FileOperations/CropFunctional.php @@ -67,9 +67,10 @@ public function testExtractCropsFromImageCorrectly(): void self::assertNotNull($response); self::assertCount(2, $response->inference->result->crops); - - $cropOperation = new Crop($inputSource); - $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); + self::assertInstanceOf(CropResponse::class, $response); + $extractedImages = $response->inference->result->extractFromInputSource($inputSource); + $extractedImage0 = $response->inference->result->crops[0]->extractFromInputSource($inputSource); + self::assertEquals($extractedImage0, $extractedImages[0]); self::assertCount(2, $extractedImages); self::assertSame('default_sample.jpg_page0-0.jpg', $extractedImages[0]->filename); @@ -100,7 +101,7 @@ public function testExtractCropsFromEachPdfPageCorrectly(): void $response = $this->client->enqueueAndGetResult(CropResponse::class, $inputSource, $cropParams); $cropOperation = new Crop($inputSource); - $extractedImages = $cropOperation->extractCrops($response->inference->result->crops); + $extractedImages = $cropOperation->extractMultipleCrops($response->inference->result->crops); self::assertCount(5, $extractedImages); self::assertSame('multipage_sample.pdf_page0-0.jpg', $extractedImages[0]->filename); diff --git a/tests/V2/FileOperations/CropTest.php b/tests/V2/FileOperations/CropTest.php index 0f6e1022..8b934721 100644 --- a/tests/V2/FileOperations/CropTest.php +++ b/tests/V2/FileOperations/CropTest.php @@ -28,7 +28,7 @@ public function testProcessesSinglePageCropSplitCorrectly(): void $doc = $localResponse->deserializeResponse(CropResponse::class); $cropOperation = new Crop($inputSample); - $extractedCrops = $cropOperation->extractCrops($doc->inference->result->crops); + $extractedCrops = $cropOperation->extractMultipleCrops($doc->inference->result->crops); self::assertCount(1, $extractedCrops); @@ -49,7 +49,7 @@ public function testProcessesMultiPageReceiptSplitCorrectly(): void $doc = $localResponse->deserializeResponse(CropResponse::class); $cropOperation = new Crop($inputSample); - $extractedCrops = $cropOperation->extractCrops($doc->inference->result->crops); + $extractedCrops = $cropOperation->extractMultipleCrops($doc->inference->result->crops); self::assertCount(2, $extractedCrops); diff --git a/tests/V2/FileOperations/SplitFunctional.php b/tests/V2/FileOperations/SplitFunctional.php index 16ca313e..d3b7de4a 100644 --- a/tests/V2/FileOperations/SplitFunctional.php +++ b/tests/V2/FileOperations/SplitFunctional.php @@ -13,6 +13,7 @@ use Mindee\V2\Product\Split\SplitResponse; use PHPUnit\Framework\TestCase; use TestingUtilities; +use ImagickException; use function count; use function sprintf; @@ -60,6 +61,9 @@ private function checkFindocReturn(ExtractionResponse $findocResponse): void self::assertGreaterThan(0, $totalAmount->value); } + /** + * @throws ImagickException + */ public function testExtractSplitsFromPdfCorrectly(): void { $inputSource = new PathInput(TestingUtilities::getV2ProductDir() . '/split/default_sample.pdf'); @@ -70,10 +74,10 @@ public function testExtractSplitsFromPdfCorrectly(): void self::assertNotNull($response); self::assertCount(2, $response->inference->result->splits); - $splitOperation = new Split($inputSource); - $extractedSplits = $splitOperation->extractSplits( - array_map(static fn($s) => $s->pageRange, $response->inference->result->splits) - ); + self::assertInstanceof(SplitResponse::class, $response); + $extractedSplits = $response->inference->result->extractFromInputSource($inputSource); + $extractedSplit0 = $response->inference->result->splits[0]->extractFromInputSource($inputSource); + self::assertEquals($extractedSplit0, $extractedSplits[0]); self::assertCount(2, $extractedSplits); self::assertSame('default_sample_001-001.pdf', $extractedSplits[0]->filename); diff --git a/tests/V2/FileOperations/SplitTest.php b/tests/V2/FileOperations/SplitTest.php index 5591c26a..feceaa17 100644 --- a/tests/V2/FileOperations/SplitTest.php +++ b/tests/V2/FileOperations/SplitTest.php @@ -31,7 +31,7 @@ public function testProcessesSinglePageSplitCorrectly(): void $splitOperation = new Split($inputSample); $splits = $doc->inference->result->splits; - $extractedSplits = $splitOperation->extractSplits(array_map(static fn($s) => $s->pageRange, $splits)); + $extractedSplits = $splitOperation->extractMultipleSplits(array_map(static fn($s) => $s->pageRange, $splits)); self::assertCount(1, $extractedSplits); @@ -47,7 +47,7 @@ public function testProcessesMultiPageReceiptSplitCorrectly(): void $splitOperation = new Split($inputSample); $splits = $doc->inference->result->splits; - $extractedSplits = $splitOperation->extractSplits(array_map(static fn($s) => $s->pageRange, $splits)); + $extractedSplits = $splitOperation->extractMultipleSplits(array_map(static fn($s) => $s->pageRange, $splits)); self::assertCount(3, $extractedSplits);