Completed
Push — master ( 197387...875417 )
by Damian
11s
created

LDAPMemberSyncTask::run()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 75
Code Lines 40

Duplication

Lines 36
Ratio 48 %

Importance

Changes 0
Metric Value
dl 36
loc 75
rs 6.2413
c 0
b 0
f 0
cc 8
eloc 40
nc 10
nop 1

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\ActiveDirectory\Tasks;
4
5
use Exception;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Core\Config\Config;
8
use SilverStripe\Dev\BuildTask;
9
use SilverStripe\ORM\DB;
10
use SilverStripe\Security\Member;
11
12
/**
13
 * Class LDAPMemberSyncTask
14
 *
15
 * A task to sync all users to the site using LDAP.
16
 *
17
 * @package activedirectory
18
 */
19
class LDAPMemberSyncTask extends BuildTask
20
{
21
    /**
22
     * {@inheritDoc}
23
     * @var string
24
     */
25
    private static $segment = 'LDAPMemberSyncTask';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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' => '%$SilverStripe\\ActiveDirectory\\Services\\LDAPService'
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('LDAPMemberSyncJob.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 introduced by
The property ldapService does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
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
        $count = 0;
68
69 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...
70
            $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
71
72
            if (!($member && $member->exists())) {
73
                // create the initial Member with some internal fields
74
                $member = new Member();
75
                $member->GUID = $data['objectguid'];
76
77
                $this->log(sprintf(
78
                    'Creating new Member (GUID: %s, sAMAccountName: %s)',
79
                    $data['objectguid'],
80
                    $data['samaccountname']
81
                ));
82
            } else {
83
                $this->log(sprintf(
84
                    'Updating existing Member "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
85
                    $member->getName(),
86
                    $member->ID,
87
                    $data['objectguid'],
88
                    $data['samaccountname']
89
                ));
90
            }
91
92
            // Sync attributes from LDAP to the Member record. This will also write the Member record.
93
            // this is also responsible for putting the user into mapped groups
94
            try {
95
                $this->ldapService->updateMemberFromLDAP($member, $data);
96
            } catch (Exception $e) {
97
                $this->log($e->getMessage());
98
            }
99
100
            // cleanup object from memory
101
            $member->destroy();
102
103
            $count++;
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
                if (!isset($users[$record['GUID']])) {
111
                    $member = Member::get()->byId($record['ID']);
112
                    $member->delete();
113
114
                    $this->log(sprintf(
115
                        'Removing Member "%s" (GUID: %s) that no longer exists in LDAP.',
116
                        $member->getName(),
117
                        $member->GUID
118
                    ));
119
120
                    // cleanup object from memory
121
                    $member->destroy();
122
                }
123
            }
124
        }
125
126
        $end = time() - $start;
127
128
        $this->log(sprintf('Done. Processed %s records. Duration: %s seconds', $count, round($end, 0)));
129
    }
130
131
    /**
132
     * Sends a message, formatted either for the CLI or browser
133
     *
134
     * @param string $message
135
     */
136
    protected function log($message)
137
    {
138
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
139
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
140
    }
141
}
142