1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverStripe\DataObjectAuditor\Extensions; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Core\Config\Configurable; |
6
|
|
|
use SilverStripe\DataObjectAuditor\Models\Audit; |
7
|
|
|
use SilverStripe\DataObjectAuditor\Models\AuditValue; |
8
|
|
|
use SilverStripe\ORM\DataExtension; |
9
|
|
|
use SilverStripe\ORM\DataObject; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class AuditExtension |
13
|
|
|
*/ |
14
|
|
|
class AuditExtension extends DataExtension |
15
|
|
|
{ |
16
|
|
|
use Configurable; |
17
|
|
|
|
18
|
|
|
private static $audit_exclusions = [ |
|
|
|
|
19
|
|
|
Audit::class, |
20
|
|
|
AuditValue::class |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Writes to the audit table after the item was deleted |
25
|
|
|
*/ |
26
|
|
|
public function onAfterDelete() |
27
|
|
|
{ |
28
|
|
|
parent::onAfterDelete(); |
29
|
|
|
$this->createAudit($this->owner->toMap()); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function onAfterWrite() |
33
|
|
|
{ |
34
|
|
|
parent::onAfterWrite(); |
35
|
|
|
$baseChangedFields = $this->owner->getChangedFields(true, DataObject::CHANGE_VALUE); |
36
|
|
|
// A good guestimate is that if baseChangedFields contains an ID column, it's safe to assume |
37
|
|
|
// that it is an INSERT operation and thus shouldn't be audited. |
38
|
|
|
if (in_array('ID', array_keys($baseChangedFields))) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$changedFields = []; |
43
|
|
|
foreach ($baseChangedFields as $key => $val) { |
44
|
|
|
$changedFields[$key] = $val['before']; |
45
|
|
|
} |
46
|
|
|
$this->createAudit($changedFields, 'update'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Writes the requisite Audit and AuditValue entries, provided they're not excluded of course. |
51
|
|
|
* @param array $record |
52
|
|
|
* @param string $mutation |
53
|
|
|
* @throws \SilverStripe\ORM\ValidationException |
54
|
|
|
*/ |
55
|
|
|
protected function createAudit($record, $mutation = 'delete') |
56
|
|
|
{ |
57
|
|
|
$needle = get_class($this->owner); |
58
|
|
|
$hayStack = self::config()->get('audit_exclusions'); |
59
|
|
|
// Early exit on exclusions |
60
|
|
|
if (in_array($needle, $hayStack)) { |
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$auditId = Audit::create()->update([ |
65
|
|
|
Audit::DB_MODEL_NAME => $this->owner->getField('ClassName'), |
66
|
|
|
Audit::DB_MODEL_ID => $this->owner->getField('ID'), |
67
|
|
|
Audit::DB_MUTATION_PEFORMED => $mutation |
68
|
|
|
])->write(); |
69
|
|
|
|
70
|
|
|
foreach ($record as $key => $value) { |
71
|
|
|
AuditValue::create() |
72
|
|
|
->setField(AuditValue::DB_FIELD, $key) |
73
|
|
|
->setField(AuditValue::DB_PREVIOUS_VALUE, $value) |
74
|
|
|
->setField(AuditValue::HAS_ONE_AUDIT_ID, $auditId) |
75
|
|
|
->write(); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
This check marks private properties in classes that are never used. Those properties can be removed.