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

LDAPGroupSyncTask::run()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 76
Code Lines 41

Duplication

Lines 31
Ratio 40.79 %

Importance

Changes 0
Metric Value
dl 31
loc 76
rs 6.1941
c 0
b 0
f 0
cc 8
eloc 41
nc 6
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 SilverStripe\Control\Director;
6
use SilverStripe\Dev\BuildTask;
7
use SilverStripe\ORM\DB;
8
use SilverStripe\Security\Group;
9
10
/**
11
 * Class LDAPGroupSyncTask
12
 *
13
 * A task to sync all groups to the site using LDAP.
14
 *
15
 * @package activedirectory
16
 */
17
class LDAPGroupSyncTask extends BuildTask
18
{
19
    /**
20
     * {@inheritDoc}
21
     * @var string
22
     */
23
    private static $segment = 'LDAPGroupSyncTask';
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...
24
25
    /**
26
     * @var array
27
     */
28
    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...
29
        'ldapService' => '%$SilverStripe\\ActiveDirectory\\Services\\LDAPService'
30
    ];
31
32
    /**
33
     * Setting this to true causes the sync to delete any local Group
34
     * records that were previously imported, but no longer existing in LDAP.
35
     *
36
     * @config
37
     * @var bool
38
     */
39
    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...
40
41
    /**
42
     * @return string
43
     */
44
    public function getTitle()
45
    {
46
        return _t('LDAPGroupSyncJob.SYNCTITLE', 'Sync all groups from Active Directory');
47
    }
48
49
    /**
50
     * {@inheritDoc}
51
     * @var HTTPRequest $request
52
     */
53
    public function run($request)
54
    {
55
        // get all groups from LDAP, but only get the attributes we need.
56
        // this is useful to avoid holding onto too much data in memory
57
        // especially in the case where getGroups() would return a lot of groups
58
        $ldapGroups = $this->ldapService->getGroups(
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...
59
            false,
60
            ['objectguid', 'samaccountname', 'dn', 'name', 'description'],
61
            // Change the indexing attribute so we can look up by GUID during the deletion process below.
62
            'objectguid'
63
        );
64
65
        $start = time();
66
67
        $count = 0;
68
69 View Code Duplication
        foreach ($ldapGroups 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
            $group = Group::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
71
72
            if (!($group && $group->exists())) {
73
                // create the initial Group with some internal fields
74
                $group = new Group();
75
                $group->GUID = $data['objectguid'];
76
77
                $this->log(sprintf(
78
                    'Creating new Group (ID: %s, GUID: %s, sAMAccountName: %s)',
79
                    $group->ID,
80
                    $data['objectguid'],
81
                    $data['samaccountname']
82
                ));
83
            } else {
84
                $this->log(sprintf(
85
                    'Updating existing Group "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
86
                    $group->getTitle(),
87
                    $group->ID,
88
                    $data['objectguid'],
89
                    $data['samaccountname']
90
                ));
91
            }
92
93
            $this->ldapService->updateGroupFromLDAP($group, $data);
94
95
            // cleanup object from memory
96
            $group->destroy();
97
98
            $count++;
99
        }
100
101
        // remove Group records that were previously imported, but no longer exist in the directory
102
        // NOTE: DB::query() here is used for performance and so we don't run out of memory
103
        if ($this->config()->destructive) {
104
            foreach (DB::query('SELECT "ID", "GUID" FROM "Group" WHERE "GUID" IS NOT NULL') as $record) {
105
                if (!isset($ldapGroups[$record['GUID']])) {
106
                    $group = Group::get()->byId($record['ID']);
107
                    // Cascade into mappings, just to clean up behind ourselves.
108
                    foreach ($group->LDAPGroupMappings() as $mapping) {
109
                        $mapping->delete();
110
                    }
111
                    $group->delete();
112
113
                    $this->log(sprintf(
114
                        'Removing Group "%s" (GUID: %s) that no longer exists in LDAP.',
115
                        $group->Title,
116
                        $group->GUID
117
                    ));
118
119
                    // cleanup object from memory
120
                    $group->destroy();
121
                }
122
            }
123
        }
124
125
        $end = time() - $start;
126
127
        $this->log(sprintf('Done. Processed %s records. Duration: %s seconds', $count, round($end, 0)));
128
    }
129
130
    /**
131
     * Sends a message, formatted either for the CLI or browser
132
     *
133
     * @param string $message
134
     */
135
    protected function log($message)
136
    {
137
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
138
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
139
    }
140
}
141