diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 95aa009f..fbe85724 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -21,6 +21,7 @@ recepciĆ³n de pagos, page 22* it is required that `pagos10:Pago@Monto` must be in an interval. - Fix samples from `tests/assets/pagos/` since new validation make it fail. - Rename validation class `MontoGreaterOrEqualThanSumOfDocuments` to `MontoBetweenIntervalSumOfDocuments` +- Refactor `CfdiUtils\Certificado\Certificado` extracting obtain public key routine to an internal method. - Create tests for trait `CalculateDocumentAmountTrait`. diff --git a/src/CfdiUtils/Certificado/Certificado.php b/src/CfdiUtils/Certificado/Certificado.php index cb2103a1..a1e3f4c1 100644 --- a/src/CfdiUtils/Certificado/Certificado.php +++ b/src/CfdiUtils/Certificado/Certificado.php @@ -53,21 +53,7 @@ public function __construct(string $filename) } // get the public key - $pubkey = false; - $pubData = false; - try { - $pubkey = openssl_get_publickey($contents); - if (is_resource($pubkey)) { - $pubData = openssl_pkey_get_details($pubkey); - } - } finally { - if (is_resource($pubkey)) { - openssl_free_key($pubkey); - } - } - if (false === $pubData) { - $pubData = ['key' => '']; - } + $pubKey = $this->obtainPubKeyFromContents($contents); // set all the values $this->rfc = (string) strstr($data['subject']['x500UniqueIdentifier'] . ' ', ' ', true); @@ -84,7 +70,7 @@ public function __construct(string $filename) $this->serial = $serial->asAscii(); $this->validFrom = $data['validFrom_time_t']; $this->validTo = $data['validTo_time_t']; - $this->pubkey = $pubData['key']; + $this->pubkey = $pubKey; $this->pemContents = $contents; $this->filename = $filename; } @@ -206,4 +192,24 @@ protected function changeCerToPem(string $contents): string . chunk_split(base64_encode($contents), 64, PHP_EOL) . '-----END CERTIFICATE-----' . PHP_EOL; } + + protected function obtainPubKeyFromContents(string $contents): string + { + try { + $pubkey = openssl_get_publickey($contents); + if (! is_resource($pubkey)) { + return ''; + } + $pubData = openssl_pkey_get_details($pubkey); + if (false === $pubData) { + return ''; + } + return $pubData['key'] ?? ''; + } finally { + // close public key even if the flow is throw an exception + if (isset($pubkey) && is_resource($pubkey)) { + openssl_free_key($pubkey); + } + } + } }