Completed
Push — master ( ba89b0...71c4cf )
by Tony Karavasilev (Тони
17:29
created

FileEncryptionTrait::validateFileNamePath()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.2222
cc 6
nc 4
nop 1
crap 6
1
<?php
2
3
/**
4
 * Trait implementation of file encryption/decryption for asymmetric/symmetric encryption algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageEncryption;
8
9
use \CryptoManana\Core\Interfaces\MessageEncryption\FileEncryptionInterface as FileEncryptionSpecification;
10
use \CryptoManana\Core\Interfaces\MessageEncryption\DataEncryptionInterface as DataEncryptionSpecification;
11
use \CryptoManana\Core\Traits\CommonValidations\FileNameValidationTrait as ValidateFileNames;
12
13
/**
14
 * Trait FileEncryptionTrait - Reusable implementation of `FileEncryptionInterface`.
15
 *
16
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\FileEncryptionInterface The abstract specification.
17
 *
18
 * @package CryptoManana\Core\Traits\MessageEncryption
19
 *
20
 * @mixin FileEncryptionSpecification
21
 * @mixin DataEncryptionSpecification
22
 * @mixin ValidateFileNames
23
 */
24
trait FileEncryptionTrait
25
{
26
    /**
27
     * File name and path validations.
28
     *
29
     * {@internal Reusable implementation of the common file name validation. }}
30
     */
31
    use ValidateFileNames;
32
33
    /**
34
     * Encrypts the content of a given plain file.
35
     *
36
     * @param string $filename The full path and name of the file for encryption.
37
     *
38
     * @return string The encrypted file content.
39
     * @throws \Exception Validation errors.
40
     */
41 60
    public function encryptFile($filename)
42
    {
43 60
        if (!is_string($filename)) {
44 20
            throw new \InvalidArgumentException('The file path must be of type string.');
45
        }
46
47 40
        $this->validateFileNamePath($filename);
48
49 20
        return $this->encryptData(file_get_contents($filename));
50
    }
51
52
    /**
53
     * Decrypts the content of a given encrypted file.
54
     *
55
     * @param string $filename The full path and name of the file for encryption.
56
     *
57
     * @return string The decrypted file content.
58
     * @throws \Exception Validation errors.
59
     */
60 60
    public function decryptFile($filename)
61
    {
62 60
        if (!is_string($filename)) {
63 20
            throw new \InvalidArgumentException('The file path must be of type string.');
64
        }
65
66 40
        $this->validateFileNamePath($filename);
67
68 20
        return $this->decryptData(file_get_contents($filename));
69
    }
70
}
71