LDAPMemberExtension   A
last analyzed

Complexity

Total Complexity 33

Size/Duplication

Total Lines 242
Duplicated Lines 14.05 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 33
lcom 1
cbo 9
dl 34
loc 242
rs 9.76
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B updateCMSFields() 0 50 8
A validate() 0 17 4
A onBeforeWrite() 18 18 6
A onAfterWrite() 0 11 3
A onAfterDelete() 16 16 5
A writeWithoutSync() 0 10 2
A sync() 0 11 3
A memberLoggedIn() 0 6 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Class LDAPMemberExtension.
4
 *
5
 * Adds mappings from AD attributes to SilverStripe {@link Member} fields.
6
 */
7
class LDAPMemberExtension extends DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
{
9
    /**
10
     * @var array
11
     */
12
    private static $db = [
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
        // Unique user identifier, same field is used by SAMLMemberExtension
14
        'GUID' => 'Varchar(50)',
15
        'Username' => 'Varchar(64)',
16
        'IsExpired' => 'Boolean',
17
        'LastSynced' => 'SS_Datetime',
18
    ];
19
20
    /**
21
     * These fields are used by {@link LDAPMemberSync} to map specific AD attributes
22
     * to {@link Member} fields.
23
     *
24
     * @var array
25
     * @config
26
     */
27
    private static $ldap_field_mappings = [
0 ignored issues
show
Unused Code introduced by
The property $ldap_field_mappings is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        'givenname' => 'FirstName',
29
        'samaccountname' => 'Username',
30
        'sn' => 'Surname',
31
        'mail' => 'Email',
32
    ];
33
34
    /**
35
     * The location (relative to /assets) where to save thumbnailphoto data.
36
     *
37
     * @var string
38
     * @config
39
     */
40
    private static $ldap_thumbnail_path = 'Uploads';
0 ignored issues
show
Unused Code introduced by
The property $ldap_thumbnail_path is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
41
42
    /**
43
     * When enabled, LDAP managed Member records (GUID flag)
44
     * have their data written back to LDAP on write, and synchronise
45
     * membership to groups mapped to LDAP.
46
     *
47
     * Keep in mind this will currently NOT trigger if there are no
48
     * field changes due to onAfterWrite in framework not being called
49
     * when there are no changes.
50
     *
51
     * This requires setting write permissions on the user configured in the LDAP
52
     * credentials, which is why this is disabled by default.
53
     *
54
     * @var bool
55
     * @config
56
     */
57
    private static $update_ldap_from_local = false;
0 ignored issues
show
Unused Code introduced by
The property $update_ldap_from_local is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
58
59
    /**
60
     * If enabled, Member records with a Username field have the user created in LDAP
61
     * on write.
62
     *
63
     * This requires setting write permissions on the user configured in the LDAP
64
     * credentials, which is why this is disabled by default.
65
     *
66
     * @var bool
67
     * @config
68
     */
69
    private static $create_users_in_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $create_users_in_ldap is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
70
71
    /**
72
     * If enabled, deleting Member records mapped to LDAP deletes the LDAP user.
73
     *
74
     * This requires setting write permissions on the user configured in the LDAP
75
     * credentials, which is why this is disabled by default.
76
     *
77
     * @var bool
78
     * @config
79
     */
80
    private static $delete_users_in_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $delete_users_in_ldap is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
81
82
    /**
83
     * @param FieldList $fields
84
     */
85
    public function updateCMSFields(FieldList $fields)
86
    {
87
        // Redo LDAP metadata fields as read-only and move to LDAP tab.
88
        $ldapMetadata = [];
89
        $fields->replaceField('GUID', $ldapMetadata[] = new ReadonlyField('GUID'));
90
        $fields->replaceField('IsExpired', $ldapMetadata[] = new ReadonlyField(
91
            'IsExpired',
92
            _t('LDAPMemberExtension.ISEXPIRED', 'Has user\'s LDAP/AD login expired?'))
93
        );
94
        $fields->replaceField('LastSynced', $ldapMetadata[] = new ReadonlyField(
95
            'LastSynced',
96
            _t('LDAPMemberExtension.LASTSYNCED', 'Last synced'))
97
        );
98
        $fields->addFieldsToTab('Root.LDAP', $ldapMetadata);
99
100
        $message = '';
101
        if ($this->owner->GUID && $this->owner->config()->update_ldap_from_local) {
102
            $message = _t(
103
                'LDAPMemberExtension.CHANGEFIELDSUPDATELDAP',
104
                'Changing fields here will update them in LDAP.'
105
            );
106
        } elseif ($this->owner->GUID && !$this->owner->config()->update_ldap_from_local) {
0 ignored issues
show
Bug introduced by
The property GUID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
107
            // Transform the automatically mapped fields into read-only. This doesn't
108
            // apply if updating LDAP from local is enabled, as changing data locally can be written back.
109
            foreach ($this->owner->config()->ldap_field_mappings as $name) {
110
                $field = $fields->dataFieldByName($name);
111
                if (!empty($field)) {
112
                    // Set to readonly, but not disabled so that the data is still sent to the
113
                    // server and doesn't break Member_Validator
114
                    $field->setReadonly(true);
115
                    $field->setTitle($field->Title()._t('LDAPMemberExtension.IMPORTEDFIELD', ' (imported)'));
116
                }
117
            }
118
            $message = _t(
119
                'LDAPMemberExtension.INFOIMPORTED',
120
                'This user is automatically imported from LDAP. '.
121
                    'Manual changes to imported fields will be removed upon sync.'
122
            );
123
        }
124
        if ($message) {
125
            $fields->addFieldToTab(
126
                'Root.Main',
127
                new LiteralField(
128
                    'Info',
129
                    sprintf('<p class="message warning">%s</p>', $message)
130
                ),
131
                'FirstName'
132
            );
133
        }
134
    }
135
136
    public function validate(ValidationResult $validationResult)
137
    {
138
        // We allow empty Username for registration purposes, as we need to
139
        // create Member records with empty Username temporarily. Forms should explicitly
140
        // check for Username not being empty if they require it not to be.
141
        if (empty($this->owner->Username) || !$this->owner->config()->create_users_in_ldap) {
0 ignored issues
show
Bug introduced by
The property Username does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
142
            return;
143
        }
144
145
        if (!preg_match('/^[a-z0-9\.]+$/', $this->owner->Username)) {
146
            $validationResult->error(
147
                'Username must only contain lowercase alphanumeric characters and dots.',
148
                'bad'
149
            );
150
            throw new ValidationException($validationResult);
151
        }
152
    }
153
154
    /**
155
     * Create the user in LDAP, provided this configuration is enabled
156
     * and a username was passed to a new Member record.
157
     */
158 View Code Duplication
    public function onBeforeWrite()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
    {
160
        if ($this->owner->LDAPMemberExtension_NoSync) {
0 ignored issues
show
Bug introduced by
The property LDAPMemberExtension_NoSync does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
161
            return;
162
        }
163
164
        $service = Injector::inst()->get('LDAPService');
165
        if (
166
            !$service->enabled() ||
167
            !$this->owner->config()->create_users_in_ldap ||
168
            !$this->owner->Username ||
0 ignored issues
show
Bug introduced by
The property Username does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
169
            $this->owner->GUID
0 ignored issues
show
Bug introduced by
The property GUID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
170
        ) {
171
            return;
172
        }
173
174
        $service->createLDAPUser($this->owner);
175
    }
176
177
    public function onAfterWrite()
178
    {
179
        if ($this->owner->LDAPMemberExtension_NoSync) {
0 ignored issues
show
Bug introduced by
The property LDAPMemberExtension_NoSync does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
180
            return;
181
        }
182
183
        if (!$this->owner->config()->update_ldap_from_local) {
184
            return;
185
        }
186
        $this->sync();
187
    }
188
189 View Code Duplication
    public function onAfterDelete() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
        if ($this->owner->LDAPMemberExtension_NoSync) {
0 ignored issues
show
Bug introduced by
The property LDAPMemberExtension_NoSync does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
191
            return;
192
        }
193
194
        $service = Injector::inst()->get('LDAPService');
195
        if (
196
            !$service->enabled() ||
197
            !$this->owner->config()->delete_users_in_ldap ||
198
            !$this->owner->GUID
0 ignored issues
show
Bug introduced by
The property GUID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
199
        ) {
200
            return;
201
        }
202
203
        $service->deleteLDAPMember($this->owner);
204
    }
205
206
    /**
207
     * Write DataObject without triggering this extension's hooks.
208
     *
209
     * @throws Exception
210
     */
211
    public function writeWithoutSync() {
212
        $this->owner->LDAPMemberExtension_NoSync = true;
0 ignored issues
show
Bug introduced by
The property LDAPMemberExtension_NoSync does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
213
        try {
214
            $this->owner->write();
215
        } catch (Exception $e) {
216
            $this->owner->LDAPMemberExtension_NoSync = false;
217
            throw $e;
218
        }
219
        $this->owner->LDAPMemberExtension_NoSync = false;
220
    }
221
222
    /**
223
     * Update the local data with LDAP, and ensure local membership is also set in
224
     * LDAP too. This writes into LDAP, provided that feature is enabled.
225
     */
226
    public function sync() {
227
        $service = Injector::inst()->get('LDAPService');
228
        if (
229
            !$service->enabled() ||
230
            !$this->owner->GUID
0 ignored issues
show
Bug introduced by
The property GUID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
231
        ) {
232
            return;
233
        }
234
        $service->updateLDAPFromMember($this->owner);
235
        $service->updateLDAPGroupsForMember($this->owner);
236
    }
237
238
    /**
239
     * Triggered by {@link Member::logIn()} when successfully logged in,
240
     * this will update the Member record from AD data.
241
     */
242
    public function memberLoggedIn()
243
    {
244
        if ($this->owner->GUID) {
0 ignored issues
show
Bug introduced by
The property GUID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
245
            Injector::inst()->get('LDAPService')->updateMemberFromLDAP($this->owner);
246
        }
247
    }
248
}
249