ObjectEncryptionTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 12
c 1
b 0
f 0
dl 0
loc 42
ccs 12
cts 12
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A encryptObject() 0 9 2
A decryptObject() 0 13 3
1
<?php
2
3
/**
4
 * Trait implementation of object encryption/decryption for asymmetric/symmetric encryption algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageEncryption;
8
9
use CryptoManana\Core\Interfaces\MessageEncryption\ObjectEncryptionInterface as ObjectEncryptionSpecification;
10
use CryptoManana\Core\Interfaces\MessageEncryption\DataEncryptionInterface as DataEncryptionSpecification;
11
12
/**
13
 * Trait ObjectEncryptionTrait - Reusable implementation of `ObjectEncryptionInterface`.
14
 *
15
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\ObjectEncryptionInterface The abstract specification.
16
 *
17
 * @package CryptoManana\Core\Traits\MessageEncryption
18
 *
19
 * @mixin ObjectEncryptionSpecification
20
 * @mixin DataEncryptionSpecification
21
 */
22
trait ObjectEncryptionTrait
23
{
24
    /**
25
     * Encrypts the serialized value of the given object.
26
     *
27
     * @param object|\stdClass $object The object for encryption.
28
     *
29
     * @return string The encrypted serialized object as a string.
30
     * @throws \Exception Validation errors.
31
     */
32 24
    public function encryptObject($object)
33
    {
34 24
        if (is_object($object)) {
35 12
            $object = serialize($object);
36
        } else {
37 12
            throw new \InvalidArgumentException('The data for encryption must be an object instance.');
38
        }
39
40 12
        return $this->encryptData($object);
41
    }
42
43
    /**
44
     * Decrypts the encrypted value of the given object.
45
     *
46
     * @param string $cipherData The encrypted serialized object as a string.
47
     *
48
     * @return object|\stdClass The decrypted and unserialized object.
49
     * @throws \Exception Validation errors.
50
     */
51 36
    public function decryptObject($cipherData)
52
    {
53 36
        if (!is_string($cipherData)) {
54 12
            throw new \InvalidArgumentException('The data for decryption must be a string or a binary string.');
55
        }
56
57 24
        $object = unserialize($this->decryptData($cipherData));
58
59 24
        if (!is_object($object)) {
60 12
            throw new \InvalidArgumentException('The decrypted data must be an object instance.');
61
        }
62
63 12
        return $object;
64
    }
65
}
66