|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LeKoala\Encrypt; |
|
4
|
|
|
|
|
5
|
|
|
use SilverStripe\Core\Injector\Injector; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* This trait helps to override the default getField method in order to return |
|
9
|
|
|
* the value of a field directly instead of the db object instance |
|
10
|
|
|
* |
|
11
|
|
|
* Simply define this in your code |
|
12
|
|
|
* |
|
13
|
|
|
* public function getField($field) |
|
14
|
|
|
* { |
|
15
|
|
|
* return $this->getEncryptedField($field); |
|
16
|
|
|
* } |
|
17
|
|
|
* |
|
18
|
|
|
* public function setField($fieldName, $val) |
|
19
|
|
|
* { |
|
20
|
|
|
* return $this->setEncryptedField($fieldName, $val); |
|
21
|
|
|
* } |
|
22
|
|
|
*/ |
|
23
|
|
|
trait HasEncryptedFields |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Extend getField to support retrieving encrypted value transparently |
|
27
|
|
|
* @param string $field The name of the field |
|
28
|
|
|
* @return mixed The field value |
|
29
|
|
|
*/ |
|
30
|
|
|
public function getEncryptedField($field) |
|
31
|
|
|
{ |
|
32
|
|
|
// If it's an encrypted field |
|
33
|
|
|
if ($this->hasEncryptedField($field)) { |
|
34
|
|
|
$fieldObj = $this->dbObject($field); |
|
|
|
|
|
|
35
|
|
|
// Set decrypted value directly on the record for later use |
|
36
|
|
|
$this->record[$field] = $fieldObj->getValue(); |
|
|
|
|
|
|
37
|
|
|
} |
|
38
|
|
|
return parent::getField($field); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Extend setField to support setting encrypted value transparently |
|
43
|
|
|
* @param string $field |
|
44
|
|
|
* @param mixed $val |
|
45
|
|
|
* @return $this |
|
46
|
|
|
*/ |
|
47
|
|
|
public function setEncryptedField($field, $val) |
|
48
|
|
|
{ |
|
49
|
|
|
// If it's an encrypted field |
|
50
|
|
|
if ($this->hasEncryptedField($field) && $val && is_scalar($val)) { |
|
51
|
|
|
$schema = static::getSchema(); |
|
52
|
|
|
|
|
53
|
|
|
// In case of composite fields, return the DBField object |
|
54
|
|
|
if ($schema->compositeField(static::class, $field)) { |
|
55
|
|
|
$fieldObj = $this->dbObject($field); |
|
56
|
|
|
$fieldObj->setValue($val); |
|
57
|
|
|
// Proceed with DBField instance, that will call saveInto |
|
58
|
|
|
// and call this method again for distinct fields |
|
59
|
|
|
$val = $fieldObj; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
return parent::setField($field, $val); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param string $field |
|
67
|
|
|
* @return boolean |
|
68
|
|
|
*/ |
|
69
|
|
|
public function hasEncryptedField($field) |
|
70
|
|
|
{ |
|
71
|
|
|
return EncryptHelper::isEncryptedField(get_class($this), $field); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|