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

LDAPGroupSyncTask::run()   C

Complexity

Conditions 10
Paths 10

Size

Total Lines 88
Code Lines 54

Duplication

Lines 32
Ratio 36.36 %

Importance

Changes 0
Metric Value
cc 10
eloc 54
nc 10
nop 1
dl 32
loc 88
rs 5.2313
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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\Dev\BuildTask;
8
use SilverStripe\LDAP\Services\LDAPService;
9
use SilverStripe\ORM\DB;
10
use SilverStripe\Security\Group;
11
12
/**
13
 * Class LDAPGroupSyncTask
14
 *
15
 * A task to sync all groups to the site using LDAP.
16
 *
17
 * @package activedirectory
18
 */
19
class LDAPGroupSyncTask extends BuildTask
20
{
21
    /**
22
     * {@inheritDoc}
23
     * @var string
24
     */
25
    private static $segment = 'LDAPGroupSyncTask';
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 Group
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 groups from Active Directory');
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     * @var HTTPRequest $request
54
     */
55
    public function run($request)
56
    {
57
        // get all groups 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 getGroups() would return a lot of groups
60
        $ldapGroups = $this->ldapService->getGroups(
0 ignored issues
show
Bug Best Practice introduced by
The property ldapService does not exist on SilverStripe\LDAP\Tasks\LDAPGroupSyncTask. Did you maybe forget to declare it?
Loading history...
61
            false,
62
            ['objectguid', 'samaccountname', 'dn', 'name', 'description'],
63
            // Change the indexing attribute so we can look up by GUID during the deletion process below.
64
            'objectguid'
65
        );
66
67
        $start = time();
68
69
        $created = 0;
70
        $updated = 0;
71
        $deleted = 0;
72
73 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...
74
            $group = Group::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
75
76
            if (!($group && $group->exists())) {
77
                // create the initial Group with some internal fields
78
                $group = new Group();
79
                $group->GUID = $data['objectguid'];
80
81
                $this->log(sprintf(
82
                    'Creating new Group (GUID: %s, sAMAccountName: %s)',
83
                    $data['objectguid'],
84
                    $data['samaccountname']
85
                ));
86
                $created++;
87
            } else {
88
                $this->log(sprintf(
89
                    'Updating existing Group "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
90
                    $group->getTitle(),
91
                    $group->ID,
92
                    $data['objectguid'],
93
                    $data['samaccountname']
94
                ));
95
                $updated++;
96
            }
97
98
            try {
99
                $this->ldapService->updateGroupFromLDAP($group, $data);
100
            } catch (Exception $e) {
101
                $this->log($e->getMessage());
102
                continue;
103
            }
104
        }
105
106
        // remove Group 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 "Group" WHERE "GUID" IS NOT NULL') as $record) {
110
                if (!isset($ldapGroups[$record['GUID']])) {
111
                    $group = Group::get()->byId($record['ID']);
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
                    try {
120
                        // Cascade into mappings, just to clean up behind ourselves.
121
                        foreach ($group->LDAPGroupMappings() as $mapping) {
122
                            $mapping->delete();
123
                        }
124
                        $group->delete();
125
                    } catch (Exception $e) {
126
                        $this->log($e->getMessage());
127
                        continue;
128
                    }
129
130
                    $deleted++;
131
                }
132
            }
133
        }
134
135
        $end = time() - $start;
136
137
        $this->log(sprintf(
138
            'Done. Created %s records. Updated %s records. Deleted %s records. Duration: %s seconds',
139
            $created,
140
            $updated,
141
            $deleted,
142
            round($end, 0)
143
        ));
144
    }
145
146
    /**
147
     * Sends a message, formatted either for the CLI or browser
148
     *
149
     * @param string $message
150
     */
151
    protected function log($message)
152
    {
153
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
154
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
155
    }
156
}
157