1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kablanfatih\Encryption; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Crypt; |
6
|
|
|
|
7
|
|
|
trait Encryptable |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Determine if the field is JSON. |
11
|
|
|
* |
12
|
|
|
* @param $json |
13
|
|
|
* @return bool |
14
|
|
|
*/ |
15
|
|
|
public function is_json($json): bool |
16
|
|
|
{ |
17
|
|
|
$ob = json_decode($json); |
18
|
|
|
|
19
|
|
|
return $ob === null ? false : true; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Decrypt field. |
24
|
|
|
* |
25
|
|
|
* @param $value |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
|
|
public function decryptField($value) |
29
|
|
|
{ |
30
|
|
|
$decrypt = $this->decryptValue($value); |
31
|
|
|
|
32
|
|
|
if (!is_array($decrypt) && $this->is_json($decrypt)) |
33
|
|
|
$decrypt = json_decode($decrypt); |
34
|
|
|
|
35
|
|
|
return $decrypt; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Decrypt the column value if it is in the encrypted array. |
40
|
|
|
* |
41
|
|
|
* @param $key |
42
|
|
|
* |
43
|
|
|
* @return mixed |
44
|
|
|
*/ |
45
|
|
|
public function getAttribute($key) |
46
|
|
|
{ |
47
|
|
|
$value = parent::getAttribute($key); |
48
|
|
|
if (in_array($key, $this->encrypted ?? [])) { |
49
|
|
|
$value = $this->decryptField($value); |
50
|
|
|
} |
51
|
|
|
return $value; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Decrypts a value only if it is not null and not empty. |
56
|
|
|
* |
57
|
|
|
* @param $value |
58
|
|
|
* |
59
|
|
|
* @return mixed |
60
|
|
|
*/ |
61
|
|
|
protected function decryptValue($value) |
62
|
|
|
{ |
63
|
|
|
if (config('encryption.encrypt') && $value !== null && !empty($value)) { |
64
|
|
|
return Crypt::decrypt($value); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $value; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Set the value, encrypting it if it is in the encrypted array. |
72
|
|
|
* |
73
|
|
|
* @param $key |
74
|
|
|
* @param $value |
75
|
|
|
* |
76
|
|
|
* @return |
77
|
|
|
*/ |
78
|
|
|
public function setAttribute($key, $value) |
79
|
|
|
{ |
80
|
|
|
if (config('encryption.encrypt')) { |
81
|
|
|
if ($value !== null && in_array($key, $this->encrypted ?? [])) { |
82
|
|
|
$value = Crypt::encrypt($value); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
return parent::setAttribute($key, $value); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* Retrieves all values and decrypts them if needed. |
90
|
|
|
* |
91
|
|
|
* @return mixed |
92
|
|
|
*/ |
93
|
|
|
public function attributesToArray() |
94
|
|
|
{ |
95
|
|
|
$attributes = parent::attributesToArray(); |
96
|
|
|
|
97
|
|
|
if (!config('encryption.encrypt')) |
98
|
|
|
return $attributes; |
99
|
|
|
|
100
|
|
|
foreach ($this->encrypted ?? [] as $key) { |
101
|
|
|
if (isset($attributes[$key])) { |
102
|
|
|
$attributes[$key] = $this->decryptValue($attributes[$key]); |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
return $attributes; |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|