From a535452e078b910688d2f3b087d4d23902e9d198 Mon Sep 17 00:00:00 2001 From: Miljan Ilic Date: Fri, 15 Mar 2024 11:33:03 +0100 Subject: [PATCH] Implement Decryption Failure Handling --- .../SingleEncryptedAttributeExpected.php | 25 ++++++++++++ src/ObjectEncryptionService.php | 40 ++++++++++++++++++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 src/Exception/SingleEncryptedAttributeExpected.php diff --git a/src/Exception/SingleEncryptedAttributeExpected.php b/src/Exception/SingleEncryptedAttributeExpected.php new file mode 100644 index 0000000..0ea4565 --- /dev/null +++ b/src/Exception/SingleEncryptedAttributeExpected.php @@ -0,0 +1,25 @@ +count; + } +} diff --git a/src/ObjectEncryptionService.php b/src/ObjectEncryptionService.php index 1940c27..9362232 100644 --- a/src/ObjectEncryptionService.php +++ b/src/ObjectEncryptionService.php @@ -4,9 +4,12 @@ use IlicMiljan\SecureProps\Attribute\Encrypted; use IlicMiljan\SecureProps\Cipher\Cipher; +use IlicMiljan\SecureProps\Cipher\Exception\FailedDecryptingValue; +use IlicMiljan\SecureProps\Exception\SingleEncryptedAttributeExpected; use IlicMiljan\SecureProps\Exception\ValueMustBeObject; use IlicMiljan\SecureProps\Exception\ValueMustBeString; use IlicMiljan\SecureProps\Reader\ObjectPropertiesReader; +use ReflectionAttribute; use ReflectionProperty; use SensitiveParameter; @@ -80,6 +83,41 @@ private function updatePropertyValue(ReflectionProperty $property, object $objec throw new ValueMustBeString(gettype($currentValue)); } - $property->setValue($object, $callback($currentValue)); + try { + $property->setValue($object, $callback($currentValue)); + } catch (FailedDecryptingValue $e) { + $this->handleDecryptionFailure($object, $property, $e); + } + } + + public function handleDecryptionFailure( + object $object, + ReflectionProperty $property, + FailedDecryptingValue $e, + ): void { + $placeholderValue = $this->getPropertyPlaceholderValue($property); + + if ($placeholderValue === null) { + throw $e; + } + + $property->setValue($object, $placeholderValue); + } + + private function getPropertyPlaceholderValue(ReflectionProperty $property): ?string + { + $encryptedAttributes = $property->getAttributes(Encrypted::class); + + if (count($encryptedAttributes) !== 1) { + throw new SingleEncryptedAttributeExpected(count($encryptedAttributes)); + } + + /** @var ReflectionAttribute $encryptedAttribute */ + $encryptedAttribute = array_pop($encryptedAttributes); + + /** @var Encrypted $encryptedAttributeInstance */ + $encryptedAttributeInstance = $encryptedAttribute->newInstance(); + + return $encryptedAttributeInstance->getPlaceholder(); } }