Passed
Push — master ( 3c190c...2857c2 )
by Robbie
03:26
created

LDAPMemberSyncTask::run()   C

Complexity

Conditions 9
Paths 10

Size

Total Lines 84
Code Lines 51

Duplication

Lines 34
Ratio 40.48 %

Importance

Changes 0
Metric Value
cc 9
eloc 51
nc 10
nop 1
dl 34
loc 84
rs 5.4349
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\LDAP\Tasks;
4
5
use Exception;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Core\Config\Config;
9
use SilverStripe\Dev\BuildTask;
10
use SilverStripe\LDAP\Services\LDAPService;
11
use SilverStripe\ORM\DB;
12
use SilverStripe\Security\Member;
13
14
/**
15
 * Class LDAPMemberSyncTask
16
 *
17
 * A task to sync all users to the site using LDAP.
18
 */
19
class LDAPMemberSyncTask extends BuildTask
20
{
21
    /**
22
     * {@inheritDoc}
23
     * @var string
24
     */
25
    private static $segment = 'LDAPMemberSyncTask';
0 ignored issues
show
Unused Code introduced by
The property $segment 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...
26
27
    /**
28
     * @var array
29
     */
30
    private static $dependencies = [
0 ignored issues
show
Unused Code introduced by
The property $dependencies 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...
31
        'ldapService' => '%$' . LDAPService::class,
32
    ];
33
34
    /**
35
     * Setting this to true causes the sync to delete any local Member
36
     * records that were previously imported, but no longer existing in LDAP.
37
     *
38
     * @config
39
     * @var bool
40
     */
41
    private static $destructive = false;
0 ignored issues
show
Unused Code introduced by
The property $destructive 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...
42
43
    /**
44
     * @return string
45
     */
46
    public function getTitle()
47
    {
48
        return _t(__CLASS__ . '.SYNCTITLE', 'Sync all users from Active Directory');
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     * @param HTTPRequest $request
54
     */
55
    public function run($request)
56
    {
57
        // get all users from LDAP, but only get the attributes we need.
58
        // this is useful to avoid holding onto too much data in memory
59
        // especially in the case where getUser() would return a lot of users
60
        $users = $this->ldapService->getUsers(array_merge(
0 ignored issues
show
Bug Best Practice introduced by
The property ldapService does not exist on SilverStripe\LDAP\Tasks\LDAPMemberSyncTask. Did you maybe forget to declare it?
Loading history...
61
            ['objectguid', 'samaccountname', 'useraccountcontrol', 'memberof'],
62
            array_keys(Config::inst()->get('SilverStripe\\Security\\Member', 'ldap_field_mappings'))
63
        ));
64
65
        $start = time();
66
67
        $created = 0;
68
        $updated = 0;
69
        $deleted = 0;
70
71 View Code Duplication
        foreach ($users as $data) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
72
            $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
73
74
            if (!($member && $member->exists())) {
75
                // create the initial Member with some internal fields
76
                $member = new Member();
77
                $member->GUID = $data['objectguid'];
78
79
                $this->log(sprintf(
80
                    'Creating new Member (GUID: %s, sAMAccountName: %s)',
81
                    $data['objectguid'],
82
                    $data['samaccountname']
83
                ));
84
                $created++;
85
            } else {
86
                $this->log(sprintf(
87
                    'Updating existing Member "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
88
                    $member->getName(),
89
                    $member->ID,
90
                    $data['objectguid'],
91
                    $data['samaccountname']
92
                ));
93
                $updated++;
94
            }
95
96
            // Sync attributes from LDAP to the Member record. This will also write the Member record.
97
            // this is also responsible for putting the user into mapped groups
98
            try {
99
                $this->ldapService->updateMemberFromLDAP($member, $data);
100
            } catch (Exception $e) {
101
                $this->log($e->getMessage());
102
                continue;
103
            }
104
        }
105
106
        // remove Member records that were previously imported, but no longer exist in the directory
107
        // NOTE: DB::query() here is used for performance and so we don't run out of memory
108
        if ($this->config()->destructive) {
109
            foreach (DB::query('SELECT "ID", "GUID" FROM "Member" WHERE "GUID" IS NOT NULL') as $record) {
110
                $member = Member::get()->byId($record['ID']);
111
112
                if (!isset($users[$record['GUID']])) {
113
                    $this->log(sprintf(
114
                        'Removing Member "%s" (GUID: %s) that no longer exists in LDAP.',
115
                        $member->getName(),
116
                        $member->GUID
117
                    ));
118
119
                    try {
120
                        $member->delete();
121
                    } catch (Exception $e) {
122
                        $this->log($e->getMessage());
123
                        continue;
124
                    }
125
126
                    $deleted++;
127
                }
128
            }
129
        }
130
131
        $end = time() - $start;
132
133
        $this->log(sprintf(
134
            'Done. Created %s records. Updated %s records. Deleted %s records. Duration: %s seconds',
135
            $created,
136
            $updated,
137
            $deleted,
138
            round($end, 0)
139
        ));
140
    }
141
142
    /**
143
     * Sends a message, formatted either for the CLI or browser
144
     *
145
     * @param string $message
146
     */
147
    protected function log($message)
148
    {
149
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
150
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
151
    }
152
}
153