Skip to content

Commit

Permalink
Implement Decryption Failure Handling
Browse files Browse the repository at this point in the history
  • Loading branch information
IlicMiljan committed Mar 15, 2024
1 parent 58a1b64 commit a535452
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
25 changes: 25 additions & 0 deletions src/Exception/SingleEncryptedAttributeExpected.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace IlicMiljan\SecureProps\Exception;

use RuntimeException;
use Throwable;

class SingleEncryptedAttributeExpected extends RuntimeException implements EncryptionServiceException
{
public function __construct(
private int $count,
?Throwable $previous = null
) {
parent::__construct(
'Each property must be annotated with a single instance of the Encrypted attribute.',
0,
$previous
);
}

public function getCount(): int
{
return $this->count;
}
}
40 changes: 39 additions & 1 deletion src/ObjectEncryptionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
}
}

0 comments on commit a535452

Please sign in to comment.