Completed
Push — feature-184 ( 21cae3 )
by Fèvre
06:02
created

EncryptedSecurityType::toStatement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
namespace App\Database\Type;
3
4
use Cake\Core\Configure;
5
use Cake\Database\Driver;
6
use Cake\Database\Type;
7
use Cake\Utility\Security;
8
use PDO;
9
10
class EncryptedSecurityType extends Type
11
{
12
    /**
13
     * Convert string values to PHP integers
14
     *
15
     * @param mixed $value The value to convert.
16
     * @param Driver $driver The driver instance to convert with.
17
     * @return string|null
18
     */
19
    public function toPHP($value, Driver $driver)
20
    {
21
        if ($value === null || empty($value)) {
22
            return null;
23
        }
24
        return Security::decrypt(base64_decode($value), Configure::read('Security.key'));
25
    }
26
27
    /**
28
     * Marshalls request data into PHP strings.
29
     *
30
     * @param mixed $value The value to convert.
31
     * @return mixed Converted value.
32
     */
33
    public function marshal($value)
34
    {
35
        if ($value === null) {
36
            return $value;
37
        }
38
        return base64_encode(Security::encrypt($value, Configure::read('Security.key')));
39
    }
40
41
    /**
42
     * Convert string data into the database format.
43
     *
44
     * @param mixed $value The value to convert.
45
     * @param Driver $driver The driver instance to convert with.
46
     * @return string|null
47
     */
48
    public function toDatabase($value, Driver $driver)
49
    {
50
        if ($value === null) {
51
            return null;
52
        }
53
        return $value;
54
    }
55
56
    /**
57
     * Get the correct PDO binding type for string data.
58
     *
59
     * @param mixed $value The value being bound.
60
     * @param Driver $driver The driver.
61
     * @return int
62
     */
63
    public function toStatement($value, Driver $driver)
64
    {
65
        if ($value === null) {
66
            return PDO::PARAM_NULL;
67
        }
68
        return PDO::PARAM_STR;
69
    }
70
}
71