EditorTrackingExtension::onBeforeWrite()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
namespace LeKoala\CommonExtensions;
4
5
use SilverStripe\Forms\FieldList;
6
use SilverStripe\Security\Member;
7
use SilverStripe\ORM\DataExtension;
8
use SilverStripe\Security\Security;
9
10
/**
11
 * Track who edited what
12
 *
13
 * @property \LeKoala\CommonExtensions\EditorTrackingExtension|\SilverStripe\ORM\DataObject $owner
14
 * @property int $CreatedByID
15
 * @property int $LastEditedByID
16
 * @method \SilverStripe\Security\Member CreatedBy()
17
 * @method \SilverStripe\Security\Member LastEditedBy()
18
 */
19
class EditorTrackingExtension extends DataExtension
20
{
21
    private static $has_one = [
0 ignored issues
show
introduced by
The private property $has_one is not used, and could be removed.
Loading history...
22
        "CreatedBy" => Member::class,
23
        "LastEditedBy" => Member::class,
24
    ];
25
26
    public function onBeforeWrite()
27
    {
28
        $user = Security::getCurrentUser();
29
        if (!$this->owner->ID) {
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on LeKoala\CommonExtensions\EditorTrackingExtension. Did you maybe forget to declare it?
Loading history...
30
            $this->owner->CreatedBy = $user->ID ?? 0;
0 ignored issues
show
Bug Best Practice introduced by
The property CreatedBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
31
        }
32
        $this->owner->LastEditedBy = $user->ID ?? 0;
0 ignored issues
show
Bug Best Practice introduced by
The property LastEditedBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
33
    }
34
35
    public function updateCMSFields(FieldList $fields)
36
    {
37
        $CreatedByID = $fields->dataFieldByName('CreatedByID');
38
        if ($CreatedByID) {
39
            $fields->replaceField('CreatedByID', $CreatedByID->performReadonlyTransformation());
40
        }
41
        $LastEditedByID = $fields->dataFieldByName('LastEditedByID');
42
        if ($LastEditedByID) {
43
            $fields->replaceField('LastEditedByID', $LastEditedByID->performReadonlyTransformation());
44
        }
45
    }
46
}
47